demux_lavf: mark AVI timestamps non-pts to avoid messages
[mplayer/glamo.git] / mplayer.c
blob2acd7e672effdc0aff2e3c17fe554043b3864713
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 enable_mouse_movements=0;
104 float start_volume = -1;
106 #include "osdep/priority.h"
108 char *heartbeat_cmd;
110 #define ROUND(x) ((int)((x)<0 ? (x)-0.5 : (x)+0.5))
112 #ifdef HAVE_RTC
113 #ifdef __linux__
114 #include <linux/rtc.h>
115 #else
116 #include <rtc.h>
117 #define RTC_IRQP_SET RTCIO_IRQP_SET
118 #define RTC_PIE_ON RTCIO_PIE_ON
119 #endif /* __linux__ */
120 #endif /* HAVE_RTC */
122 #include "stream/tv.h"
123 #include "stream/stream_radio.h"
124 #ifdef CONFIG_DVBIN
125 #include "stream/dvbin.h"
126 #endif
127 #include "stream/cache2.h"
129 //**************************************************************************//
130 // Playtree
131 //**************************************************************************//
132 #include "playtree.h"
133 #include "playtreeparser.h"
135 //**************************************************************************//
136 // Config
137 //**************************************************************************//
138 #include "parser-cfg.h"
139 #include "parser-mpcmd.h"
141 //**************************************************************************//
142 // Config file
143 //**************************************************************************//
145 static int cfg_inc_verbose(m_option_t *conf){ ++verbose; return 0;}
147 #include "path.h"
149 //**************************************************************************//
150 //**************************************************************************//
151 // Input media streaming & demultiplexer:
152 //**************************************************************************//
154 static int max_framesize=0;
156 #include "stream/stream.h"
157 #include "libmpdemux/demuxer.h"
158 #include "libmpdemux/stheader.h"
160 #ifdef CONFIG_DVDREAD
161 #include "stream/stream_dvd.h"
162 #endif
163 #include "stream/stream_dvdnav.h"
165 #include "libmpcodecs/dec_audio.h"
166 #include "libmpcodecs/dec_video.h"
167 #include "libmpcodecs/mp_image.h"
168 #include "libmpcodecs/vf.h"
169 #include "libmpcodecs/vd.h"
171 #include "mixer.h"
173 #include "mp_core.h"
174 #include "options.h"
175 #include "defaultopts.h"
177 static const char help_text[]=_(
178 "Usage: mplayer [options] [url|path/]filename\n"
179 "\n"
180 "Basic options: (complete list in the man page)\n"
181 " -vo <drv> select video output driver ('-vo help' for a list)\n"
182 " -ao <drv> select audio output driver ('-ao help' for a list)\n"
183 #ifdef CONFIG_VCD
184 " vcd://<trackno> play (S)VCD (Super Video CD) track (raw device, no mount)\n"
185 #endif
186 #ifdef CONFIG_DVDREAD
187 " dvd://<titleno> play DVD title from device instead of plain file\n"
188 #endif
189 " -alang/-slang select DVD audio/subtitle language (by 2-char country code)\n"
190 " -ss <position> seek to given (seconds or hh:mm:ss) position\n"
191 " -nosound do not play sound\n"
192 " -fs fullscreen playback (or -vm, -zoom, details in the man page)\n"
193 " -x <x> -y <y> set display resolution (for use with -vm or -zoom)\n"
194 " -sub <file> specify subtitle file to use (also see -subfps, -subdelay)\n"
195 " -playlist <file> specify playlist file\n"
196 " -vid x -aid y select video (x) and audio (y) stream to play\n"
197 " -fps x -srate y change video (x fps) and audio (y Hz) rate\n"
198 " -pp <quality> enable postprocessing filter (details in the man page)\n"
199 " -framedrop enable frame dropping (for slow machines)\n"
200 "\n"
201 "Basic keys: (complete list in the man page, also check input.conf)\n"
202 " <- or -> seek backward/forward 10 seconds\n"
203 " down or up seek backward/forward 1 minute\n"
204 " pgdown or pgup seek backward/forward 10 minutes\n"
205 " < or > step backward/forward in playlist\n"
206 " p or SPACE pause movie (press any key to continue)\n"
207 " q or ESC stop playing and quit program\n"
208 " + or - adjust audio delay by +/- 0.1 second\n"
209 " o cycle OSD mode: none / seekbar / seekbar + timer\n"
210 " * or / increase or decrease PCM volume\n"
211 " x or z adjust subtitle delay by +/- 0.1 second\n"
212 " r or t adjust subtitle position up/down, also see -vf expand\n"
213 "\n"
214 " * * * SEE THE MAN PAGE FOR DETAILS, FURTHER (ADVANCED) OPTIONS AND KEYS * * *\n"
215 "\n");
218 #define Exit_SIGILL_RTCpuSel _(\
219 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
220 " It may be a bug in our new runtime CPU-detection code...\n"\
221 " Please read DOCS/HTML/en/bugreports.html.\n")
223 #define Exit_SIGILL _(\
224 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
225 " It usually happens when you run it on a CPU different than the one it was\n"\
226 " compiled/optimized for.\n"\
227 " Verify this!\n")
229 #define Exit_SIGSEGV_SIGFPE _(\
230 "- MPlayer crashed by bad usage of CPU/FPU/RAM.\n"\
231 " Recompile MPlayer with --enable-debug and make a 'gdb' backtrace and\n"\
232 " disassembly. Details in DOCS/HTML/en/bugreports_what.html#bugreports_crash.\n")
234 #define Exit_SIGCRASH _(\
235 "- MPlayer crashed. This shouldn't happen.\n"\
236 " It can be a bug in the MPlayer code _or_ in your drivers _or_ in your\n"\
237 " gcc version. If you think it's MPlayer's fault, please read\n"\
238 " DOCS/HTML/en/bugreports.html and follow the instructions there. We can't and\n"\
239 " won't help unless you provide this information when reporting a possible bug.\n")
241 #define SystemTooSlow _("\n\n"\
242 " ************************************************\n"\
243 " **** Your system is too SLOW to play this! ****\n"\
244 " ************************************************\n\n"\
245 "Possible reasons, problems, workarounds:\n"\
246 "- Most common: broken/buggy _audio_ driver\n"\
247 " - Try -ao sdl or use the OSS emulation of ALSA.\n"\
248 " - Experiment with different values for -autosync, 30 is a good start.\n"\
249 "- Slow video output\n"\
250 " - Try a different -vo driver (-vo help for a list) or try -framedrop!\n"\
251 "- Slow CPU\n"\
252 " - Don't try to play a big DVD/DivX on a slow CPU! Try some of the lavdopts,\n"\
253 " e.g. -vfm ffmpeg -lavdopts lowres=1:fast:skiploopfilter=all.\n"\
254 "- Broken file\n"\
255 " - Try various combinations of -nobps -ni -forceidx -mc 0.\n"\
256 "- Slow media (NFS/SMB mounts, DVD, VCD etc)\n"\
257 " - Try -cache 8192.\n"\
258 "- Are you using -cache to play a non-interleaved AVI file?\n"\
259 " - Try -nocache.\n"\
260 "Read DOCS/HTML/en/video.html for tuning/speedup tips.\n"\
261 "If none of this helps you, read DOCS/HTML/en/bugreports.html.\n\n")
264 //**************************************************************************//
265 //**************************************************************************//
267 #include "mp_fifo.h"
269 // benchmark:
270 double video_time_usage=0;
271 double vout_time_usage=0;
272 static double audio_time_usage=0;
273 static int total_time_usage_start=0;
274 static int total_frame_cnt=0;
275 static int drop_frame_cnt=0; // total number of dropped frames
277 // options:
278 static int output_quality=0;
280 // seek:
281 static double seek_to_sec;
282 static off_t seek_to_byte=0;
283 static off_t step_sec=0;
285 static m_time_size_t end_at = { .type = END_AT_NONE, .pos = 0 };
287 // codecs:
288 char **audio_codec_list=NULL; // override audio codec
289 char **video_codec_list=NULL; // override video codec
290 char **audio_fm_list=NULL; // override audio codec family
291 char **video_fm_list=NULL; // override video codec family
293 // this dvdsub_id was selected via slang
294 // use this to allow dvdnav to follow -slang across stream resets,
295 // in particular the subtitle ID for a language changes
296 int dvdsub_lang_id;
297 int vobsub_id=-1;
298 static char* spudec_ifo=NULL;
299 int forced_subs_only=0;
300 int file_filter=1;
302 // cache2:
303 int stream_cache_size=-1;
305 // dump:
306 int stream_dump_type=0;
308 // A-V sync:
309 static float default_max_pts_correction=-1;//0.01f;
310 float audio_delay=0;
311 static int ignore_start=0;
313 double force_fps=0;
314 static int force_srate=0;
315 int frame_dropping=0; // option 0=no drop 1= drop vo 2= drop decode
316 static int play_n_frames=-1;
317 static int play_n_frames_mf=-1;
319 // sub:
320 char *font_name=NULL;
321 char *sub_font_name=NULL;
322 extern int font_fontconfig;
323 float font_factor=0.75;
324 char **sub_name=NULL;
325 float sub_delay=0;
326 float sub_fps=0;
327 int sub_auto = 1;
328 char *vobsub_name=NULL;
329 int subcc_enabled=0;
330 int suboverlap_enabled = 1;
332 #include "ass_mp.h"
334 char* current_module=NULL; // for debugging
337 // ---
339 #ifdef CONFIG_MENU
340 #include "m_struct.h"
341 #include "libmenu/menu.h"
342 static const vf_info_t* const libmenu_vfs[] = {
343 &vf_info_menu,
344 NULL
346 static vf_instance_t* vf_menu = NULL;
347 int use_menu = 0;
348 static char* menu_cfg = NULL;
349 static char* menu_root = "main";
350 #endif
353 edl_record_ptr edl_records = NULL; ///< EDL entries memory area
354 edl_record_ptr next_edl_record = NULL; ///< only for traversing edl_records
355 FILE* edl_fd = NULL; ///< fd to write to when in -edlout mode.
356 int use_filedir_conf;
357 int use_filename_title;
359 #include "mpcommon.h"
360 #include "command.h"
362 #include "metadata.h"
364 #define mp_basename2(s) (strrchr(s,'/')==NULL?(char*)s:(strrchr(s,'/')+1))
366 const void *mpctx_get_video_out(MPContext *mpctx)
368 return mpctx->video_out;
371 const void *mpctx_get_audio_out(MPContext *mpctx)
373 return mpctx->audio_out;
376 void *mpctx_get_demuxer(MPContext *mpctx)
378 return mpctx->demuxer;
381 void *mpctx_get_playtree_iter(MPContext *mpctx)
383 return mpctx->playtree_iter;
386 void *mpctx_get_mixer(MPContext *mpctx)
388 return &mpctx->mixer;
391 int mpctx_get_global_sub_size(MPContext *mpctx)
393 return mpctx->global_sub_size;
396 int mpctx_get_osd_function(MPContext *mpctx)
398 return mpctx->osd_function;
401 static float get_relative_time(struct MPContext *mpctx)
403 unsigned int new_time = GetTimer();
404 unsigned int delta = new_time - mpctx->last_time;
405 mpctx->last_time = new_time;
406 return delta * 0.000001;
409 static int is_valid_metadata_type(struct MPContext *mpctx, metadata_t type) {
410 switch (type)
412 /* check for valid video stream */
413 case META_VIDEO_CODEC:
414 case META_VIDEO_BITRATE:
415 case META_VIDEO_RESOLUTION:
417 if (!mpctx->sh_video)
418 return 0;
419 break;
422 /* check for valid audio stream */
423 case META_AUDIO_CODEC:
424 case META_AUDIO_BITRATE:
425 case META_AUDIO_SAMPLES:
427 if (!mpctx->sh_audio)
428 return 0;
429 break;
432 /* check for valid demuxer */
433 case META_INFO_TITLE:
434 case META_INFO_ARTIST:
435 case META_INFO_ALBUM:
436 case META_INFO_YEAR:
437 case META_INFO_COMMENT:
438 case META_INFO_TRACK:
439 case META_INFO_GENRE:
441 if (!mpctx->demuxer)
442 return 0;
443 break;
446 default:
447 break;
450 return 1;
453 static char *get_demuxer_info(struct MPContext *mpctx, char *tag) {
454 char **info = mpctx->demuxer->info;
455 int n;
457 if (!info || !tag)
458 return NULL;
460 for (n = 0; info[2*n] != NULL ; n++)
461 if (!strcasecmp (info[2*n], tag))
462 break;
464 return info[2*n+1] ? strdup (info[2*n+1]) : NULL;
467 char *get_metadata(struct MPContext *mpctx, metadata_t type)
469 char *meta = NULL;
470 sh_audio_t * const sh_audio = mpctx->sh_audio;
471 sh_video_t * const sh_video = mpctx->sh_video;
473 if (!is_valid_metadata_type(mpctx, type))
474 return NULL;
476 switch (type)
478 case META_NAME:
480 return strdup (mp_basename2 (mpctx->filename));
483 case META_VIDEO_CODEC:
485 if (sh_video->format == 0x10000001)
486 meta = strdup ("mpeg1");
487 else if (sh_video->format == 0x10000002)
488 meta = strdup ("mpeg2");
489 else if (sh_video->format == 0x10000004)
490 meta = strdup ("mpeg4");
491 else if (sh_video->format == 0x10000005)
492 meta = strdup ("h264");
493 else if (sh_video->format >= 0x20202020)
495 meta = malloc (8);
496 sprintf (meta, "%.4s", (char *) &sh_video->format);
498 else
500 meta = malloc (8);
501 sprintf (meta, "0x%08X", sh_video->format);
503 return meta;
506 case META_VIDEO_BITRATE:
508 meta = malloc (16);
509 sprintf (meta, "%d kbps", (int) (sh_video->i_bps * 8 / 1024));
510 return meta;
513 case META_VIDEO_RESOLUTION:
515 meta = malloc (16);
516 sprintf (meta, "%d x %d", sh_video->disp_w, sh_video->disp_h);
517 return meta;
520 case META_AUDIO_CODEC:
522 if (sh_audio->codec && sh_audio->codec->name)
523 meta = strdup (sh_audio->codec->name);
524 return meta;
527 case META_AUDIO_BITRATE:
529 meta = malloc (16);
530 sprintf (meta, "%d kbps", (int) (sh_audio->i_bps * 8/1000));
531 return meta;
534 case META_AUDIO_SAMPLES:
536 meta = malloc (16);
537 sprintf (meta, "%d Hz, %d ch.", sh_audio->samplerate, sh_audio->channels);
538 return meta;
541 /* check for valid demuxer */
542 case META_INFO_TITLE:
543 return get_demuxer_info(mpctx, "Title");
545 case META_INFO_ARTIST:
546 return get_demuxer_info(mpctx, "Artist");
548 case META_INFO_ALBUM:
549 return get_demuxer_info(mpctx, "Album");
551 case META_INFO_YEAR:
552 return get_demuxer_info(mpctx, "Year");
554 case META_INFO_COMMENT:
555 return get_demuxer_info(mpctx, "Comment");
557 case META_INFO_TRACK:
558 return get_demuxer_info(mpctx, "Track");
560 case META_INFO_GENRE:
561 return get_demuxer_info(mpctx, "Genre");
563 default:
564 break;
567 return meta;
570 static void print_file_properties(struct MPContext *mpctx, const char *filename)
572 double start_pts = MP_NOPTS_VALUE;
573 double video_start_pts = MP_NOPTS_VALUE;
574 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_FILENAME=%s\n",
575 filename_recode(filename));
576 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_DEMUXER=%s\n", mpctx->demuxer->desc->name);
577 if (mpctx->sh_video) {
578 /* Assume FOURCC if all bytes >= 0x20 (' ') */
579 if (mpctx->sh_video->format >= 0x20202020)
580 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=%.4s\n", (char *)&mpctx->sh_video->format);
581 else
582 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=0x%08X\n", mpctx->sh_video->format);
583 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_BITRATE=%d\n", mpctx->sh_video->i_bps*8);
584 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_WIDTH=%d\n", mpctx->sh_video->disp_w);
585 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_HEIGHT=%d\n", mpctx->sh_video->disp_h);
586 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FPS=%5.3f\n", mpctx->sh_video->fps);
587 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_ASPECT=%1.4f\n", mpctx->sh_video->aspect);
588 video_start_pts = ds_get_next_pts(mpctx->d_video);
590 if (mpctx->sh_audio) {
591 /* Assume FOURCC if all bytes >= 0x20 (' ') */
592 if (mpctx->sh_audio->format >= 0x20202020)
593 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_FORMAT=%.4s\n", (char *)&mpctx->sh_audio->format);
594 else
595 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_FORMAT=%d\n", mpctx->sh_audio->format);
596 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_BITRATE=%d\n", mpctx->sh_audio->i_bps*8);
597 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_RATE=%d\n", mpctx->sh_audio->samplerate);
598 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_NCH=%d\n", mpctx->sh_audio->channels);
599 start_pts = ds_get_next_pts(mpctx->d_audio);
601 if (video_start_pts != MP_NOPTS_VALUE) {
602 if (start_pts == MP_NOPTS_VALUE || !mpctx->sh_audio ||
603 (mpctx->sh_video && video_start_pts < start_pts))
604 start_pts = video_start_pts;
606 if (start_pts != MP_NOPTS_VALUE)
607 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_START_TIME=%.2f\n", start_pts);
608 else
609 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_START_TIME=unknown\n");
610 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_LENGTH=%.2f\n", get_time_length(mpctx));
611 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_SEEKABLE=%d\n",
612 mpctx->stream->seek && (!mpctx->demuxer || mpctx->demuxer->seekable));
613 if (mpctx->demuxer) {
614 if (mpctx->demuxer->num_chapters == 0)
615 stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_NUM_CHAPTERS, &mpctx->demuxer->num_chapters);
616 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_CHAPTERS=%d\n", mpctx->demuxer->num_chapters);
620 /// step size of mixer changes
621 int volstep = 3;
623 #ifdef CONFIG_DVDNAV
624 static void mp_dvdnav_context_free(MPContext *ctx){
625 if (ctx->nav_smpi) free_mp_image(ctx->nav_smpi);
626 ctx->nav_smpi = NULL;
627 free(ctx->nav_buffer);
628 ctx->nav_buffer = NULL;
629 ctx->nav_start = NULL;
630 ctx->nav_in_size = 0;
632 #endif
634 void uninit_player(struct MPContext *mpctx, unsigned int mask){
635 mask &= mpctx->initialized_flags;
637 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n*** uninit(0x%X)\n",mask);
639 if(mask&INITIALIZED_ACODEC){
640 mpctx->initialized_flags&=~INITIALIZED_ACODEC;
641 current_module="uninit_acodec";
642 if(mpctx->sh_audio) uninit_audio(mpctx->sh_audio);
643 mpctx->sh_audio=NULL;
644 mpctx->mixer.afilter = NULL;
647 if(mask&INITIALIZED_VCODEC){
648 mpctx->initialized_flags&=~INITIALIZED_VCODEC;
649 current_module="uninit_vcodec";
650 if(mpctx->sh_video) uninit_video(mpctx->sh_video);
651 mpctx->sh_video=NULL;
652 #ifdef CONFIG_MENU
653 vf_menu=NULL;
654 #endif
657 if(mask&INITIALIZED_DEMUXER){
658 mpctx->initialized_flags&=~INITIALIZED_DEMUXER;
659 current_module="free_demuxer";
660 if (mpctx->num_sources) {
661 mpctx->demuxer = mpctx->sources[0].demuxer;
662 for (int i = 1; i < mpctx->num_sources; i++) {
663 free_stream(mpctx->sources[i].stream);
664 free_demuxer(mpctx->sources[i].demuxer);
667 talloc_free(mpctx->sources);
668 mpctx->sources = NULL;
669 mpctx->num_sources = 0;
670 talloc_free(mpctx->timeline);
671 mpctx->timeline = NULL;
672 mpctx->num_timeline_parts = 0;
673 talloc_free(mpctx->chapters);
674 mpctx->chapters = NULL;
675 mpctx->num_chapters = 0;
676 mpctx->video_offset = 0;
677 if(mpctx->demuxer){
678 mpctx->stream=mpctx->demuxer->stream;
679 free_demuxer(mpctx->demuxer);
681 mpctx->demuxer=NULL;
684 // kill the cache process:
685 if(mask&INITIALIZED_STREAM){
686 mpctx->initialized_flags&=~INITIALIZED_STREAM;
687 current_module="uninit_stream";
688 if(mpctx->stream) free_stream(mpctx->stream);
689 mpctx->stream=NULL;
692 if(mask&INITIALIZED_VO){
693 mpctx->initialized_flags&=~INITIALIZED_VO;
694 current_module="uninit_vo";
695 vo_destroy(mpctx->video_out);
696 mpctx->video_out=NULL;
697 #ifdef CONFIG_DVDNAV
698 mp_dvdnav_context_free(mpctx);
699 #endif
702 // Must be after libvo uninit, as few vo drivers (svgalib) have tty code.
703 if(mask&INITIALIZED_GETCH2){
704 mpctx->initialized_flags&=~INITIALIZED_GETCH2;
705 current_module="uninit_getch2";
706 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[uninit getch2]]]\n");
707 // restore terminal:
708 getch2_disable();
711 if(mask&INITIALIZED_VOBSUB){
712 mpctx->initialized_flags&=~INITIALIZED_VOBSUB;
713 current_module="uninit_vobsub";
714 if(vo_vobsub) vobsub_close(vo_vobsub);
715 vo_vobsub=NULL;
718 if (mask&INITIALIZED_SPUDEC){
719 mpctx->initialized_flags&=~INITIALIZED_SPUDEC;
720 current_module="uninit_spudec";
721 spudec_free(vo_spudec);
722 vo_spudec=NULL;
725 if(mask&INITIALIZED_AO){
726 mpctx->initialized_flags&=~INITIALIZED_AO;
727 current_module="uninit_ao";
728 if (mpctx->edl_muted) mixer_mute(&mpctx->mixer);
729 if (mpctx->audio_out)
730 mpctx->audio_out->uninit(mpctx->stop_play != AT_END_OF_FILE);
731 mpctx->audio_out=NULL;
734 current_module=NULL;
737 void exit_player_with_rc(struct MPContext *mpctx, enum exit_reason how, int rc)
739 if (mpctx->user_muted && !mpctx->edl_muted) mixer_mute(&mpctx->mixer);
740 uninit_player(mpctx, INITIALIZED_ALL);
741 #if defined(__MINGW32__) || defined(__CYGWIN__)
742 timeEndPeriod(1);
743 #endif
744 #ifdef CONFIG_X11
745 vo_uninit(mpctx->x11_state); // Close the X11 connection (if any is open).
746 #endif
748 current_module="uninit_input";
749 mp_input_uninit(mpctx->input);
750 #ifdef CONFIG_MENU
751 if (use_menu)
752 menu_uninit();
753 #endif
755 #ifdef CONFIG_FREETYPE
756 current_module="uninit_font";
757 if (mpctx->osd && mpctx->osd->sub_font != vo_font)
758 free_font_desc(mpctx->osd->sub_font);
759 free_font_desc(vo_font);
760 vo_font = NULL;
761 done_freetype();
762 #endif
763 osd_free(mpctx->osd);
765 #ifdef CONFIG_ASS
766 ass_library_done(ass_library);
767 ass_library = NULL;
768 #endif
770 current_module="exit_player";
772 // free mplayer config
773 if(mpctx->mconfig)
774 m_config_free(mpctx->mconfig);
775 mpctx->mconfig = NULL;
777 if(mpctx->playtree_iter)
778 play_tree_iter_free(mpctx->playtree_iter);
779 mpctx->playtree_iter = NULL;
780 if(mpctx->playtree)
781 play_tree_free(mpctx->playtree, 1);
782 mpctx->playtree = NULL;
784 talloc_free(mpctx->key_fifo);
786 free(edl_records); // free mem allocated for EDL
787 edl_records = NULL;
788 switch(how) {
789 case EXIT_QUIT:
790 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Quit");
791 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=QUIT\n");
792 break;
793 case EXIT_EOF:
794 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","End of file");
795 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=EOF\n");
796 break;
797 case EXIT_ERROR:
798 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Fatal error");
799 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=ERROR\n");
800 break;
801 default:
802 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=NONE\n");
804 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"max framesize was %d bytes\n",max_framesize);
806 exit(rc);
809 static void exit_player(struct MPContext *mpctx, enum exit_reason how)
811 exit_player_with_rc(mpctx, how, 1);
814 #ifndef __MINGW32__
815 static void child_sighandler(int x){
816 pid_t pid;
817 while((pid=waitpid(-1,NULL,WNOHANG)) > 0);
819 #endif
821 #ifdef CONFIG_CRASH_DEBUG
822 static char *prog_path;
823 static int crash_debug = 0;
824 #endif
826 static void exit_sighandler(int x){
827 static int sig_count=0;
828 #ifdef CONFIG_CRASH_DEBUG
829 if (!crash_debug || x != SIGTRAP)
830 #endif
831 ++sig_count;
832 if(sig_count==5)
834 /* We're crashing bad and can't uninit cleanly :(
835 * by popular request, we make one last (dirty)
836 * effort to restore the user's
837 * terminal. */
838 getch2_disable();
839 exit(1);
841 if(sig_count==6) exit(1);
842 if(sig_count>6){
843 // can't stop :(
844 #ifndef __MINGW32__
845 kill(getpid(),SIGKILL);
846 #endif
848 mp_msg(MSGT_CPLAYER, MSGL_FATAL, "\n");
849 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,
850 "\nMPlayer interrupted by signal %d in module: %s\n", x,
851 current_module ? current_module : "unknown");
852 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SIGNAL=%d\n", x);
853 if(sig_count<=1)
854 switch(x){
855 case SIGINT:
856 case SIGPIPE:
857 case SIGQUIT:
858 case SIGTERM:
859 case SIGKILL:
860 async_quit_request = 1;
861 return; // killed from keyboard (^C) or killed [-9]
862 case SIGILL:
863 #if CONFIG_RUNTIME_CPUDETECT
864 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL_RTCpuSel);
865 #else
866 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL);
867 #endif
868 case SIGFPE:
869 case SIGSEGV:
870 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGSEGV_SIGFPE);
871 default:
872 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGCRASH);
873 #ifdef CONFIG_CRASH_DEBUG
874 if (crash_debug) {
875 int gdb_pid;
876 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forking...\n");
877 gdb_pid = fork();
878 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forked...\n");
879 if (gdb_pid == 0) { // We are the child
880 char spid[20];
881 snprintf(spid, sizeof(spid), "%i", getppid());
882 getch2_disable(); // allow terminal to work properly with gdb
883 if (execlp("gdb", "gdb", prog_path, spid, "-ex", "bt", NULL) == -1)
884 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't start gdb\n");
885 } else if (gdb_pid < 0)
886 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't fork\n");
887 else {
888 waitpid(gdb_pid, NULL, 0);
890 if (x == SIGTRAP) return;
892 #endif
894 getch2_disable();
895 exit(1);
898 #include "cfg-mplayer.h"
900 static int cfg_include(m_option_t *conf, char *filename)
902 return m_config_parse_config_file(conf->priv, filename);
905 static void parse_cfgfiles(struct MPContext *mpctx, m_config_t* conf)
907 char *conffile;
908 int conffile_fd;
909 if (!disable_system_conf &&
910 m_config_parse_config_file(conf, MPLAYER_CONFDIR "/mplayer.conf") < 0)
911 exit_player(mpctx, EXIT_NONE);
912 if ((conffile = get_path("")) == NULL) {
913 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"Cannot find HOME directory.\n");
914 } else {
915 #ifdef __MINGW32__
916 mkdir(conffile);
917 #else
918 mkdir(conffile, 0777);
919 #endif
920 free(conffile);
921 if ((conffile = get_path("config")) == NULL) {
922 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"get_path(\"config\") problem\n");
923 } else {
924 if ((conffile_fd = open(conffile, O_CREAT | O_EXCL | O_WRONLY, 0666)) != -1) {
925 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Creating config file: %s\n", conffile);
926 write(conffile_fd, default_config, strlen(default_config));
927 close(conffile_fd);
929 if (!disable_user_conf &&
930 m_config_parse_config_file(conf, conffile) < 0)
931 exit_player(mpctx, EXIT_NONE);
932 free(conffile);
937 #define PROFILE_CFG_PROTOCOL "protocol."
939 static void load_per_protocol_config (m_config_t* conf, const char *const file)
941 char *str;
942 char protocol[strlen (PROFILE_CFG_PROTOCOL) + strlen (file) + 1];
943 m_profile_t *p;
945 /* does filename actually uses a protocol ? */
946 str = strstr (file, "://");
947 if (!str)
948 return;
950 sprintf (protocol, "%s%s", PROFILE_CFG_PROTOCOL, file);
951 protocol[strlen (PROFILE_CFG_PROTOCOL)+strlen(file)-strlen(str)] = '\0';
952 p = m_config_get_profile (conf, protocol);
953 if (p)
955 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading protocol-related profile '%s'\n", protocol);
956 m_config_set_profile(conf,p);
960 #define PROFILE_CFG_EXTENSION "extension."
962 static void load_per_extension_config (m_config_t* conf, const char *const file)
964 char *str;
965 char extension[strlen (PROFILE_CFG_EXTENSION) + 8];
966 m_profile_t *p;
968 /* does filename actually have an extension ? */
969 str = strrchr (file, '.');
970 if (!str)
971 return;
973 sprintf (extension, PROFILE_CFG_EXTENSION);
974 strncat (extension, ++str, 7);
975 p = m_config_get_profile (conf, extension);
976 if (p)
978 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", extension);
979 m_config_set_profile(conf,p);
983 #define PROFILE_CFG_VO "vo."
984 #define PROFILE_CFG_AO "ao."
986 static void load_per_output_config (m_config_t* conf, char *cfg, char *out)
988 char profile[strlen (cfg) + strlen (out) + 1];
989 m_profile_t *p;
991 sprintf (profile, "%s%s", cfg, out);
992 p = m_config_get_profile (conf, profile);
993 if (p)
995 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", profile);
996 m_config_set_profile(conf,p);
1001 * Tries to load a config file
1002 * @return 0 if file was not found, 1 otherwise
1004 static int try_load_config(m_config_t *conf, const char *file)
1006 struct stat st;
1007 if (stat(file, &st))
1008 return 0;
1009 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Loading config '%s'\n", file);
1010 m_config_parse_config_file (conf, file);
1011 return 1;
1014 static void load_per_file_config (m_config_t* conf, const char *const file)
1016 char *confpath;
1017 char cfg[PATH_MAX];
1018 char *name;
1020 if (strlen(file) > PATH_MAX - 14) {
1021 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Filename is too long, can not load file or directory specific config files\n");
1022 return;
1024 sprintf (cfg, "%s.conf", file);
1026 name = strrchr(cfg, '/');
1027 if (HAVE_DOS_PATHS) {
1028 char *tmp = strrchr(cfg, '\\');
1029 if (!name || tmp > name)
1030 name = tmp;
1031 tmp = strrchr(cfg, ':');
1032 if (!name || tmp > name)
1033 name = tmp;
1035 if (!name)
1036 name = cfg;
1037 else
1038 name++;
1040 if (use_filedir_conf) {
1041 char dircfg[PATH_MAX];
1042 strcpy(dircfg, cfg);
1043 strcpy(dircfg + (name - cfg), "mplayer.conf");
1044 try_load_config(conf, dircfg);
1046 if (try_load_config(conf, cfg))
1047 return;
1050 if ((confpath = get_path (name)) != NULL)
1052 try_load_config(conf, confpath);
1054 free (confpath);
1058 /* When libmpdemux performs a blocking operation (network connection or
1059 * cache filling) if the operation fails we use this function to check
1060 * if it was interrupted by the user.
1061 * The function returns a new value for eof. */
1062 static int libmpdemux_was_interrupted(struct MPContext *mpctx, int stop_play)
1064 mp_cmd_t* cmd;
1065 if((cmd = mp_input_get_cmd(mpctx->input, 0, 0)) != NULL) {
1066 switch(cmd->id) {
1067 case MP_CMD_QUIT:
1068 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
1069 case MP_CMD_PLAY_TREE_STEP: {
1070 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_ENTRY : PT_PREV_ENTRY;
1071 mpctx->play_tree_step = (cmd->args[0].v.i == 0) ? 1 : cmd->args[0].v.i;
1072 } break;
1073 case MP_CMD_PLAY_TREE_UP_STEP: {
1074 stop_play = (cmd->args[0].v.i > 0) ? PT_UP_NEXT : PT_UP_PREV;
1075 } break;
1076 case MP_CMD_PLAY_ALT_SRC_STEP: {
1077 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_SRC : PT_PREV_SRC;
1078 } break;
1080 mp_cmd_free(cmd);
1082 return stop_play;
1085 #define mp_basename(s) (strrchr(s,'\\')==NULL?(mp_basename2(s)):(strrchr(s,'\\')+1))
1087 static int playtree_add_playlist(struct MPContext *mpctx, play_tree_t* entry)
1089 play_tree_add_bpf(entry,mpctx->filename);
1092 if(!entry) {
1093 entry = mpctx->playtree_iter->tree;
1094 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1095 return PT_NEXT_ENTRY;
1097 if(mpctx->playtree_iter->tree == entry ) { // Loop with a single file
1098 if(play_tree_iter_up_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1099 return PT_NEXT_ENTRY;
1102 play_tree_remove(entry,1,1);
1103 return PT_NEXT_SRC;
1105 play_tree_insert_entry(mpctx->playtree_iter->tree,entry);
1106 play_tree_set_params_from(entry,mpctx->playtree_iter->tree);
1107 entry = mpctx->playtree_iter->tree;
1108 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1109 return PT_NEXT_ENTRY;
1111 play_tree_remove(entry,1,1);
1113 return PT_NEXT_SRC;
1116 void add_subtitles(struct MPContext *mpctx, char *filename, float fps, int noerr)
1118 struct MPOpts *opts = &mpctx->opts;
1119 sub_data *subd = NULL;
1120 struct ass_track *asst = NULL;
1122 if (filename == NULL || mpctx->set_of_sub_size >= MAX_SUBTITLE_FILES) {
1123 return;
1126 #ifdef CONFIG_ASS
1127 if (opts->ass_enabled) {
1128 #ifdef CONFIG_ICONV
1129 asst = ass_read_stream(ass_library, filename, sub_cp);
1130 #else
1131 asst = ass_read_stream(ass_library, filename, 0);
1132 #endif
1133 if (!asst) {
1134 subd = sub_read_file(filename, fps);
1135 if (subd) {
1136 asst = ass_read_subdata(ass_library, subd, fps);
1137 if (asst) {
1138 sub_free(subd);
1139 subd = NULL;
1143 } else
1144 #endif
1145 subd = sub_read_file(filename, fps);
1148 if (!asst && !subd) {
1149 mp_tmsg(MSGT_CPLAYER, noerr ? MSGL_WARN : MSGL_ERR,
1150 "Cannot load subtitles: %s\n", filename_recode(filename));
1151 return;
1154 mpctx->set_of_ass_tracks[mpctx->set_of_sub_size] = asst;
1155 mpctx->set_of_subtitles[mpctx->set_of_sub_size] = subd;
1156 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_ID=%d\n", mpctx->set_of_sub_size);
1157 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_FILENAME=%s\n",
1158 filename_recode(filename));
1159 ++mpctx->set_of_sub_size;
1160 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "SUB: Added subtitle file (%d): %s\n", mpctx->set_of_sub_size,
1161 filename_recode(filename));
1164 void init_vo_spudec(struct MPContext *mpctx)
1166 if (vo_spudec)
1167 spudec_free(vo_spudec);
1168 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
1169 vo_spudec = NULL;
1171 // we currently can't work without video stream
1172 if (!mpctx->sh_video)
1173 return;
1175 if (spudec_ifo) {
1176 unsigned int palette[16], width, height;
1177 current_module="spudec_init_vobsub";
1178 if (vobsub_parse_ifo(NULL,spudec_ifo, palette, &width, &height, 1, -1, NULL) >= 0)
1179 vo_spudec=spudec_new_scaled(palette, width, height, NULL, 0);
1182 #ifdef CONFIG_DVDREAD
1183 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVD) {
1184 current_module="spudec_init_dvdread";
1185 vo_spudec=spudec_new_scaled(((dvd_priv_t *)(mpctx->stream->priv))->cur_pgc->palette,
1186 mpctx->sh_video->disp_w, mpctx->sh_video->disp_h,
1187 NULL, 0);
1189 #endif
1191 #ifdef CONFIG_DVDNAV
1192 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVDNAV) {
1193 unsigned int *palette = mp_dvdnav_get_spu_clut(mpctx->stream);
1194 current_module="spudec_init_dvdnav";
1195 vo_spudec=spudec_new_scaled(palette, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, NULL, 0);
1197 #endif
1199 if (vo_spudec==NULL) {
1200 sh_sub_t *sh = mpctx->d_sub->sh;
1201 current_module="spudec_init_normal";
1202 vo_spudec=spudec_new_scaled(NULL, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, sh->extradata, sh->extradata_len);
1203 spudec_set_font_factor(vo_spudec,font_factor);
1206 if (vo_spudec!=NULL) {
1207 mpctx->initialized_flags|=INITIALIZED_SPUDEC;
1208 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
1213 * In Mac OS X the SDL-lib is built upon Cocoa. The easiest way to
1214 * make it all work is to use the builtin SDL-bootstrap code, which
1215 * will be done automatically by replacing our main() if we include SDL.h.
1217 #if defined(__APPLE__) && defined(CONFIG_SDL)
1218 #ifdef CONFIG_SDL_SDL_H
1219 #include <SDL/SDL.h>
1220 #else
1221 #include <SDL.h>
1222 #endif
1223 #endif
1226 * \brief append a formatted string
1227 * \param buf buffer to print into
1228 * \param pos position of terminating 0 in buf
1229 * \param len maximum number of characters in buf, not including terminating 0
1230 * \param format printf format string
1232 static void saddf(char *buf, unsigned *pos, int len, const char *format, ...)
1234 va_list va;
1235 va_start(va, format);
1236 *pos += vsnprintf(&buf[*pos], len - *pos, format, va);
1237 va_end(va);
1238 if (*pos >= len ) {
1239 buf[len] = 0;
1240 *pos = len;
1245 * \brief append time in the hh:mm:ss.f format
1246 * \param buf buffer to print into
1247 * \param pos position of terminating 0 in buf
1248 * \param len maximum number of characters in buf, not including terminating 0
1249 * \param time time value to convert/append
1251 static void sadd_hhmmssf(char *buf, unsigned *pos, int len, float time) {
1252 int64_t tenths = 10 * time;
1253 int f1 = tenths % 10;
1254 int ss = (tenths / 10) % 60;
1255 int mm = (tenths / 600) % 60;
1256 int hh = tenths / 36000;
1257 if (time <= 0) {
1258 saddf(buf, pos, len, "unknown");
1259 return;
1261 if (hh > 0)
1262 saddf(buf, pos, len, "%2d:", hh);
1263 if (hh > 0 || mm > 0)
1264 saddf(buf, pos, len, "%02d:", mm);
1265 saddf(buf, pos, len, "%02d.%1d", ss, f1);
1268 static void print_status(struct MPContext *mpctx, double a_pos, bool at_frame)
1270 struct MPOpts *opts = &mpctx->opts;
1271 sh_video_t * const sh_video = mpctx->sh_video;
1273 if (mpctx->sh_audio && a_pos == MP_NOPTS_VALUE)
1274 a_pos = playing_audio_pts(mpctx);
1275 if (mpctx->sh_audio && sh_video && at_frame) {
1276 mpctx->last_av_difference = a_pos - sh_video->pts - audio_delay;
1277 if (mpctx->time_frame > 0)
1278 mpctx->last_av_difference += mpctx->time_frame * opts->playback_speed;
1279 if (mpctx->last_av_difference > 0.5 && drop_frame_cnt > 50
1280 && !mpctx->drop_message_shown) {
1281 mp_tmsg(MSGT_AVSYNC,MSGL_WARN,SystemTooSlow);
1282 mpctx->drop_message_shown = true;
1285 if (opts->quiet)
1286 return;
1289 int width;
1290 char *line;
1291 unsigned pos = 0;
1292 get_screen_size();
1293 if (screen_width > 0)
1294 width = screen_width;
1295 else
1296 width = 80;
1297 #if defined(__MINGW32__) || defined(__CYGWIN__) || defined(__OS2__)
1298 /* Windows command line is broken (MinGW's rxvt works, but we
1299 * should not depend on that). */
1300 width--;
1301 #endif
1302 line = malloc(width + 1); // one additional char for the terminating null
1304 // Audio time
1305 if (mpctx->sh_audio) {
1306 saddf(line, &pos, width, "A:%6.1f ", a_pos);
1307 if (!sh_video) {
1308 float len = get_time_length(mpctx);
1309 saddf(line, &pos, width, "(");
1310 sadd_hhmmssf(line, &pos, width, a_pos);
1311 saddf(line, &pos, width, ") of %.1f (", len);
1312 sadd_hhmmssf(line, &pos, width, len);
1313 saddf(line, &pos, width, ") ");
1317 // Video time
1318 if (sh_video)
1319 saddf(line, &pos, width, "V:%6.1f ", sh_video->pts);
1321 // A-V sync
1322 if (mpctx->sh_audio && sh_video)
1323 saddf(line, &pos, width, "A-V:%7.3f ct:%7.3f ",
1324 mpctx->last_av_difference, mpctx->total_avsync_change);
1326 // Video stats
1327 if (sh_video)
1328 saddf(line, &pos, width, "%3d/%3d ",
1329 (int)sh_video->num_frames,
1330 (int)sh_video->num_frames_decoded);
1332 // CPU usage
1333 if (sh_video) {
1334 if (sh_video->timer > 0.5)
1335 saddf(line, &pos, width, "%2d%% %2d%% %4.1f%% ",
1336 (int)(100.0*video_time_usage*opts->playback_speed/(double)sh_video->timer),
1337 (int)(100.0*vout_time_usage*opts->playback_speed/(double)sh_video->timer),
1338 (100.0*audio_time_usage*opts->playback_speed/(double)sh_video->timer));
1339 else
1340 saddf(line, &pos, width, "??%% ??%% ??,?%% ");
1341 } else if (mpctx->sh_audio) {
1342 if (mpctx->delay > 0.5)
1343 saddf(line, &pos, width, "%4.1f%% ",
1344 100.0*audio_time_usage/(double)mpctx->delay);
1345 else
1346 saddf(line, &pos, width, "??,?%% ");
1349 // VO stats
1350 if (sh_video)
1351 saddf(line, &pos, width, "%d %d ", drop_frame_cnt, output_quality);
1353 #ifdef CONFIG_STREAM_CACHE
1354 // cache stats
1355 if (stream_cache_size > 0)
1356 saddf(line, &pos, width, "%d%% ", cache_fill_status);
1357 #endif
1359 // other
1360 if (opts->playback_speed != 1)
1361 saddf(line, &pos, width, "%4.2fx ", opts->playback_speed);
1363 // end
1364 if (erase_to_end_of_line) {
1365 line[pos] = 0;
1366 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s%s\r", line, erase_to_end_of_line);
1367 } else {
1368 memset(&line[pos], ' ', width - pos);
1369 line[width] = 0;
1370 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s\r", line);
1372 free(line);
1376 * \brief build a chain of audio filters that converts the input format
1377 * to the ao's format, taking into account the current playback_speed.
1378 * \param sh_audio describes the requested input format of the chain.
1379 * \param ao_data describes the requested output format of the chain.
1381 int build_afilter_chain(struct MPContext *mpctx, sh_audio_t *sh_audio, ao_data_t *ao_data)
1383 struct MPOpts *opts = &mpctx->opts;
1384 int new_srate;
1385 int result;
1386 if (!sh_audio)
1388 mpctx->mixer.afilter = NULL;
1389 return 0;
1391 if(af_control_any_rev(sh_audio->afilter,
1392 AF_CONTROL_PLAYBACK_SPEED | AF_CONTROL_SET,
1393 &opts->playback_speed)) {
1394 new_srate = sh_audio->samplerate;
1395 } else {
1396 new_srate = sh_audio->samplerate * opts->playback_speed;
1397 if (new_srate != ao_data->samplerate) {
1398 // limits are taken from libaf/af_resample.c
1399 if (new_srate < 8000)
1400 new_srate = 8000;
1401 if (new_srate > 192000)
1402 new_srate = 192000;
1403 opts->playback_speed = (float)new_srate / (float)sh_audio->samplerate;
1406 result = init_audio_filters(sh_audio, new_srate,
1407 &ao_data->samplerate, &ao_data->channels, &ao_data->format);
1408 mpctx->mixer.afilter = sh_audio->afilter;
1409 return result;
1413 typedef struct mp_osd_msg mp_osd_msg_t;
1414 struct mp_osd_msg {
1415 /// Previous message on the stack.
1416 mp_osd_msg_t* prev;
1417 /// Message text.
1418 char msg[128];
1419 int id,level,started;
1420 /// Display duration in ms.
1421 unsigned time;
1424 /// OSD message stack.
1425 static mp_osd_msg_t* osd_msg_stack = NULL;
1428 * \brief Add a message on the OSD message stack
1430 * If a message with the same id is already present in the stack
1431 * it is pulled on top of the stack, otherwise a new message is created.
1434 static void set_osd_msg_va(int id, int level, int time, const char *fmt,
1435 va_list ap)
1437 mp_osd_msg_t *msg,*last=NULL;
1438 int r;
1440 // look if the id is already in the stack
1441 for(msg = osd_msg_stack ; msg && msg->id != id ;
1442 last = msg, msg = msg->prev);
1443 // not found: alloc it
1444 if(!msg) {
1445 msg = calloc(1,sizeof(mp_osd_msg_t));
1446 msg->prev = osd_msg_stack;
1447 osd_msg_stack = msg;
1448 } else if(last) { // found, but it's not on top of the stack
1449 last->prev = msg->prev;
1450 msg->prev = osd_msg_stack;
1451 osd_msg_stack = msg;
1453 // write the msg
1454 r = vsnprintf(msg->msg, 128, fmt, ap);
1455 if(r >= 128) msg->msg[127] = 0;
1456 // set id and time
1457 msg->id = id;
1458 msg->level = level;
1459 msg->time = time;
1463 void set_osd_msg(int id, int level, int time, const char *fmt, ...)
1465 va_list ap;
1466 va_start(ap, fmt);
1467 set_osd_msg_va(id, level, time, fmt, ap);
1468 va_end(ap);
1471 void set_osd_tmsg(int id, int level, int time, const char *fmt, ...)
1473 va_list ap;
1474 va_start(ap, fmt);
1475 set_osd_msg_va(id, level, time, mp_gtext(fmt), ap);
1476 va_end(ap);
1481 * \brief Remove a message from the OSD stack
1483 * This function can be used to get rid of a message right away.
1487 void rm_osd_msg(int id) {
1488 mp_osd_msg_t *msg,*last=NULL;
1490 // Search for the msg
1491 for(msg = osd_msg_stack ; msg && msg->id != id ;
1492 last = msg, msg = msg->prev);
1493 if(!msg) return;
1495 // Detach it from the stack and free it
1496 if(last)
1497 last->prev = msg->prev;
1498 else
1499 osd_msg_stack = msg->prev;
1500 free(msg);
1504 * \brief Remove all messages from the OSD stack
1508 static void clear_osd_msgs(void) {
1509 mp_osd_msg_t* msg = osd_msg_stack, *prev = NULL;
1510 while(msg) {
1511 prev = msg->prev;
1512 free(msg);
1513 msg = prev;
1515 osd_msg_stack = NULL;
1519 * \brief Get the current message from the OSD stack.
1521 * This function decrements the message timer and destroys the old ones.
1522 * The message that should be displayed is returned (if any).
1526 static mp_osd_msg_t* get_osd_msg(struct MPContext *mpctx)
1528 struct MPOpts *opts = &mpctx->opts;
1529 mp_osd_msg_t *msg,*prev,*last = NULL;
1530 static unsigned last_update = 0;
1531 unsigned now = GetTimerMS();
1532 unsigned diff;
1533 char hidden_dec_done = 0;
1535 if (mpctx->osd_visible) {
1536 // 36000000 means max timed visibility is 1 hour into the future, if
1537 // the difference is greater assume it's wrapped around from below 0
1538 if (mpctx->osd_visible - now > 36000000) {
1539 mpctx->osd_visible = 0;
1540 vo_osd_progbar_type = -1; // disable
1541 vo_osd_changed(OSDTYPE_PROGBAR);
1542 mpctx->osd_function = mpctx->paused ? OSD_PAUSE : OSD_PLAY;
1545 if (mpctx->osd_show_percentage_until - now > 36000000)
1546 mpctx->osd_show_percentage_until = 0;
1548 if(!last_update) last_update = now;
1549 diff = now >= last_update ? now - last_update : 0;
1551 last_update = now;
1553 // Look for the first message in the stack with high enough level.
1554 for(msg = osd_msg_stack ; msg ; last = msg, msg = prev) {
1555 prev = msg->prev;
1556 if (msg->level > opts->osd_level && hidden_dec_done)
1557 continue;
1558 // The message has a high enough level or it is the first hidden one
1559 // in both cases we decrement the timer or kill it.
1560 if(!msg->started || msg->time > diff) {
1561 if(msg->started) msg->time -= diff;
1562 else msg->started = 1;
1563 // display it
1564 if (msg->level <= opts->osd_level)
1565 return msg;
1566 hidden_dec_done = 1;
1567 continue;
1569 // kill the message
1570 free(msg);
1571 if(last) {
1572 last->prev = prev;
1573 msg = last;
1574 } else {
1575 osd_msg_stack = prev;
1576 msg = NULL;
1579 // Nothing found
1580 return NULL;
1584 * \brief Display the OSD bar.
1586 * Display the OSD bar or fall back on a simple message.
1590 void set_osd_bar(struct MPContext *mpctx, int type,const char* name,double min,double max,double val) {
1591 struct MPOpts *opts = &mpctx->opts;
1592 if (opts->osd_level < 1)
1593 return;
1595 if(mpctx->sh_video) {
1596 mpctx->osd_visible = (GetTimerMS() + 1000) | 1;
1597 vo_osd_progbar_type = type;
1598 vo_osd_progbar_value = 256*(val-min)/(max-min);
1599 vo_osd_changed(OSDTYPE_PROGBAR);
1600 return;
1603 set_osd_msg(OSD_MSG_BAR, 1, opts->osd_duration, "%s: %d %%",
1604 name, ROUND(100*(val-min)/(max-min)));
1608 * \brief Display text subtitles on the OSD
1610 void set_osd_subtitle(struct MPContext *mpctx, subtitle *subs)
1612 int i;
1613 vo_sub = subs;
1614 vo_osd_changed(OSDTYPE_SUBTITLE);
1615 if (!mpctx->sh_video) {
1616 // reverse order, since newest set_osd_msg is displayed first
1617 for (i = SUB_MAX_TEXT - 1; i >= 0; i--) {
1618 if (!subs || i >= subs->lines || !subs->text[i])
1619 rm_osd_msg(OSD_MSG_SUB_BASE + i);
1620 else {
1621 // HACK: currently display time for each sub line except the last is set to 2 seconds.
1622 int display_time = i == subs->lines - 1 ? 180000 : 2000;
1623 set_osd_msg(OSD_MSG_SUB_BASE + i, 1, display_time, "%s", subs->text[i]);
1630 * \brief Update the OSD message line.
1632 * This function displays the current message on the vo OSD or on the term.
1633 * If the stack is empty and the OSD level is high enough the timer
1634 * is displayed (only on the vo OSD).
1638 static void update_osd_msg(struct MPContext *mpctx)
1640 struct MPOpts *opts = &mpctx->opts;
1641 mp_osd_msg_t *msg;
1642 struct osd_state *osd = mpctx->osd;
1643 char osd_text_timer[128];
1645 if (mpctx->add_osd_seek_info) {
1646 double percentage = get_percent_pos(mpctx);
1647 set_osd_bar(mpctx, 0, "Position", 0, 100, percentage);
1648 if (mpctx->sh_video)
1649 mpctx->osd_show_percentage_until = (GetTimerMS() + 1000) | 1;
1650 mpctx->add_osd_seek_info = false;
1653 // Look if we have a msg
1654 if((msg = get_osd_msg(mpctx))) {
1655 if (strcmp(osd->osd_text, msg->msg)) {
1656 strncpy(osd->osd_text, msg->msg, 127);
1657 if(mpctx->sh_video) vo_osd_changed(OSDTYPE_OSD); else
1658 if(opts->term_osd)
1659 mp_msg(MSGT_CPLAYER,MSGL_STATUS, "%s%s\n", opts->term_osd_esc,
1660 msg->msg);
1662 return;
1665 if(mpctx->sh_video) {
1666 // fallback on the timer
1667 if (opts->osd_level >= 2) {
1668 int len = get_time_length(mpctx);
1669 int percentage = -1;
1670 char percentage_text[10];
1671 int pts = get_current_time(mpctx);
1673 if (mpctx->osd_show_percentage_until)
1674 percentage = get_percent_pos(mpctx);
1676 if (percentage >= 0)
1677 snprintf(percentage_text, 9, " (%d%%)", percentage);
1678 else
1679 percentage_text[0] = 0;
1681 if (opts->osd_level == 3)
1682 snprintf(osd_text_timer, 63,
1683 "%c %02d:%02d:%02d / %02d:%02d:%02d%s",
1684 mpctx->osd_function,pts/3600,(pts/60)%60,pts%60,
1685 len/3600,(len/60)%60,len%60,percentage_text);
1686 else
1687 snprintf(osd_text_timer, 63, "%c %02d:%02d:%02d%s",
1688 mpctx->osd_function,pts/3600,(pts/60)%60,
1689 pts%60,percentage_text);
1690 } else
1691 osd_text_timer[0]=0;
1693 if (strcmp(osd->osd_text, osd_text_timer)) {
1694 strncpy(osd->osd_text, osd_text_timer, 63);
1695 vo_osd_changed(OSDTYPE_OSD);
1697 return;
1700 // Clear the term osd line
1701 if (opts->term_osd && osd->osd_text[0]) {
1702 osd->osd_text[0] = 0;
1703 printf("%s\n", opts->term_osd_esc);
1707 ///@}
1708 // OSDMsgStack
1711 void reinit_audio_chain(struct MPContext *mpctx)
1713 struct MPOpts *opts = &mpctx->opts;
1714 if (!mpctx->sh_audio)
1715 return;
1716 if (!(mpctx->initialized_flags & INITIALIZED_ACODEC)) {
1717 current_module="init_audio_codec";
1718 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1719 if(!init_best_audio_codec(mpctx->sh_audio,audio_codec_list,audio_fm_list)){
1720 goto init_error;
1722 mpctx->initialized_flags|=INITIALIZED_ACODEC;
1723 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1727 current_module="af_preinit";
1728 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1729 ao_data.samplerate=force_srate;
1730 ao_data.channels=0;
1731 ao_data.format = opts->audio_output_format;
1733 // first init to detect best values
1734 if(!init_audio_filters(mpctx->sh_audio, // preliminary init
1735 // input:
1736 mpctx->sh_audio->samplerate,
1737 // output:
1738 &ao_data.samplerate, &ao_data.channels, &ao_data.format)){
1739 mp_tmsg(MSGT_CPLAYER,MSGL_ERR, "Error at audio filter chain "
1740 "pre-init!\n");
1741 exit_player(mpctx, EXIT_ERROR);
1743 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1744 current_module="ao2_init";
1745 ao_data.buffersize = opts->ao_buffersize;
1746 mpctx->audio_out = init_best_audio_out(opts->audio_driver_list,
1747 0, // plugin flag
1748 ao_data.samplerate,
1749 ao_data.channels,
1750 ao_data.format, 0);
1751 if(!mpctx->audio_out){
1752 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Could not open/initialize audio device -> no sound.\n");
1753 goto init_error;
1755 mpctx->initialized_flags|=INITIALIZED_AO;
1756 mp_msg(MSGT_CPLAYER,MSGL_INFO,"AO: [%s] %dHz %dch %s (%d bytes per sample)\n",
1757 mpctx->audio_out->info->short_name,
1758 ao_data.samplerate, ao_data.channels,
1759 af_fmt2str_short(ao_data.format),
1760 af_fmt2bits(ao_data.format)/8 );
1761 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Description: %s\nAO: Author: %s\n",
1762 mpctx->audio_out->info->name, mpctx->audio_out->info->author);
1763 if(strlen(mpctx->audio_out->info->comment) > 0)
1764 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Comment: %s\n", mpctx->audio_out->info->comment);
1767 // init audio filters:
1768 current_module="af_init";
1769 if(!build_afilter_chain(mpctx, mpctx->sh_audio, &ao_data)) {
1770 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Couldn't find matching filter/ao format!\n");
1771 goto init_error;
1773 mpctx->mixer.audio_out = mpctx->audio_out;
1774 mpctx->mixer.volstep = volstep;
1775 mpctx->syncing_audio = true;
1776 return;
1778 init_error:
1779 uninit_player(mpctx, INITIALIZED_ACODEC|INITIALIZED_AO); // close codec and possibly AO
1780 mpctx->sh_audio=mpctx->d_audio->sh=NULL; // -> nosound
1781 mpctx->d_audio->id = -2;
1785 ///@}
1786 // Command2Property
1789 // Return pts value corresponding to the end point of audio written to the
1790 // ao so far.
1791 static double written_audio_pts(struct MPContext *mpctx)
1793 sh_audio_t *sh_audio = mpctx->sh_audio;
1794 demux_stream_t *d_audio = mpctx->d_audio;
1795 double buffered_output;
1796 // first calculate the end pts of audio that has been output by decoder
1797 double a_pts = sh_audio->pts;
1798 if (a_pts != MP_NOPTS_VALUE)
1799 // Good, decoder supports new way of calculating audio pts.
1800 // sh_audio->pts is the timestamp of the latest input packet with
1801 // known pts that the decoder has decoded. sh_audio->pts_bytes is
1802 // the amount of bytes the decoder has written after that timestamp.
1803 a_pts += sh_audio->pts_bytes / (double) sh_audio->o_bps;
1804 else {
1805 // Decoder doesn't support new way of calculating pts (or we're
1806 // being called before it has decoded anything with known timestamp).
1807 // Use the old method of audio pts calculation: take the timestamp
1808 // of last packet with known pts the decoder has read data from,
1809 // and add amount of bytes read after the beginning of that packet
1810 // divided by input bps. This will be inaccurate if the input/output
1811 // ratio is not constant for every audio packet or if it is constant
1812 // but not accurately known in sh_audio->i_bps.
1814 a_pts = d_audio->pts;
1815 // ds_tell_pts returns bytes read after last timestamp from
1816 // demuxing layer, decoder might use sh_audio->a_in_buffer for bytes
1817 // it has read but not decoded
1818 if (sh_audio->i_bps)
1819 a_pts += (ds_tell_pts(d_audio) - sh_audio->a_in_buffer_len) /
1820 (double)sh_audio->i_bps;
1822 // Now a_pts hopefully holds the pts for end of audio from decoder.
1823 // Substract data in buffers between decoder and audio out.
1825 // Decoded but not filtered
1826 a_pts -= sh_audio->a_buffer_len / (double)sh_audio->o_bps;
1828 // Data buffered in audio filters, measured in bytes of "missing" output
1829 buffered_output = af_calc_delay(sh_audio->afilter);
1831 // Data that was ready for ao but was buffered because ao didn't fully
1832 // accept everything to internal buffers yet
1833 buffered_output += sh_audio->a_out_buffer_len;
1835 // Filters divide audio length by playback_speed, so multiply by it
1836 // to get the length in original units without speedup or slowdown
1837 a_pts -= buffered_output * mpctx->opts.playback_speed / ao_data.bps;
1839 return a_pts + mpctx->video_offset;
1842 // Return pts value corresponding to currently playing audio.
1843 double playing_audio_pts(struct MPContext *mpctx)
1845 return written_audio_pts(mpctx) - mpctx->opts.playback_speed *
1846 mpctx->audio_out->get_delay();
1849 static int check_framedrop(struct MPContext *mpctx, double frame_time) {
1850 struct MPOpts *opts = &mpctx->opts;
1851 // check for frame-drop:
1852 current_module = "check_framedrop";
1853 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
1854 static int dropped_frames;
1855 float delay = opts->playback_speed*mpctx->audio_out->get_delay();
1856 float d = delay-mpctx->delay;
1857 ++total_frame_cnt;
1858 // we should avoid dropping too many frames in sequence unless we
1859 // are too late. and we allow 100ms A-V delay here:
1860 if (d < -dropped_frames*frame_time-0.100 && !mpctx->paused
1861 && !mpctx->restart_playback) {
1862 ++drop_frame_cnt;
1863 ++dropped_frames;
1864 return frame_dropping;
1865 } else
1866 dropped_frames = 0;
1868 return 0;
1872 #ifdef HAVE_RTC
1873 int rtc_fd = -1;
1874 #endif
1876 static float timing_sleep(struct MPContext *mpctx, float time_frame)
1878 #ifdef HAVE_RTC
1879 if (rtc_fd >= 0){
1880 // -------- RTC -----------
1881 current_module="sleep_rtc";
1882 while (time_frame > 0.000) {
1883 unsigned long rtc_ts;
1884 if (read(rtc_fd, &rtc_ts, sizeof(rtc_ts)) <= 0)
1885 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC read error: %s\n", strerror(errno));
1886 time_frame -= get_relative_time(mpctx);
1888 } else
1889 #endif
1891 // assume kernel HZ=100 for softsleep, works with larger HZ but with
1892 // unnecessarily high CPU usage
1893 struct MPOpts *opts = &mpctx->opts;
1894 float margin = opts->softsleep ? 0.011 : 0;
1895 current_module = "sleep_timer";
1896 while (time_frame > margin) {
1897 usec_sleep(1000000 * (time_frame - margin));
1898 time_frame -= get_relative_time(mpctx);
1900 if (opts->softsleep){
1901 current_module = "sleep_soft";
1902 if (time_frame < 0)
1903 mp_tmsg(MSGT_AVSYNC, MSGL_WARN, "Warning! Softsleep underflow!\n");
1904 while (time_frame > 0)
1905 time_frame -= get_relative_time(mpctx); // burn the CPU
1908 return time_frame;
1911 static int select_subtitle(MPContext *mpctx)
1913 struct MPOpts *opts = &mpctx->opts;
1914 // find the best sub to use
1915 int id;
1916 int found = 0;
1917 mpctx->global_sub_pos = -1; // no subs by default
1918 if (vobsub_id >= 0) {
1919 // if user asks for a vobsub id, use that first.
1920 id = vobsub_id;
1921 found = mp_property_do("sub_vob", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1924 if (!found && opts->sub_id >= 0) {
1925 // if user asks for a dvd sub id, use that next.
1926 id = opts->sub_id;
1927 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1930 if (!found) {
1931 // if there are text subs to use, use those. (autosubs come last here)
1932 id = 0;
1933 found = mp_property_do("sub_file", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1936 if (!found && opts->sub_id == -1) {
1937 // finally select subs by language and container hints
1938 if (opts->sub_id == -1)
1939 opts->sub_id =
1940 demuxer_sub_track_by_lang_and_default(mpctx->d_sub->demuxer,
1941 opts->sub_lang);
1942 if (opts->sub_id >= 0) {
1943 id = opts->sub_id;
1944 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
1947 return found;
1950 #ifdef CONFIG_DVDNAV
1951 #ifndef FF_B_TYPE
1952 #define FF_B_TYPE 3
1953 #endif
1954 /// store decoded video image
1955 static mp_image_t * mp_dvdnav_copy_mpi(mp_image_t *to_mpi,
1956 mp_image_t *from_mpi) {
1957 mp_image_t *mpi;
1959 /// Do not store B-frames
1960 if (from_mpi->pict_type == FF_B_TYPE)
1961 return to_mpi;
1963 if (to_mpi &&
1964 to_mpi->w == from_mpi->w &&
1965 to_mpi->h == from_mpi->h &&
1966 to_mpi->imgfmt == from_mpi->imgfmt)
1967 mpi = to_mpi;
1968 else {
1969 if (to_mpi)
1970 free_mp_image(to_mpi);
1971 if (from_mpi->w == 0 || from_mpi->h == 0)
1972 return NULL;
1973 mpi = alloc_mpi(from_mpi->w,from_mpi->h,from_mpi->imgfmt);
1976 copy_mpi(mpi,from_mpi);
1977 return mpi;
1980 static void mp_dvdnav_reset_stream (MPContext *ctx) {
1981 struct MPOpts *opts = &ctx->opts;
1982 if (ctx->sh_video) {
1983 /// clear video pts
1984 ctx->d_video->pts = 0.0f;
1985 ctx->sh_video->pts = 0.0f;
1986 ctx->sh_video->i_pts = 0.0f;
1987 ctx->sh_video->last_pts = 0.0f;
1988 ctx->sh_video->num_buffered_pts = 0;
1989 ctx->sh_video->num_frames = 0;
1990 ctx->sh_video->num_frames_decoded = 0;
1991 ctx->sh_video->timer = 0.0f;
1992 ctx->sh_video->stream_delay = 0.0f;
1993 ctx->sh_video->timer = 0;
1994 ctx->demuxer->stream_pts = MP_NOPTS_VALUE;
1997 if (ctx->sh_audio) {
1998 /// free audio packets and reset
1999 ds_free_packs(ctx->d_audio);
2000 audio_delay -= ctx->sh_audio->stream_delay;
2001 ctx->delay =- audio_delay;
2002 ctx->audio_out->reset();
2003 resync_audio_stream(ctx->sh_audio);
2006 audio_delay = 0.0f;
2007 ctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(ctx->stream);
2008 if (opts->sub_lang && opts->sub_id == dvdsub_lang_id) {
2009 dvdsub_lang_id = mp_dvdnav_sid_from_lang(ctx->stream, opts->sub_lang);
2010 if (dvdsub_lang_id != opts->sub_id) {
2011 opts->sub_id = dvdsub_lang_id;
2012 select_subtitle(ctx);
2016 /// clear all EOF related flags
2017 ctx->d_video->eof = ctx->d_audio->eof = ctx->stream->eof = 0;
2020 /// Restore last decoded DVDNAV (still frame)
2021 static mp_image_t *mp_dvdnav_restore_smpi(struct MPContext *mpctx,
2022 int *in_size,
2023 unsigned char **start,
2024 mp_image_t *decoded_frame)
2026 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2027 return decoded_frame;
2029 /// a change occured in dvdnav stream
2030 if (mp_dvdnav_cell_has_changed(mpctx->stream,0)) {
2031 mp_dvdnav_read_wait(mpctx->stream, 1, 1);
2032 mp_dvdnav_context_free(mpctx);
2033 mp_dvdnav_reset_stream(mpctx);
2034 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
2035 mp_dvdnav_cell_has_changed(mpctx->stream,1);
2038 if (*in_size < 0) {
2039 float len;
2041 /// Display still frame, if any
2042 if (mpctx->nav_smpi && !mpctx->nav_buffer)
2043 decoded_frame = mpctx->nav_smpi;
2045 /// increment video frame : continue playing after still frame
2046 len = get_time_length(mpctx);
2047 if (mpctx->sh_video->pts >= len &&
2048 mpctx->sh_video->pts > 0.0 && len > 0.0) {
2049 mp_dvdnav_skip_still(mpctx->stream);
2050 mp_dvdnav_skip_wait(mpctx->stream);
2052 mpctx->sh_video->pts += 1 / mpctx->sh_video->fps;
2054 if (mpctx->nav_buffer) {
2055 *start = mpctx->nav_start;
2056 *in_size = mpctx->nav_in_size;
2057 if (mpctx->nav_start)
2058 memcpy(*start,mpctx->nav_buffer,mpctx->nav_in_size);
2062 return decoded_frame;
2065 /// Save last decoded DVDNAV (still frame)
2066 static void mp_dvdnav_save_smpi(struct MPContext *mpctx, int in_size,
2067 unsigned char *start,
2068 mp_image_t *decoded_frame)
2070 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2071 return;
2073 free(mpctx->nav_buffer);
2075 mpctx->nav_buffer = malloc(in_size);
2076 mpctx->nav_start = start;
2077 mpctx->nav_in_size = mpctx->nav_buffer ? in_size : -1;
2078 if (mpctx->nav_buffer)
2079 memcpy(mpctx->nav_buffer,start,in_size);
2081 if (decoded_frame && mpctx->nav_smpi != decoded_frame)
2082 mpctx->nav_smpi = mp_dvdnav_copy_mpi(mpctx->nav_smpi,decoded_frame);
2084 #endif /* CONFIG_DVDNAV */
2086 /* Modify video timing to match the audio timeline. There are two main
2087 * reasons this is needed. First, video and audio can start from different
2088 * positions at beginning of file or after a seek (MPlayer starts both
2089 * immediately even if they have different pts). Second, the file can have
2090 * audio timestamps that are inconsistent with the duration of the audio
2091 * packets, for example two consecutive timestamp values differing by
2092 * one second but only a packet with enough samples for half a second
2093 * of playback between them.
2095 static void adjust_sync(struct MPContext *mpctx, double frame_time)
2097 current_module = "av_sync";
2099 if (!mpctx->sh_audio || mpctx->syncing_audio)
2100 return;
2102 double a_pts = written_audio_pts(mpctx) - mpctx->delay;
2103 double v_pts = mpctx->sh_video->pts;
2104 double av_delay = a_pts - v_pts;
2105 // Try to sync vo_flip() so it will *finish* at given time
2106 av_delay += mpctx->last_vo_flip_duration;
2107 av_delay -= audio_delay; // This much pts difference is desired
2109 double change = av_delay * 0.1;
2110 double max_change = default_max_pts_correction >= 0 ?
2111 default_max_pts_correction : frame_time * 0.1;
2112 if (change < -max_change)
2113 change = -max_change;
2114 else if (change > max_change)
2115 change = max_change;
2116 mpctx->delay += change;
2117 mpctx->total_avsync_change += change;
2120 #define ASYNC_PLAY_DONE -3
2121 static int audio_start_sync(struct MPContext *mpctx, int playsize)
2123 struct MPOpts *opts = &mpctx->opts;
2124 sh_audio_t * const sh_audio = mpctx->sh_audio;
2125 int res;
2127 // Timing info may not be set without
2128 res = decode_audio(sh_audio, 1);
2129 if (res < 0)
2130 return res;
2131 double ptsdiff = written_audio_pts(mpctx) - mpctx->sh_video->pts -
2132 mpctx->delay - audio_delay;
2133 int bytes = ptsdiff * ao_data.bps / mpctx->opts.playback_speed;
2134 bytes -= bytes % (ao_data.channels * af_fmt2bits(ao_data.format) / 8);
2136 if (fabs(ptsdiff) > 300) // pts reset or just broken?
2137 bytes = 0;
2139 if (bytes <= 0) {
2140 mpctx->syncing_audio = false;
2141 while (1) {
2142 int a = FFMIN(-bytes, FFMAX(playsize, 20000));
2143 int res = decode_audio(sh_audio, a);
2144 bytes += sh_audio->a_out_buffer_len;
2145 if (bytes >= 0) {
2146 memmove(sh_audio->a_out_buffer,
2147 sh_audio->a_out_buffer +
2148 sh_audio->a_out_buffer_len - bytes,
2149 bytes);
2150 sh_audio->a_out_buffer_len = bytes;
2151 if (res < 0)
2152 return res;
2153 return decode_audio(sh_audio, playsize);
2155 sh_audio->a_out_buffer_len = 0;
2156 if (res < 0)
2157 return res;
2159 } else {
2160 int fillbyte = 0;
2161 if ((ao_data.format & AF_FORMAT_SIGN_MASK) == AF_FORMAT_US)
2162 fillbyte = 0x80;
2163 if (bytes >= playsize) {
2164 /* This case could fall back to the one below with
2165 * bytes = playsize, but then silence would keep accumulating
2166 * in a_out_buffer if the AO accepts less data than it asks for
2167 * in playsize. */
2168 char *p = malloc(playsize);
2169 memset(p, fillbyte, playsize);
2170 playsize = mpctx->audio_out->play(p, playsize, 0);
2171 free(p);
2172 mpctx->delay += opts->playback_speed*playsize/(double)ao_data.bps;
2173 return ASYNC_PLAY_DONE;
2175 mpctx->syncing_audio = false;
2176 decode_audio_prepend_bytes(sh_audio, bytes, fillbyte);
2177 return decode_audio(sh_audio, playsize);
2181 static int fill_audio_out_buffers(struct MPContext *mpctx)
2183 struct MPOpts *opts = &mpctx->opts;
2184 unsigned int t;
2185 double tt;
2186 int playsize;
2187 int playflags=0;
2188 int audio_eof=0;
2189 bool format_change = false;
2190 sh_audio_t * const sh_audio = mpctx->sh_audio;
2192 current_module="play_audio";
2194 while (1) {
2195 int sleep_time;
2196 // all the current uses of ao_data.pts seem to be in aos that handle
2197 // sync completely wrong; there should be no need to use ao_data.pts
2198 // in get_space()
2199 ao_data.pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2200 playsize = mpctx->audio_out->get_space();
2201 if (mpctx->sh_video || playsize >= ao_data.outburst)
2202 break;
2204 // handle audio-only case:
2205 // this is where mplayer sleeps during audio-only playback
2206 // to avoid 100% CPU use
2207 sleep_time = (ao_data.outburst - playsize) * 1000 / ao_data.bps;
2208 if (sleep_time < 10) sleep_time = 10; // limit to 100 wakeups per second
2209 usec_sleep(sleep_time * 1000);
2212 // Fill buffer if needed:
2213 current_module="decode_audio";
2214 t = GetTimer();
2216 if (!opts->initial_audio_sync || (ao_data.format & AF_FORMAT_SPECIAL_MASK))
2217 mpctx->syncing_audio = false;
2219 int res;
2220 if (mpctx->syncing_audio && mpctx->sh_video)
2221 res = audio_start_sync(mpctx, playsize);
2222 else
2223 res = decode_audio(sh_audio, playsize);
2224 if (res < 0) { // EOF, error or format change
2225 if (res == -2)
2226 format_change = true;
2227 else if (res == ASYNC_PLAY_DONE)
2228 return 1;
2229 else if (mpctx->d_audio->eof) {
2230 audio_eof = 1;
2231 int unitsize = ao_data.channels * af_fmt2bits(ao_data.format) / 8;
2232 if (sh_audio->a_out_buffer_len < unitsize)
2233 return 0;
2236 t = GetTimer() - t;
2237 tt = t*0.000001f; audio_time_usage+=tt;
2238 if (playsize > sh_audio->a_out_buffer_len) {
2239 playsize = sh_audio->a_out_buffer_len;
2240 if (audio_eof)
2241 playflags |= AOPLAY_FINAL_CHUNK;
2243 if (!playsize)
2244 return 1;
2246 // play audio:
2247 current_module="play_audio";
2249 // Is this pts value actually useful for the aos that access it?
2250 // They're obviously badly broken in the way they handle av sync;
2251 // would not having access to this make them more broken?
2252 ao_data.pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2253 playsize = mpctx->audio_out->play(sh_audio->a_out_buffer, playsize, playflags);
2255 if (playsize > 0) {
2256 sh_audio->a_out_buffer_len -= playsize;
2257 memmove(sh_audio->a_out_buffer, &sh_audio->a_out_buffer[playsize],
2258 sh_audio->a_out_buffer_len);
2259 mpctx->delay += opts->playback_speed*playsize/(double)ao_data.bps;
2261 else if (audio_eof && mpctx->audio_out->get_delay() < .04) {
2262 // Sanity check to avoid hanging in case current ao doesn't output
2263 // partial chunks and doesn't check for AOPLAY_FINAL_CHUNK
2264 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Audio output truncated at end.\n");
2265 sh_audio->a_out_buffer_len = 0;
2268 /* The format change isn't handled too gracefully. A more precise
2269 * implementation would require draining buffered old-format audio
2270 * while displaying video, then doing the output format switch.
2272 if (format_change) {
2273 uninit_player(mpctx, INITIALIZED_AO);
2274 reinit_audio_chain(mpctx);
2277 return 1;
2280 static int sleep_until_update(struct MPContext *mpctx, float *time_frame,
2281 float *aq_sleep_time)
2283 struct MPOpts *opts = &mpctx->opts;
2284 int frame_time_remaining = 0;
2285 current_module="calc_sleep_time";
2287 *time_frame -= get_relative_time(mpctx); // reset timer
2289 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
2290 float delay = mpctx->audio_out->get_delay();
2291 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "delay=%f\n", delay);
2293 if (opts->autosync) {
2295 * Adjust this raw delay value by calculating the expected
2296 * delay for this frame and generating a new value which is
2297 * weighted between the two. The higher autosync is, the
2298 * closer to the delay value gets to that which "-nosound"
2299 * would have used, and the longer it will take for A/V
2300 * sync to settle at the right value (but it eventually will.)
2301 * This settling time is very short for values below 100.
2303 float predicted = mpctx->delay / opts->playback_speed + *time_frame;
2304 float difference = delay - predicted;
2305 delay = predicted + difference / (float)opts->autosync;
2308 *time_frame = delay - mpctx->delay / opts->playback_speed;
2309 *time_frame -= mpctx->video_out->flip_queue_offset;
2311 // delay = amount of audio buffered in soundcard/driver
2312 if (delay > 0.25) delay=0.25; else
2313 if (delay < 0.10) delay=0.10;
2315 if (*time_frame > delay*0.6) {
2316 // sleep time too big - may cause audio drops (buffer underrun)
2317 frame_time_remaining = 1;
2318 *time_frame = delay*0.5;
2320 } else {
2321 // If we're lagging more than 200 ms behind the right playback rate,
2322 // don't try to "catch up".
2323 // If benchmark is set always output frames as fast as possible
2324 // without sleeping.
2325 if (*time_frame < -0.2 || opts->benchmark)
2326 *time_frame = 0;
2327 *time_frame -= mpctx->video_out->flip_queue_offset;
2330 *aq_sleep_time += *time_frame;
2333 //============================== SLEEP: ===================================
2335 // flag 256 means: libvo driver does its timing (dvb card)
2336 if (*time_frame > 0.001 && !(mpctx->sh_video->output_flags&256))
2337 *time_frame = timing_sleep(mpctx, *time_frame);
2338 *time_frame += mpctx->video_out->flip_queue_offset;
2339 return frame_time_remaining;
2342 int reinit_video_chain(struct MPContext *mpctx)
2344 struct MPOpts *opts = &mpctx->opts;
2345 sh_video_t * const sh_video = mpctx->sh_video;
2346 double ar=-1.0;
2347 //================== Init VIDEO (codec & libvo) ==========================
2348 if (!opts->fixed_vo || !(mpctx->initialized_flags & INITIALIZED_VO)) {
2349 current_module="preinit_libvo";
2351 //shouldn't we set dvideo->id=-2 when we fail?
2352 //if((mpctx->video_out->preinit(vo_subdevice))!=0){
2353 if(!(mpctx->video_out=init_best_video_out(opts, mpctx->x11_state, mpctx->key_fifo, mpctx->input))){
2354 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Error opening/initializing the selected video_out (-vo) device.\n");
2355 goto err_out;
2357 mpctx->initialized_flags|=INITIALIZED_VO;
2360 if(stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_ASPECT_RATIO, &ar) != STREAM_UNSUPPORTED)
2361 mpctx->sh_video->stream_aspect = ar;
2362 current_module="init_video_filters";
2364 char* vf_arg[] = { "_oldargs_", (char*)mpctx->video_out , NULL };
2365 sh_video->vfilter = vf_open_filter(opts, NULL,"vo",vf_arg);
2367 #ifdef CONFIG_MENU
2368 if(use_menu) {
2369 char* vf_arg[] = { "_oldargs_", menu_root, NULL };
2370 vf_menu = vf_open_plugin(opts,libmenu_vfs,sh_video->vfilter,"menu",vf_arg);
2371 if(!vf_menu) {
2372 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Can't open libmenu video filter with root menu %s.\n",menu_root);
2373 use_menu = 0;
2376 if(vf_menu)
2377 sh_video->vfilter = vf_menu;
2378 #endif
2380 #ifdef CONFIG_ASS
2381 if(opts->ass_enabled) {
2382 int i;
2383 int insert = 1;
2384 if (opts->vf_settings)
2385 for (i = 0; opts->vf_settings[i].name; ++i)
2386 if (strcmp(opts->vf_settings[i].name, "ass") == 0) {
2387 insert = 0;
2388 break;
2390 if (insert) {
2391 extern vf_info_t vf_info_ass;
2392 const vf_info_t* libass_vfs[] = {&vf_info_ass, NULL};
2393 char* vf_arg[] = {"auto", "1", NULL};
2394 int retcode = 0;
2395 struct vf_instance *vf_ass = vf_open_plugin_noerr(opts, libass_vfs,
2396 sh_video->vfilter,
2397 "ass", vf_arg,
2398 &retcode);
2399 if (vf_ass)
2400 sh_video->vfilter = vf_ass;
2401 else if (retcode == -1) // vf_ass open() returns -1 if there's VO EOSD
2402 mp_msg(MSGT_CPLAYER, MSGL_V, "[ass] vf_ass not needed\n");
2403 else
2404 mp_msg(MSGT_CPLAYER,MSGL_ERR, "ASS: cannot add video filter\n");
2407 #endif
2409 sh_video->vfilter = append_filters(sh_video->vfilter, opts->vf_settings);
2411 #ifdef CONFIG_ASS
2412 if (opts->ass_enabled)
2413 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_INIT_EOSD, ass_library);
2414 #endif
2416 current_module="init_video_codec";
2418 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2419 init_best_video_codec(sh_video,video_codec_list,video_fm_list);
2420 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2422 if(!sh_video->initialized){
2423 if(!opts->fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
2424 goto err_out;
2427 mpctx->initialized_flags|=INITIALIZED_VCODEC;
2429 if (sh_video->codec)
2430 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODEC=%s\n", sh_video->codec->name);
2432 sh_video->last_pts = MP_NOPTS_VALUE;
2433 sh_video->num_buffered_pts = 0;
2434 sh_video->next_frame_time = 0;
2436 if (opts->auto_quality > 0) {
2437 // Auto quality option enabled
2438 output_quality=get_video_quality_max(sh_video);
2439 if (opts->auto_quality > output_quality)
2440 opts->auto_quality = output_quality;
2441 else
2442 output_quality = opts->auto_quality;
2443 mp_msg(MSGT_CPLAYER,MSGL_V,"AutoQ: setting quality to %d.\n",output_quality);
2444 set_video_quality(sh_video,output_quality);
2447 // ========== Init display (sh_video->disp_w*sh_video->disp_h/out_fmt) ============
2449 current_module="init_vo";
2451 return 1;
2453 err_out:
2454 mpctx->sh_video = mpctx->d_video->sh = NULL;
2455 return 0;
2458 static double update_video_nocorrect_pts(struct MPContext *mpctx)
2460 struct sh_video *sh_video = mpctx->sh_video;
2461 double frame_time = 0;
2462 struct vo *video_out = mpctx->video_out;
2463 while (!video_out->frame_loaded) {
2464 current_module = "filter_video";
2465 // In nocorrect-pts mode there is no way to properly time these frames
2466 if (vo_get_buffered_frame(video_out, 0) >= 0)
2467 break;
2468 if (vf_output_queued_frame(sh_video->vfilter))
2469 continue;
2470 unsigned char *packet = NULL;
2471 frame_time = sh_video->next_frame_time;
2472 if (mpctx->restart_playback)
2473 frame_time = 0;
2474 int in_size = video_read_frame(sh_video, &sh_video->next_frame_time,
2475 &packet, force_fps);
2476 if (in_size < 0) {
2477 #ifdef CONFIG_DVDNAV
2478 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
2479 if (mp_dvdnav_is_eof(mpctx->stream))
2480 return -1;
2481 if (mpctx->d_video)
2482 mpctx->d_video->eof = 0;
2483 if (mpctx->d_audio)
2484 mpctx->d_audio->eof = 0;
2485 mpctx->stream->eof = 0;
2486 } else
2487 #endif
2488 return -1;
2490 if (in_size > max_framesize)
2491 max_framesize = in_size;
2492 sh_video->timer += frame_time;
2493 if (mpctx->sh_audio)
2494 mpctx->delay -= frame_time;
2495 // video_read_frame can change fps (e.g. for ASF video)
2496 vo_fps = sh_video->fps;
2497 int framedrop_type = check_framedrop(mpctx, frame_time);
2498 current_module = "decode video";
2500 void *decoded_frame;
2501 #ifdef CONFIG_DVDNAV
2502 decoded_frame = mp_dvdnav_restore_smpi(mpctx, &in_size, &packet, NULL);
2503 if (in_size >= 0 && !decoded_frame)
2504 #endif
2505 decoded_frame = decode_video(sh_video, packet, in_size, framedrop_type,
2506 sh_video->pts);
2507 #ifdef CONFIG_DVDNAV
2508 // Save last still frame for future display
2509 mp_dvdnav_save_smpi(mpctx, in_size, packet, decoded_frame);
2510 #endif
2511 if (decoded_frame) {
2512 current_module = "filter video";
2513 if (filter_video(sh_video, decoded_frame, sh_video->pts))
2514 if (!video_out->config_ok)
2515 break;
2518 return frame_time;
2521 static void determine_frame_pts(struct MPContext *mpctx)
2523 struct sh_video *sh_video = mpctx->sh_video;
2524 struct MPOpts *opts = &mpctx->opts;
2526 if (opts->user_pts_assoc_mode) {
2527 sh_video->pts_assoc_mode = opts->user_pts_assoc_mode;
2528 } else if (sh_video->pts_assoc_mode == 0) {
2529 if (mpctx->d_video->demuxer->timestamp_type == TIMESTAMP_TYPE_PTS
2530 && sh_video->codec_reordered_pts != MP_NOPTS_VALUE)
2531 sh_video->pts_assoc_mode = 1;
2532 else
2533 sh_video->pts_assoc_mode = 2;
2534 } else {
2535 int probcount1 = sh_video->num_reordered_pts_problems;
2536 int probcount2 = sh_video->num_sorted_pts_problems;
2537 if (sh_video->pts_assoc_mode == 2) {
2538 int tmp = probcount1;
2539 probcount1 = probcount2;
2540 probcount2 = tmp;
2542 if (probcount1 >= probcount2 * 1.5 + 2) {
2543 sh_video->pts_assoc_mode = 3 - sh_video->pts_assoc_mode;
2544 mp_msg(MSGT_CPLAYER, MSGL_V, "Switching to pts association mode "
2545 "%d.\n", sh_video->pts_assoc_mode);
2548 sh_video->pts = sh_video->pts_assoc_mode == 1 ?
2549 sh_video->codec_reordered_pts : sh_video->sorted_pts;
2552 static double update_video(struct MPContext *mpctx)
2554 struct sh_video *sh_video = mpctx->sh_video;
2555 struct vo *video_out = mpctx->video_out;
2556 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_SET_OSD_OBJ,
2557 mpctx->osd); // hack for vf_expand
2558 if (!mpctx->opts.correct_pts)
2559 return update_video_nocorrect_pts(mpctx);
2561 double pts;
2563 bool hit_eof = false;
2564 while (!video_out->frame_loaded) {
2565 current_module = "filter_video";
2566 if (vo_get_buffered_frame(video_out, hit_eof) >= 0)
2567 break;
2568 // XXX Time used in this call is not counted in any performance
2569 // timer now, OSD time is not updated correctly for filter-added frames
2570 if (vf_output_queued_frame(sh_video->vfilter))
2571 continue;
2572 if (hit_eof)
2573 return -1;
2574 unsigned char *packet = NULL;
2575 int in_size = ds_get_packet_pts(mpctx->d_video, &packet, &pts);
2576 if (pts != MP_NOPTS_VALUE)
2577 pts += mpctx->video_offset;
2578 if (in_size < 0) {
2579 // try to extract last frames in case of decoder lag
2580 in_size = 0;
2581 pts = MP_NOPTS_VALUE;
2582 hit_eof = true;
2584 if (in_size > max_framesize)
2585 max_framesize = in_size;
2586 current_module = "decode video";
2587 int framedrop_type = check_framedrop(mpctx, sh_video->frametime);
2588 void *decoded_frame = decode_video(sh_video, packet, in_size,
2589 framedrop_type, pts);
2590 if (decoded_frame) {
2591 determine_frame_pts(mpctx);
2592 current_module = "filter video";
2593 if (filter_video(sh_video, decoded_frame, sh_video->pts))
2594 if (!video_out->config_ok)
2595 break; // We'd likely hang in this loop otherwise
2599 pts = video_out->next_pts;
2600 if (pts == MP_NOPTS_VALUE) {
2601 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Video pts after filters MISSING\n");
2602 // Try to use decoder pts from before filters
2603 pts = sh_video->pts;
2604 if (pts == MP_NOPTS_VALUE)
2605 pts = sh_video->last_pts;
2607 sh_video->pts = pts;
2608 if (sh_video->last_pts == MP_NOPTS_VALUE)
2609 sh_video->last_pts = sh_video->pts;
2610 else if (sh_video->last_pts > sh_video->pts) {
2611 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Decreasing video pts: %f < %f\n",
2612 sh_video->pts, sh_video->last_pts);
2613 /* If the difference in pts is small treat it as jitter around the
2614 * right value (possibly caused by incorrect timestamp ordering) and
2615 * just show this frame immediately after the last one.
2616 * Treat bigger differences as timestamp resets and start counting
2617 * timing of later frames from the position of this one. */
2618 if (sh_video->last_pts - sh_video->pts > 0.5)
2619 sh_video->last_pts = sh_video->pts;
2620 else
2621 sh_video->pts = sh_video->last_pts;
2623 double frame_time = sh_video->pts - sh_video->last_pts;
2624 sh_video->last_pts = sh_video->pts;
2625 sh_video->timer += frame_time;
2626 if (mpctx->sh_audio)
2627 mpctx->delay -= frame_time;
2628 return frame_time;
2631 void pause_player(struct MPContext *mpctx)
2633 if (mpctx->paused)
2634 return;
2635 mpctx->paused = 1;
2636 mpctx->step_frames = 0;
2637 mpctx->time_frame -= get_relative_time(mpctx);
2639 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2640 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2642 if (mpctx->audio_out && mpctx->sh_audio)
2643 mpctx->audio_out->pause(); // pause audio, keep data if possible
2646 void unpause_player(struct MPContext *mpctx)
2648 if (!mpctx->paused)
2649 return;
2650 mpctx->paused = 0;
2652 if (mpctx->audio_out && mpctx->sh_audio)
2653 mpctx->audio_out->resume(); // resume audio
2654 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok
2655 && !mpctx->step_frames)
2656 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL); // resume video
2657 (void)get_relative_time(mpctx); // ignore time that passed during pause
2660 void add_step_frame(struct MPContext *mpctx)
2662 mpctx->step_frames++;
2663 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2664 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2665 unpause_player(mpctx);
2668 static void pause_loop(struct MPContext *mpctx)
2670 struct MPOpts *opts = &mpctx->opts;
2671 mp_cmd_t* cmd;
2672 if (!opts->quiet) {
2673 // Small hack to display the pause message on the OSD line.
2674 // The pause string is: "\n == PAUSE == \r" so we need to
2675 // take the first and the last char out
2676 if (opts->term_osd && !mpctx->sh_video) {
2677 char msg[128] = _("\n ===== PAUSE =====\r");
2678 int mlen = strlen(msg);
2679 msg[mlen-1] = '\0';
2680 set_osd_msg(OSD_MSG_PAUSE, 1, 0, "%s", msg+1);
2681 update_osd_msg(mpctx);
2682 } else
2683 mp_tmsg(MSGT_CPLAYER,MSGL_STATUS,"\n ===== PAUSE =====\r");
2684 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_PAUSED\n");
2687 while ( (cmd = mp_input_get_cmd(mpctx->input, 20, 1)) == NULL
2688 || cmd->id == MP_CMD_SET_MOUSE_POS || cmd->pausing == 4) {
2689 if (cmd) {
2690 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
2691 run_command(mpctx, cmd);
2692 mp_cmd_free(cmd);
2693 continue;
2695 if (mpctx->sh_video && mpctx->video_out)
2696 vo_check_events(mpctx->video_out);
2697 #ifdef CONFIG_MENU
2698 if (vf_menu)
2699 vf_menu_pause_update(vf_menu);
2700 #endif
2701 usec_sleep(20000);
2702 update_osd_msg(mpctx);
2703 int hack = vo_osd_changed(0);
2704 vo_osd_changed(hack);
2705 if (hack)
2706 break;
2711 // Find the right mute status and record position for new file position
2712 static void edl_seek_reset(MPContext *mpctx)
2714 mpctx->edl_muted = 0;
2715 next_edl_record = edl_records;
2717 while (next_edl_record) {
2718 if (next_edl_record->start_sec >= mpctx->sh_video->pts)
2719 break;
2721 if (next_edl_record->action == EDL_MUTE)
2722 mpctx->edl_muted = !mpctx->edl_muted;
2723 next_edl_record = next_edl_record->next;
2725 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2726 mixer_mute(&mpctx->mixer);
2730 // Execute EDL command for the current position if one exists
2731 static void edl_update(MPContext *mpctx)
2733 if (!next_edl_record)
2734 return;
2736 if (!mpctx->sh_video) {
2737 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot use EDL without video, disabling.\n");
2738 free_edl(edl_records);
2739 next_edl_record = NULL;
2740 edl_records = NULL;
2741 return;
2744 if (mpctx->sh_video->pts >= next_edl_record->start_sec) {
2745 if (next_edl_record->action == EDL_SKIP) {
2746 mpctx->osd_function = OSD_FFW;
2747 mpctx->abs_seek_pos = 0;
2748 mpctx->rel_seek_secs = next_edl_record->length_sec;
2749 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_SKIP: start [%f], stop "
2750 "[%f], length [%f]\n", next_edl_record->start_sec,
2751 next_edl_record->stop_sec, next_edl_record->length_sec);
2753 else if (next_edl_record->action == EDL_MUTE) {
2754 mpctx->edl_muted = !mpctx->edl_muted;
2755 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2756 mixer_mute(&mpctx->mixer);
2757 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_MUTE: [%f]\n",
2758 next_edl_record->start_sec );
2760 next_edl_record = next_edl_record->next;
2764 static void reinit_decoders(struct MPContext *mpctx)
2766 reinit_video_chain(mpctx);
2767 reinit_audio_chain(mpctx);
2768 mp_property_do("sub", M_PROPERTY_SET, &mpctx->global_sub_pos, mpctx);
2771 static void seek_reset(struct MPContext *mpctx)
2773 if (mpctx->sh_video) {
2774 current_module = "seek_video_reset";
2775 resync_video_stream(mpctx->sh_video);
2776 mpctx->sh_video->timer = 0;
2777 vo_seek_reset(mpctx->video_out);
2778 mpctx->sh_video->timer = 0;
2779 mpctx->sh_video->num_buffered_pts = 0;
2780 mpctx->sh_video->last_pts = MP_NOPTS_VALUE;
2781 mpctx->delay = 0;
2782 mpctx->time_frame = 0;
2783 mpctx->restart_playback = true;
2784 // Not all demuxers set d_video->pts during seek, so this value
2785 // (which is used by at least vobsub and edl code below) may
2786 // be completely wrong (probably 0).
2787 mpctx->sh_video->pts = mpctx->d_video->pts + mpctx->video_offset;
2788 update_subtitles(mpctx, &mpctx->opts, mpctx->sh_video,
2789 mpctx->sh_video->pts, mpctx->video_offset,
2790 mpctx->d_sub, 1);
2791 update_teletext(mpctx->sh_video, mpctx->demuxer, 1);
2794 if (mpctx->sh_audio) {
2795 current_module = "seek_audio_reset";
2796 resync_audio_stream(mpctx->sh_audio);
2797 mpctx->audio_out->reset(); // stop audio, throwing away buffered data
2798 mpctx->sh_audio->a_buffer_len = 0;
2799 mpctx->sh_audio->a_out_buffer_len = 0;
2800 if (!mpctx->sh_video)
2801 update_subtitles(mpctx, &mpctx->opts, NULL, mpctx->sh_audio->pts,
2802 mpctx->video_offset, mpctx->d_sub, 1);
2805 if (vo_vobsub && mpctx->sh_video) {
2806 current_module = "seek_vobsub_reset";
2807 vobsub_seek(vo_vobsub, mpctx->sh_video->pts);
2810 edl_seek_reset(mpctx);
2812 mpctx->total_avsync_change = 0;
2813 audio_time_usage = 0; video_time_usage = 0; vout_time_usage = 0;
2814 drop_frame_cnt = 0;
2816 current_module = NULL;
2819 static bool timeline_set_part(struct MPContext *mpctx, int i)
2821 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
2822 struct timeline_part *n = mpctx->timeline + i;
2823 mpctx->timeline_part = i;
2824 mpctx->video_offset = n->start - n->source_start;
2825 if (n->source == p->source)
2826 return false;
2827 uninit_player(mpctx, INITIALIZED_VCODEC | (mpctx->opts.fixed_vo && mpctx->opts.video_id != -2 ? 0 : INITIALIZED_VO) | INITIALIZED_AO | INITIALIZED_ACODEC);
2828 mpctx->demuxer = n->source->demuxer;
2829 mpctx->d_video = mpctx->demuxer->video;
2830 mpctx->d_audio = mpctx->demuxer->audio;
2831 mpctx->d_sub = mpctx->demuxer->sub;
2832 mpctx->sh_video = mpctx->d_video->sh;
2833 mpctx->sh_audio = mpctx->d_audio->sh;
2834 return true;
2837 // Given pts, switch playback to the corresponding part.
2838 // Return offset within that part.
2839 static double timeline_set_from_time(struct MPContext *mpctx, double pts,
2840 bool *need_reset)
2842 if (pts < 0)
2843 pts = 0;
2844 for (int i = 0; i < mpctx->num_timeline_parts; i++) {
2845 struct timeline_part *p = mpctx->timeline + i;
2846 if (pts < (p+1)->start) {
2847 *need_reset = timeline_set_part(mpctx, i);
2848 return pts - p->start + p->source_start;
2851 return -1;
2855 // style & SEEK_ABSOLUTE == 0 means seek relative to current position, == 1 means absolute
2856 // style & SEEK_FACTOR == 0 means amount in seconds, == 2 means fraction of file length
2857 // return -1 if seek failed (non-seekable stream?), 0 otherwise
2858 static int seek(MPContext *mpctx, double amount, int style)
2860 current_module = "seek";
2861 if (mpctx->stop_play == AT_END_OF_FILE)
2862 mpctx->stop_play = KEEP_PLAYING;
2863 if (style & SEEK_FACTOR
2864 || style & SEEK_ABSOLUTE && amount < mpctx->last_chapter_pts
2865 || amount < 0)
2866 mpctx->last_chapter_seek = -1;
2867 if (mpctx->timeline && style & SEEK_FACTOR) {
2868 amount *= mpctx->timeline[mpctx->num_timeline_parts].start;
2869 style &= ~SEEK_FACTOR;
2871 if ((mpctx->demuxer->accurate_seek || mpctx->timeline) && mpctx->sh_video
2872 && !(style & (SEEK_ABSOLUTE | SEEK_FACTOR))) {
2873 style |= SEEK_ABSOLUTE;
2874 if (amount > 0)
2875 style |= SEEK_FORWARD;
2876 else
2877 style |= SEEK_BACKWARD;
2878 amount += mpctx->sh_video->pts;
2881 /* At least the liba52 decoder wants to read from the input stream
2882 * during initialization, so reinit must be done after the demux_seek()
2883 * call that clears possible stream EOF. */
2884 bool need_reset = false;
2885 if (mpctx->timeline) {
2886 amount = timeline_set_from_time(mpctx, amount, &need_reset);
2887 if (amount == -1) {
2888 mpctx->stop_play = AT_END_OF_FILE;
2889 // Clear audio from current position
2890 if (mpctx->sh_audio) {
2891 mpctx->audio_out->reset();
2892 mpctx->sh_audio->a_buffer_len = 0;
2893 mpctx->sh_audio->a_out_buffer_len = 0;
2895 return -1;
2898 int seekresult = demux_seek(mpctx->demuxer, amount, audio_delay, style);
2899 if (need_reset)
2900 reinit_decoders(mpctx);
2901 if (seekresult == 0)
2902 return -1;
2904 seek_reset(mpctx);
2905 return 0;
2909 double get_time_length(struct MPContext *mpctx)
2911 if (mpctx->timeline)
2912 return mpctx->timeline[mpctx->num_timeline_parts].start;
2914 struct demuxer *demuxer = mpctx->demuxer;
2915 double get_time_ans;
2916 // <= 0 means DEMUXER_CTRL_NOTIMPL or DEMUXER_CTRL_DONTKNOW
2917 if (demux_control(demuxer, DEMUXER_CTRL_GET_TIME_LENGTH,
2918 (void *) &get_time_ans) > 0)
2919 return get_time_ans;
2921 struct sh_video *sh_video = mpctx->d_video->sh;
2922 struct sh_audio *sh_audio = mpctx->d_audio->sh;
2923 if (sh_video && sh_video->i_bps && sh_audio && sh_audio->i_bps)
2924 return (double) (demuxer->movi_end - demuxer->movi_start) /
2925 (sh_video->i_bps + sh_audio->i_bps);
2926 if (sh_video && sh_video->i_bps)
2927 return (double) (demuxer->movi_end - demuxer->movi_start) /
2928 sh_video->i_bps;
2929 if (sh_audio && sh_audio->i_bps)
2930 return (double) (demuxer->movi_end - demuxer->movi_start) /
2931 sh_audio->i_bps;
2932 return 0;
2935 /* If there are timestamps from stream level then use those (for example
2936 * DVDs can have consistent times there while the MPEG-level timestamps
2937 * reset). */
2938 double get_current_time(struct MPContext *mpctx)
2940 struct demuxer *demuxer = mpctx->demuxer;
2941 if (demuxer->stream_pts != MP_NOPTS_VALUE)
2942 return demuxer->stream_pts;
2943 struct sh_video *sh_video = demuxer->video->sh;
2944 if (sh_video)
2945 return sh_video->pts;
2946 return playing_audio_pts(mpctx);
2949 int get_percent_pos(struct MPContext *mpctx)
2951 struct demuxer *demuxer = mpctx->demuxer;
2952 int ans = 0;
2953 if (mpctx->timeline)
2954 ans = get_current_time(mpctx) * 100 /
2955 mpctx->timeline[mpctx->num_timeline_parts].start;
2956 else if (demux_control(demuxer, DEMUXER_CTRL_GET_PERCENT_POS, &ans) > 0)
2958 else {
2959 int len = (demuxer->movi_end - demuxer->movi_start) / 100;
2960 off_t pos = demuxer->filepos > 0 ?
2961 demuxer->filepos : stream_tell(demuxer->stream);
2962 if (len > 0)
2963 ans = (pos - demuxer->movi_start) / len;
2964 else
2965 ans = 0;
2967 if (ans < 0)
2968 ans = 0;
2969 if (ans > 100)
2970 ans = 100;
2971 return ans;
2974 // -2 is no chapters, -1 is before first chapter
2975 int get_current_chapter(struct MPContext *mpctx)
2977 double current_pts = get_current_time(mpctx);
2978 if (!mpctx->chapters)
2979 return FFMAX(mpctx->last_chapter_seek,
2980 demuxer_get_current_chapter(mpctx->demuxer, current_pts));
2982 int i;
2983 for (i = 1; i < mpctx->num_chapters; i++)
2984 if (current_pts < mpctx->chapters[i].start)
2985 break;
2986 return FFMAX(mpctx->last_chapter_seek, i - 1);
2989 // currently returns a string allocated with malloc, not talloc
2990 char *chapter_display_name(struct MPContext *mpctx, int chapter)
2992 if (!mpctx->chapters || !mpctx->sh_video)
2993 return demuxer_chapter_display_name(mpctx->demuxer, chapter);
2994 return strdup(mpctx->chapters[chapter].name);
2997 int seek_chapter(struct MPContext *mpctx, int chapter, double *seek_pts,
2998 char **chapter_name)
3000 mpctx->last_chapter_seek = -1;
3001 if (!mpctx->chapters || !mpctx->sh_video) {
3002 int res = demuxer_seek_chapter(mpctx->demuxer, chapter, seek_pts,
3003 chapter_name);
3004 if (res >= 0) {
3005 if (*seek_pts == -1)
3006 seek_reset(mpctx);
3007 else {
3008 mpctx->last_chapter_seek = res;
3009 mpctx->last_chapter_pts = *seek_pts;
3012 return res;
3015 if (chapter >= mpctx->num_chapters)
3016 return -1;
3017 if (chapter < 0)
3018 chapter = 0;
3019 *seek_pts = mpctx->chapters[chapter].start;
3020 mpctx->last_chapter_seek = chapter;
3021 mpctx->last_chapter_pts = *seek_pts;
3022 if (chapter_name)
3023 *chapter_name = talloc_strdup(NULL, mpctx->chapters[chapter].name);
3024 return chapter;
3027 static int find_ordered_chapter_sources(struct MPContext *mpctx,
3028 struct content_source *sources,
3029 int num_sources,
3030 unsigned char uid_map[][16])
3032 int num_filenames = 0;
3033 char **filenames = NULL;
3034 if (num_sources > 1) {
3035 mp_msg(MSGT_CPLAYER, MSGL_INFO, "This file references data from "
3036 "other sources.\n");
3037 if (mpctx->stream->type != STREAMTYPE_FILE) {
3038 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Playback source is not a "
3039 "normal disk file. Will not search for related files.\n");
3040 } else {
3041 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Will scan other files in the "
3042 "same directory to find referenced sources.\n");
3043 filenames = find_files(mpctx->demuxer->filename, ".mkv",
3044 &num_filenames);
3048 int num_left = num_sources - 1;
3049 for (int i = 0; i < num_filenames && num_left > 0; i++) {
3050 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Checking file %s\n",
3051 filename_recode(filenames[i]));
3052 int format;
3053 struct stream *s = open_stream(filenames[i], &mpctx->opts, &format);
3054 if (!s)
3055 continue;
3056 struct demuxer *d = demux_open(&mpctx->opts, s, DEMUXER_TYPE_MATROSKA,
3057 mpctx->opts.audio_id,
3058 mpctx->opts.video_id,
3059 mpctx->opts.sub_id, filenames[i]);
3060 if (!d) {
3061 free_stream(s);
3062 continue;
3064 if (d->file_format == DEMUXER_TYPE_MATROSKA) {
3065 for (int i = 1; i < num_sources; i++) {
3066 if (sources[i].demuxer)
3067 continue;
3068 if (!memcmp(uid_map[i], d->matroska_data.segment_uid, 16)) {
3069 mp_msg(MSGT_CPLAYER, MSGL_INFO,"Match for source %d: %s\n",
3070 i, filename_recode(d->filename));
3071 sources[i].stream = s;
3072 sources[i].demuxer = d;
3073 num_left--;
3074 goto match;
3078 free_demuxer(d);
3079 free_stream(s);
3080 continue;
3081 match:
3084 talloc_free(filenames);
3085 if (num_left) {
3086 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Failed to find ordered chapter part!\n"
3087 "There will be parts MISSING from the video!\n");
3088 for (int i = 1, j = 1; i < num_sources; i++)
3089 if (sources[i].demuxer) {
3090 sources[j] = sources[i];
3091 memcpy(uid_map[j], uid_map[i], 16);
3092 j++;
3095 return num_sources - num_left;
3098 static void build_ordered_chapter_timeline(struct MPContext *mpctx)
3100 if (!mpctx->opts.ordered_chapters) {
3101 mp_msg(MSGT_CPLAYER, MSGL_INFO, "File uses ordered chapters, but "
3102 "you have disabled support for them. Ignoring.\n");
3103 return;
3106 mp_msg(MSGT_CPLAYER, MSGL_INFO, "File uses ordered chapters, will build "
3107 "edit timeline.\n");
3109 struct demuxer *demuxer = mpctx->demuxer;
3110 struct matroska_data *m = &demuxer->matroska_data;
3112 // +1 because sources/uid_map[0] is original file even if all chapters
3113 // actually use other sources and need separate entries
3114 struct content_source *sources = talloc_array_ptrtype(NULL, sources,
3115 m->num_ordered_chapters+1);
3116 sources[0].stream = mpctx->stream;
3117 sources[0].demuxer = mpctx->demuxer;
3118 unsigned char uid_map[m->num_ordered_chapters+1][16];
3119 int num_sources = 1;
3120 memcpy(uid_map[0], m->segment_uid, 16);
3122 for (int i = 0; i < m->num_ordered_chapters; i++) {
3123 struct matroska_chapter *c = m->ordered_chapters + i;
3124 if (!c->has_segment_uid)
3125 memcpy(c->segment_uid, m->segment_uid, 16);
3127 for (int j = 0; j < num_sources; j++)
3128 if (!memcmp(c->segment_uid, uid_map[j], 16))
3129 goto found1;
3130 memcpy(uid_map[num_sources], c->segment_uid, 16);
3131 sources[num_sources] = (struct content_source){};
3132 num_sources++;
3133 found1:
3137 num_sources = find_ordered_chapter_sources(mpctx, sources, num_sources,
3138 uid_map);
3141 // +1 for terminating chapter with start time marking end of last real one
3142 struct timeline_part *timeline = talloc_array_ptrtype(NULL, timeline,
3143 m->num_ordered_chapters + 1);
3144 struct chapter *chapters = talloc_array_ptrtype(NULL, chapters,
3145 m->num_ordered_chapters);
3146 uint64_t starttime = 0;
3147 uint64_t missing_time = 0;
3148 int part_count = 0;
3149 int num_chapters = 0;
3150 uint64_t prev_part_offset = 0;
3151 for (int i = 0; i < m->num_ordered_chapters; i++) {
3152 struct matroska_chapter *c = m->ordered_chapters + i;
3154 int j;
3155 for (j = 0; j < num_sources; j++) {
3156 if (!memcmp(c->segment_uid, uid_map[j], 16))
3157 goto found2;
3159 missing_time += c->end - c->start;
3160 continue;
3161 found2:;
3162 chapters[num_chapters].start = starttime / 1000.;
3163 chapters[num_chapters].name = talloc_strdup(chapters, c->name);
3164 /* Only add a separate part if the time or file actually changes.
3165 * Matroska files have chapter divisions that are redundant from
3166 * timeline point of view because the same chapter structure is used
3167 * both to specify the timeline and for normal chapter information.
3168 * Removing a missing inserted external chapter can also cause this. */
3169 if (part_count == 0 || c->start != starttime + prev_part_offset
3170 || sources + j != timeline[part_count - 1].source) {
3171 timeline[part_count].source = sources + j;
3172 timeline[part_count].start = chapters[num_chapters].start;
3173 timeline[part_count].source_start = c->start / 1000.;
3174 prev_part_offset = c->start - starttime;
3175 part_count++;
3177 starttime += c->end - c->start;
3178 num_chapters++;
3180 timeline[part_count].start = starttime / 1000.;
3182 if (!part_count) {
3183 // None of the parts come from the file itself???
3184 talloc_free(sources);
3185 talloc_free(timeline);
3186 talloc_free(chapters);
3187 return;
3190 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline contains %d parts from %d "
3191 "sources. Total length %.3f seconds.\n", part_count, num_sources,
3192 timeline[part_count].start);
3193 if (missing_time)
3194 mp_msg(MSGT_CPLAYER, MSGL_ERR, "There are %.3f seconds missing "
3195 "from the timeline!\n", missing_time / 1000.);
3196 mp_msg(MSGT_CPLAYER, MSGL_V, "Source files:\n");
3197 for (int i = 0; i < num_sources; i++)
3198 mp_msg(MSGT_CPLAYER, MSGL_V, "%d: %s\n", i,
3199 filename_recode(sources[i].demuxer->filename));
3200 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline parts: (number, start, "
3201 "source_start, source):\n");
3202 for (int i = 0; i < part_count; i++) {
3203 struct timeline_part *p = timeline + i;
3204 mp_msg(MSGT_CPLAYER, MSGL_V, "%3d %9.3f %9.3f %3td\n", i, p->start,
3205 p->source_start, p->source - sources);
3207 mp_msg(MSGT_CPLAYER, MSGL_V, "END %9.3f\n", timeline[part_count].start);
3208 mpctx->sources = sources;
3209 mpctx->num_sources = num_sources;
3210 mpctx->timeline = timeline;
3211 mpctx->num_timeline_parts = part_count;
3212 mpctx->num_chapters = num_chapters;
3213 mpctx->chapters = chapters;
3215 mpctx->timeline_part = 0;
3216 mpctx->demuxer = timeline[0].source->demuxer;
3220 static int read_keys(void *ctx, int fd)
3222 getch2(ctx);
3223 return mplayer_get_key(ctx, 0);
3227 /* This preprocessor directive is a hack to generate a mplayer-nomain.o object
3228 * file for some tools to link against. */
3229 #ifndef DISABLE_MAIN
3230 int main(int argc,char* argv[]){
3233 char * mem_ptr;
3235 // movie info:
3237 /* Flag indicating whether MPlayer should exit without playing anything. */
3238 int opt_exit = 0;
3239 int i;
3241 struct MPContext *mpctx = &(struct MPContext){
3242 .osd_function = OSD_PLAY,
3243 .begin_skip = MP_NOPTS_VALUE,
3244 .play_tree_step = 1,
3245 .global_sub_pos = -1,
3246 .set_of_sub_pos = -1,
3247 .file_format = DEMUXER_TYPE_UNKNOWN,
3248 .last_dvb_step = 1,
3251 InitTimer();
3252 srand(GetTimerMS());
3254 mp_msg_init();
3255 set_av_log_callback();
3257 #ifdef CONFIG_X11
3258 mpctx->x11_state = vo_x11_init_state();
3259 #endif
3260 struct MPOpts *opts = &mpctx->opts;
3261 set_default_mplayer_options(opts);
3262 // Create the config context and register the options
3263 mpctx->mconfig = m_config_new(opts, cfg_include);
3264 m_config_register_options(mpctx->mconfig,mplayer_opts);
3265 m_config_register_options(mpctx->mconfig, common_opts);
3266 mp_input_register_options(mpctx->mconfig);
3268 // Preparse the command line
3269 m_config_preparse_command_line(mpctx->mconfig,argc,argv);
3271 #if (defined(__MINGW32__) || defined(__CYGWIN__)) && defined(CONFIG_WIN32DLL)
3272 set_path_env();
3273 #endif
3275 #ifdef CONFIG_TV
3276 stream_tv_defaults.immediate = 1;
3277 #endif
3279 parse_cfgfiles(mpctx, mpctx->mconfig);
3281 mpctx->playtree = m_config_parse_mp_command_line(mpctx->mconfig, argc, argv);
3282 if(mpctx->playtree == NULL)
3283 opt_exit = 1;
3284 else {
3285 mpctx->playtree = play_tree_cleanup(mpctx->playtree);
3286 if(mpctx->playtree) {
3287 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,mpctx->mconfig);
3288 if(mpctx->playtree_iter) {
3289 if(play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
3290 play_tree_iter_free(mpctx->playtree_iter);
3291 mpctx->playtree_iter = NULL;
3293 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,1);
3297 mpctx->key_fifo = mp_fifo_create(opts);
3299 print_version("MPlayer");
3301 #if defined(__MINGW32__) || defined(__CYGWIN__)
3303 HMODULE kernel32 = GetModuleHandle("Kernel32.dll");
3304 BOOL WINAPI (*setDEP)(DWORD) = NULL;
3305 BOOL WINAPI (*setDllDir)(LPCTSTR) = NULL;
3306 if (kernel32) {
3307 setDEP = GetProcAddress(kernel32, "SetProcessDEPPolicy");
3308 setDllDir = GetProcAddress(kernel32, "SetDllDirectoryA");
3310 if (setDEP) setDEP(3);
3311 if (setDllDir) setDllDir("");
3313 // stop Windows from showing all kinds of annoying error dialogs
3314 SetErrorMode(0x8003);
3315 // request 1ms timer resolution
3316 timeBeginPeriod(1);
3317 #endif
3319 #ifdef CONFIG_PRIORITY
3320 set_priority();
3321 #endif
3323 if (codec_path)
3324 set_codec_path(codec_path);
3326 if(opts->video_driver_list && strcmp(opts->video_driver_list[0],"help")==0){
3327 list_video_out();
3328 opt_exit = 1;
3331 if(opts->audio_driver_list && strcmp(opts->audio_driver_list[0],"help")==0){
3332 list_audio_out();
3333 opt_exit = 1;
3336 /* Check codecs.conf. */
3337 if(!codecs_file || !parse_codec_cfg(codecs_file)){
3338 if(!parse_codec_cfg(mem_ptr=get_path("codecs.conf"))){
3339 if(!parse_codec_cfg(MPLAYER_CONFDIR "/codecs.conf")){
3340 if(!parse_codec_cfg(NULL)){
3341 exit_player_with_rc(mpctx, EXIT_NONE, 0);
3343 mp_tmsg(MSGT_CPLAYER,MSGL_V,"Using built-in default codecs.conf.\n");
3346 free( mem_ptr ); // release the buffer created by get_path()
3349 if(audio_codec_list && strcmp(audio_codec_list[0],"help")==0){
3350 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available audio codecs:\n");
3351 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AUDIO_CODECS\n");
3352 list_codecs(1);
3353 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3354 opt_exit = 1;
3356 if(video_codec_list && strcmp(video_codec_list[0],"help")==0){
3357 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available video codecs:\n");
3358 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODECS\n");
3359 list_codecs(0);
3360 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3361 opt_exit = 1;
3363 if(video_fm_list && strcmp(video_fm_list[0],"help")==0){
3364 vfm_help();
3365 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3366 opt_exit = 1;
3368 if(audio_fm_list && strcmp(audio_fm_list[0],"help")==0){
3369 afm_help();
3370 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3371 opt_exit = 1;
3373 if(af_cfg.list && strcmp(af_cfg.list[0],"help")==0){
3374 af_help();
3375 printf("\n");
3376 opt_exit = 1;
3378 #ifdef CONFIG_X11
3379 if(vo_fstype_list && strcmp(vo_fstype_list[0],"help")==0){
3380 fstype_help();
3381 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3382 opt_exit = 1;
3384 #endif
3385 if((opts->demuxer_name && strcmp(opts->demuxer_name,"help")==0) ||
3386 (opts->audio_demuxer_name && strcmp(opts->audio_demuxer_name,"help")==0) ||
3387 (opts->sub_demuxer_name && strcmp(opts->sub_demuxer_name,"help")==0)){
3388 demuxer_help();
3389 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
3390 opt_exit = 1;
3392 if (opts->list_properties) {
3393 property_print_help();
3394 opt_exit = 1;
3397 if(opt_exit)
3398 exit_player(mpctx, EXIT_NONE);
3400 if (!mpctx->filename && !opts->player_idle_mode) {
3401 // no file/vcd/dvd -> show HELP:
3402 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", mp_gtext(help_text));
3403 exit_player_with_rc(mpctx, EXIT_NONE, 0);
3406 /* Display what configure line was used */
3407 mp_msg(MSGT_CPLAYER, MSGL_V, "Configuration: " CONFIGURATION "\n");
3409 // Many users forget to include command line in bugreports...
3410 if( mp_msg_test(MSGT_CPLAYER,MSGL_V) ){
3411 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "CommandLine:");
3412 for(i=1;i<argc;i++)mp_msg(MSGT_CPLAYER, MSGL_INFO," '%s'",argv[i]);
3413 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
3416 //------ load global data first ------
3418 mpctx->osd = osd_create();
3420 // check font
3421 #ifdef CONFIG_FREETYPE
3422 init_freetype();
3423 #endif
3424 #ifdef CONFIG_FONTCONFIG
3425 if(font_fontconfig <= 0)
3427 #endif
3428 #ifdef CONFIG_BITMAP_FONT
3429 if(font_name){
3430 vo_font=read_font_desc(font_name,font_factor,verbose>1);
3431 if(!vo_font) mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load bitmap font: %s\n",
3432 filename_recode(font_name));
3433 } else {
3434 // try default:
3435 vo_font=read_font_desc( mem_ptr=get_path("font/font.desc"),font_factor,verbose>1);
3436 free(mem_ptr); // release the buffer created by get_path()
3437 if(!vo_font)
3438 vo_font=read_font_desc(MPLAYER_DATADIR "/font/font.desc",font_factor,verbose>1);
3440 if (sub_font_name)
3441 mpctx->osd->sub_font = read_font_desc(sub_font_name, font_factor, verbose>1);
3442 else
3443 mpctx->osd->sub_font = vo_font;
3444 #endif
3445 #ifdef CONFIG_FONTCONFIG
3447 #endif
3449 #ifdef CONFIG_ASS
3450 ass_library = ass_init();
3451 #endif
3453 #ifdef HAVE_RTC
3454 if(opts->rtc)
3456 char *rtc_device = opts->rtc_device;
3457 // seteuid(0); /* Can't hurt to try to get root here */
3458 if ((rtc_fd = open(rtc_device ? rtc_device : "/dev/rtc", O_RDONLY)) < 0)
3459 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Failed to open %s: %s (it should be readable by the user.)\n",
3460 rtc_device ? rtc_device : "/dev/rtc", strerror(errno));
3461 else {
3462 unsigned long irqp = 1024; /* 512 seemed OK. 128 is jerky. */
3464 if (ioctl(rtc_fd, RTC_IRQP_SET, irqp) < 0) {
3465 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Linux RTC init error in ioctl (rtc_irqp_set %lu): %s\n", irqp, strerror(errno));
3466 mp_tmsg(MSGT_CPLAYER, MSGL_HINT, "Try adding \"echo %lu > /proc/sys/dev/rtc/max-user-freq\" to your system startup scripts.\n", irqp);
3467 close (rtc_fd);
3468 rtc_fd = -1;
3469 } else if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
3470 /* variable only by the root */
3471 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC init error in ioctl (rtc_pie_on): %s\n", strerror(errno));
3472 close (rtc_fd);
3473 rtc_fd = -1;
3474 } else
3475 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Using Linux hardware RTC timing (%ldHz).\n", irqp);
3478 if(rtc_fd<0)
3479 #endif /* HAVE_RTC */
3480 mp_msg(MSGT_CPLAYER, MSGL_V, "Using %s timing\n",
3481 opts->softsleep ? "software" : timer_name);
3483 #ifdef HAVE_TERMCAP
3484 load_termcap(NULL); // load key-codes
3485 #endif
3487 // ========== Init keyboard FIFO (connection to libvo) ============
3489 // Init input system
3490 current_module = "init_input";
3491 mpctx->input = mp_input_init(&opts->input);
3492 mp_input_add_key_fd(mpctx->input, -1,0,mplayer_get_key,NULL, mpctx->key_fifo);
3493 if(slave_mode)
3494 mp_input_add_cmd_fd(mpctx->input, 0,USE_SELECT,MP_INPUT_SLAVE_CMD_FUNC,NULL);
3495 else if (opts->consolecontrols)
3496 mp_input_add_key_fd(mpctx->input, 0, 1, read_keys, NULL, mpctx->key_fifo);
3497 // Set the libstream interrupt callback
3498 stream_set_interrupt_callback(mp_input_check_interrupt, mpctx->input);
3500 #ifdef CONFIG_MENU
3501 if(use_menu) {
3502 if(menu_cfg && menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
3503 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
3504 else {
3505 menu_cfg = get_path("menu.conf");
3506 if(menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
3507 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
3508 else {
3509 if(menu_init(mpctx, mpctx->mconfig, mpctx->input,
3510 MPLAYER_CONFDIR "/menu.conf"))
3511 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", MPLAYER_CONFDIR"/menu.conf");
3512 else {
3513 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Menu init failed.\n");
3514 use_menu = 0;
3519 #endif
3521 current_module = NULL;
3523 /// Catch signals
3524 #ifndef __MINGW32__
3525 signal(SIGCHLD,child_sighandler);
3526 #endif
3528 #ifdef CONFIG_CRASH_DEBUG
3529 prog_path = argv[0];
3530 #endif
3531 //========= Catch terminate signals: ================
3532 // terminate requests:
3533 signal(SIGTERM,exit_sighandler); // kill
3534 signal(SIGHUP,exit_sighandler); // kill -HUP / xterm closed
3536 signal(SIGINT,exit_sighandler); // Interrupt from keyboard
3538 signal(SIGQUIT,exit_sighandler); // Quit from keyboard
3539 signal(SIGPIPE,exit_sighandler); // Some window managers cause this
3540 #ifdef CONFIG_SIGHANDLER
3541 // fatal errors:
3542 signal(SIGBUS,exit_sighandler); // bus error
3543 signal(SIGSEGV,exit_sighandler); // segfault
3544 signal(SIGILL,exit_sighandler); // illegal instruction
3545 signal(SIGFPE,exit_sighandler); // floating point exc.
3546 signal(SIGABRT,exit_sighandler); // abort()
3547 #ifdef CONFIG_CRASH_DEBUG
3548 if (crash_debug)
3549 signal(SIGTRAP,exit_sighandler);
3550 #endif
3551 #endif
3553 // ******************* Now, let's see the per-file stuff ********************
3555 play_next_file:
3557 // init global sub numbers
3558 mpctx->global_sub_size = 0;
3559 memset(mpctx->sub_counts, 0, sizeof(mpctx->sub_counts));
3561 if (mpctx->filename) {
3562 load_per_protocol_config (mpctx->mconfig, mpctx->filename);
3563 load_per_extension_config (mpctx->mconfig, mpctx->filename);
3564 load_per_file_config (mpctx->mconfig, mpctx->filename);
3567 if (opts->video_driver_list)
3568 load_per_output_config (mpctx->mconfig, PROFILE_CFG_VO, opts->video_driver_list[0]);
3569 if (opts->audio_driver_list)
3570 load_per_output_config (mpctx->mconfig, PROFILE_CFG_AO, opts->audio_driver_list[0]);
3572 // We must enable getch2 here to be able to interrupt network connection
3573 // or cache filling
3574 if (opts->consolecontrols && !slave_mode) {
3575 if(mpctx->initialized_flags&INITIALIZED_GETCH2)
3576 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"WARNING: getch2_init called twice!\n");
3577 else
3578 getch2_enable(); // prepare stdin for hotkeys...
3579 mpctx->initialized_flags|=INITIALIZED_GETCH2;
3580 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[init getch2]]]\n");
3583 // =================== GUI idle loop (STOP state) ===========================
3584 while (opts->player_idle_mode && !mpctx->filename) {
3585 play_tree_t * entry = NULL;
3586 mp_cmd_t * cmd;
3587 if (mpctx->video_out && mpctx->video_out->config_ok)
3588 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
3589 while (!(cmd = mp_input_get_cmd(mpctx->input, 0, 0))) { // wait for command
3590 if (mpctx->video_out)
3591 vo_check_events(mpctx->video_out);
3592 usec_sleep(20000);
3594 switch (cmd->id) {
3595 case MP_CMD_LOADFILE:
3596 // prepare a tree entry with the new filename
3597 entry = play_tree_new();
3598 play_tree_add_file(entry, cmd->args[0].v.s);
3599 // The entry is added to the main playtree after the switch().
3600 break;
3601 case MP_CMD_LOADLIST:
3602 entry = parse_playlist_file(mpctx->mconfig, cmd->args[0].v.s);
3603 break;
3604 case MP_CMD_QUIT:
3605 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
3606 break;
3607 case MP_CMD_VO_FULLSCREEN:
3608 case MP_CMD_GET_PROPERTY:
3609 case MP_CMD_SET_PROPERTY:
3610 case MP_CMD_STEP_PROPERTY:
3611 run_command(mpctx, cmd);
3612 break;
3615 mp_cmd_free(cmd);
3617 if (entry) { // user entered a command that gave a valid entry
3618 if (mpctx->playtree) // the playtree is always a node with one child. let's clear it
3619 play_tree_free_list(mpctx->playtree->child, 1);
3620 else mpctx->playtree=play_tree_new(); // .. or make a brand new playtree
3622 if (!mpctx->playtree) continue; // couldn't make playtree! wait for next command
3624 play_tree_set_child(mpctx->playtree, entry);
3626 /* Make iterator start at the top the of tree. */
3627 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree, mpctx->mconfig);
3628 if (!mpctx->playtree_iter) continue;
3630 // find the first real item in the tree
3631 if (play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
3632 // no items!
3633 play_tree_iter_free(mpctx->playtree_iter);
3634 mpctx->playtree_iter = NULL;
3635 continue; // wait for next command
3637 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, 1);
3640 //---------------------------------------------------------------------------
3642 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
3643 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL);
3645 if (mpctx->filename) {
3646 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nPlaying %s.\n",
3647 filename_recode(mpctx->filename));
3648 if(use_filename_title && opts->vo_wintitle == NULL)
3649 opts->vo_wintitle = strdup(mp_basename2(mpctx->filename));
3652 if (edl_filename) {
3653 if (edl_records) free_edl(edl_records);
3654 next_edl_record = edl_records = edl_parse_file();
3656 if (edl_output_filename) {
3657 if (edl_fd) fclose(edl_fd);
3658 if ((edl_fd = fopen(edl_output_filename, "w")) == NULL)
3660 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Can't open EDL file [%s] for writing.\n",
3661 filename_recode(edl_output_filename));
3665 //==================== Open VOB-Sub ============================
3667 current_module="vobsub";
3668 if (vobsub_name){
3669 vo_vobsub=vobsub_open(vobsub_name,spudec_ifo,1,&vo_spudec);
3670 if(vo_vobsub==NULL)
3671 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load subtitles: %s\n",
3672 filename_recode(vobsub_name));
3673 } else if (sub_auto && mpctx->filename){
3674 /* try to autodetect vobsub from movie filename ::atmos */
3675 char *buf = strdup(mpctx->filename), *psub;
3676 char *pdot = strrchr(buf, '.');
3677 char *pslash = strrchr(buf, '/');
3678 #if defined(__MINGW32__) || defined(__CYGWIN__)
3679 if (!pslash) pslash = strrchr(buf, '\\');
3680 #endif
3681 if (pdot && (!pslash || pdot > pslash))
3682 *pdot = '\0';
3683 vo_vobsub=vobsub_open(buf,spudec_ifo,0,&vo_spudec);
3684 /* try from ~/.mplayer/sub */
3685 if(!vo_vobsub && (psub = get_path( "sub/" ))) {
3686 char *bname;
3687 int l;
3688 bname = strrchr(buf,'/');
3689 #if defined(__MINGW32__) || defined(__CYGWIN__)
3690 if(!bname) bname = strrchr(buf,'\\');
3691 #endif
3692 if(bname) bname++;
3693 else bname = buf;
3694 l = strlen(psub) + strlen(bname) + 1;
3695 psub = realloc(psub,l);
3696 strcat(psub,bname);
3697 vo_vobsub=vobsub_open(psub,spudec_ifo,0,&vo_spudec);
3698 free(psub);
3700 free(buf);
3702 if(vo_vobsub){
3703 mpctx->initialized_flags|=INITIALIZED_VOBSUB;
3704 vobsub_set_from_lang(vo_vobsub, opts->sub_lang);
3705 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
3707 // setup global sub numbering
3708 mpctx->sub_counts[SUB_SOURCE_VOBSUB] = vobsub_get_indexes_count(vo_vobsub);
3711 //============ Open & Sync STREAM --- fork cache2 ====================
3713 mpctx->stream=NULL;
3714 mpctx->demuxer=NULL;
3715 if (mpctx->d_audio) {
3716 //free_demuxer_stream(mpctx->d_audio);
3717 mpctx->d_audio=NULL;
3719 if (mpctx->d_video) {
3720 //free_demuxer_stream(d_video);
3721 mpctx->d_video=NULL;
3723 mpctx->sh_audio=NULL;
3724 mpctx->sh_video=NULL;
3726 current_module="open_stream";
3727 mpctx->stream = open_stream(mpctx->filename, opts, &mpctx->file_format);
3728 if(!mpctx->stream) { // error...
3729 mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY);
3730 goto goto_next_file;
3732 mpctx->initialized_flags|=INITIALIZED_STREAM;
3734 if(mpctx->file_format == DEMUXER_TYPE_PLAYLIST) {
3735 mp_msg(MSGT_CPLAYER, MSGL_ERR, "\nThis looks like a playlist, but "
3736 "playlist support will not be used automatically.\n"
3737 "MPlayer's playlist code is unsafe and should only be used with "
3738 "trusted sources.\nPlayback will probably fail.\n\n");
3739 #if 0
3740 play_tree_t* entry;
3741 // Handle playlist
3742 current_module="handle_playlist";
3743 mp_msg(MSGT_CPLAYER,MSGL_V,"Parsing playlist %s...\n",
3744 filename_recode(mpctx->filename));
3745 entry = parse_playtree(mpctx->stream, mpctx->mconfig, 0);
3746 mpctx->eof=playtree_add_playlist(mpctx, entry);
3747 goto goto_next_file;
3748 #endif
3750 mpctx->stream->start_pos+=seek_to_byte;
3752 if(stream_dump_type==5){
3753 unsigned char buf[4096];
3754 int len;
3755 FILE *f;
3756 current_module="dumpstream";
3757 stream_reset(mpctx->stream);
3758 stream_seek(mpctx->stream,mpctx->stream->start_pos);
3759 f=fopen(opts->stream_dump_name,"wb");
3760 if(!f){
3761 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
3762 exit_player(mpctx, EXIT_ERROR);
3764 if (opts->chapterrange[0] > 1) {
3765 int chapter = opts->chapterrange[0] - 1;
3766 stream_control(mpctx->stream, STREAM_CTRL_SEEK_TO_CHAPTER, &chapter);
3768 while(!mpctx->stream->eof && !async_quit_request){
3769 len=stream_read(mpctx->stream,buf,4096);
3770 if(len>0) {
3771 if(fwrite(buf,len,1,f) != 1) {
3772 mp_tmsg(MSGT_MENCODER,MSGL_FATAL,"%s: Error writing file.\n",opts->stream_dump_name);
3773 exit_player(mpctx, EXIT_ERROR);
3776 if (opts->chapterrange[1] > 0) {
3777 int chapter = -1;
3778 if (stream_control(mpctx->stream, STREAM_CTRL_GET_CURRENT_CHAPTER,
3779 &chapter) == STREAM_OK
3780 && chapter + 1 > opts->chapterrange[1])
3781 break;
3784 if(fclose(f)) {
3785 mp_tmsg(MSGT_MENCODER,MSGL_FATAL,"%s: Error writing file.\n",opts->stream_dump_name);
3786 exit_player(mpctx, EXIT_ERROR);
3788 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Core dumped ;)\n");
3789 exit_player_with_rc(mpctx, EXIT_EOF, 0);
3792 #ifdef CONFIG_DVDREAD
3793 if(mpctx->stream->type==STREAMTYPE_DVD){
3794 current_module="dvd lang->id";
3795 if(opts->audio_lang && opts->audio_id==-1) opts->audio_id=dvd_aid_from_lang(mpctx->stream,opts->audio_lang);
3796 if(opts->sub_lang && opts->sub_id==-1) opts->sub_id=dvd_sid_from_lang(mpctx->stream,opts->sub_lang);
3797 // setup global sub numbering
3798 mpctx->sub_counts[SUB_SOURCE_DEMUX] = dvd_number_of_subs(mpctx->stream);
3799 current_module=NULL;
3801 #endif
3803 #ifdef CONFIG_DVDNAV
3804 if(mpctx->stream->type==STREAMTYPE_DVDNAV){
3805 current_module="dvdnav lang->id";
3806 if(opts->audio_lang && opts->audio_id==-1) opts->audio_id=mp_dvdnav_aid_from_lang(mpctx->stream,opts->audio_lang);
3807 dvdsub_lang_id = -3;
3808 if(opts->sub_lang && opts->sub_id==-1)
3809 dvdsub_lang_id = opts->sub_id = mp_dvdnav_sid_from_lang(mpctx->stream,opts->sub_lang);
3810 // setup global sub numbering
3811 mpctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(mpctx->stream);
3812 current_module=NULL;
3814 #endif
3816 // CACHE2: initial prefill: 20% later: 5% (should be set by -cacheopts)
3817 goto_enable_cache:
3818 if(stream_cache_size>0){
3819 int res;
3820 float stream_cache_min_percent = opts->stream_cache_min_percent;
3821 float stream_cache_seek_min_percent = opts->stream_cache_seek_min_percent;
3822 current_module="enable_cache";
3823 res = stream_enable_cache(mpctx->stream,stream_cache_size*1024,
3824 stream_cache_size*1024*(stream_cache_min_percent / 100.0),
3825 stream_cache_size*1024*(stream_cache_seek_min_percent / 100.0));
3826 if(res == 0)
3827 if((mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY))) goto goto_next_file;
3830 //============ Open DEMUXERS --- DETECT file type =======================
3831 current_module="demux_open";
3833 mpctx->demuxer=demux_open(opts, mpctx->stream,mpctx->file_format,opts->audio_id,opts->video_id,opts->sub_id,mpctx->filename);
3835 // HACK to get MOV Reference Files working
3837 if (mpctx->demuxer && mpctx->demuxer->type==DEMUXER_TYPE_PLAYLIST)
3839 unsigned char* playlist_entry;
3840 play_tree_t *list = NULL, *entry = NULL;
3842 current_module="handle_demux_playlist";
3843 while (ds_get_packet(mpctx->demuxer->video,&playlist_entry)>0)
3845 char *temp, *bname;
3847 mp_msg(MSGT_CPLAYER,MSGL_V,"Adding file %s to element entry.\n",
3848 filename_recode(playlist_entry));
3850 bname=mp_basename(playlist_entry);
3851 if ((strlen(bname)>10) && !strncmp(bname,"qt",2) && !strncmp(bname+3,"gateQT",6))
3852 continue;
3854 if (!strcmp(playlist_entry, mpctx->filename)) // ignoring self-reference
3855 continue;
3857 entry = play_tree_new();
3859 if (mpctx->filename && !strcmp(mp_basename(playlist_entry),playlist_entry)) // add reference path of current file
3861 temp=malloc((strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))+strlen(playlist_entry)+1));
3862 if (temp)
3864 strncpy(temp, mpctx->filename, strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename)));
3865 temp[strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))]='\0';
3866 strcat(temp, playlist_entry);
3867 if (!strcmp(temp, mpctx->filename)) {
3868 free(temp);
3869 continue;
3871 play_tree_add_file(entry,temp);
3872 mp_msg(MSGT_CPLAYER,MSGL_V,"Resolving reference to %s.\n",temp);
3873 free(temp);
3876 else
3877 play_tree_add_file(entry,playlist_entry);
3879 if(!list)
3880 list = entry;
3881 else
3882 play_tree_append_entry(list,entry);
3884 free_demuxer(mpctx->demuxer);
3885 mpctx->demuxer = NULL;
3887 if (list)
3889 entry = play_tree_new();
3890 play_tree_set_child(entry,list);
3891 mpctx->stop_play = playtree_add_playlist(mpctx, entry);
3892 goto goto_next_file;
3896 if(!mpctx->demuxer) {
3897 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Failed to recognize file format.\n");
3898 goto goto_next_file;
3901 if (mpctx->demuxer->matroska_data.ordered_chapters)
3902 build_ordered_chapter_timeline(mpctx);
3904 if (!mpctx->sources) {
3905 mpctx->sources = talloc_ptrtype(NULL, mpctx->sources);
3906 *mpctx->sources = (struct content_source){.stream = mpctx->stream,
3907 .demuxer = mpctx->demuxer};
3908 mpctx->num_sources = 1;
3911 mpctx->initialized_flags|=INITIALIZED_DEMUXER;
3913 #ifdef CONFIG_ASS
3914 if (opts->ass_enabled && ass_library) {
3915 for (int j = 0; j < mpctx->num_sources; j++) {
3916 struct demuxer *d = mpctx->sources[j].demuxer;
3917 for (int i = 0; i < d->num_attachments; i++) {
3918 struct demux_attachment *att = d->attachments + i;
3919 if (use_embedded_fonts && attachment_is_font(att))
3920 ass_add_font(ass_library, att->name, att->data, att->data_size);
3924 #endif
3926 current_module="demux_open2";
3928 mpctx->d_audio=mpctx->demuxer->audio;
3929 mpctx->d_video=mpctx->demuxer->video;
3930 mpctx->d_sub=mpctx->demuxer->sub;
3932 if (ts_prog) {
3933 int tmp = ts_prog;
3934 mp_property_do("switch_program", M_PROPERTY_SET, &tmp, mpctx);
3936 // select audio stream
3937 if (mpctx->num_sources)
3938 for (int i = 0; i < mpctx->num_sources; i++)
3939 select_audio(mpctx->sources[i].demuxer, opts->audio_id,
3940 opts->audio_lang);
3941 else
3942 select_audio(mpctx->d_audio->demuxer, opts->audio_id, opts->audio_lang);
3944 // DUMP STREAMS:
3945 if((stream_dump_type)&&(stream_dump_type<4)){
3946 FILE *f;
3947 demux_stream_t *ds=NULL;
3948 current_module="dump";
3949 // select stream to dump
3950 switch(stream_dump_type){
3951 case 1: ds=mpctx->d_audio;break;
3952 case 2: ds=mpctx->d_video;break;
3953 case 3: ds=mpctx->d_sub;break;
3955 if(!ds){
3956 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"dump: FATAL: Selected stream missing!\n");
3957 exit_player(mpctx, EXIT_ERROR);
3959 // disable other streams:
3960 if(mpctx->d_audio && mpctx->d_audio!=ds) {ds_free_packs(mpctx->d_audio); mpctx->d_audio->id=-2; }
3961 if(mpctx->d_video && mpctx->d_video!=ds) {ds_free_packs(mpctx->d_video); mpctx->d_video->id=-2; }
3962 if(mpctx->d_sub && mpctx->d_sub!=ds) {ds_free_packs(mpctx->d_sub); mpctx->d_sub->id=-2; }
3963 // let's dump it!
3964 f=fopen(opts->stream_dump_name,"wb");
3965 if(!f){
3966 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
3967 exit_player(mpctx, EXIT_ERROR);
3969 while(!ds->eof){
3970 unsigned char* start;
3971 int in_size=ds_get_packet(ds,&start);
3972 if( (mpctx->demuxer->file_format==DEMUXER_TYPE_AVI || mpctx->demuxer->file_format==DEMUXER_TYPE_ASF || mpctx->demuxer->file_format==DEMUXER_TYPE_MOV)
3973 && stream_dump_type==2) fwrite(&in_size,1,4,f);
3974 if(in_size>0) fwrite(start,in_size,1,f);
3975 if (opts->chapterrange[1] > 0) {
3976 int cur_chapter = demuxer_get_current_chapter(mpctx->demuxer, 0);
3977 if(cur_chapter!=-1 && cur_chapter+1 > opts->chapterrange[1])
3978 break;
3981 fclose(f);
3982 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Core dumped ;)\n");
3983 exit_player_with_rc(mpctx, EXIT_EOF, 0);
3986 mpctx->sh_audio=mpctx->d_audio->sh;
3987 mpctx->sh_video=mpctx->d_video->sh;
3989 if(mpctx->sh_video){
3991 current_module="video_read_properties";
3992 if(!video_read_properties(mpctx->sh_video)) {
3993 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Video: Cannot read properties.\n");
3994 mpctx->sh_video=mpctx->d_video->sh=NULL;
3995 } else {
3996 mp_tmsg(MSGT_CPLAYER,MSGL_V,"[V] filefmt:%d fourcc:0x%X size:%dx%d fps:%5.3f ftime:=%6.4f\n",
3997 mpctx->demuxer->file_format,mpctx->sh_video->format, mpctx->sh_video->disp_w,mpctx->sh_video->disp_h,
3998 mpctx->sh_video->fps,mpctx->sh_video->frametime
4001 /* need to set fps here for output encoders to pick it up in their init */
4002 if(force_fps){
4003 mpctx->sh_video->fps=force_fps;
4004 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
4006 vo_fps = mpctx->sh_video->fps;
4008 if(!mpctx->sh_video->fps && !force_fps){
4009 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"FPS not specified in the header or invalid, use the -fps option.\n");
4010 mpctx->opts.correct_pts = 1;
4016 if(!mpctx->sh_video && !mpctx->sh_audio){
4017 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL, "No stream found.\n");
4018 #ifdef CONFIG_DVBIN
4019 if(mpctx->stream->type == STREAMTYPE_DVB)
4021 int dir;
4022 int v = mpctx->last_dvb_step;
4023 if(v > 0)
4024 dir = DVB_CHANNEL_HIGHER;
4025 else
4026 dir = DVB_CHANNEL_LOWER;
4028 if(dvb_step_channel(mpctx->stream, dir)) {
4029 mpctx->stop_play = PT_NEXT_ENTRY;
4030 mpctx->dvbin_reopen = 1;
4033 #endif
4034 goto goto_next_file; // exit_player(_("Fatal error"));
4037 /* display clip info */
4038 demux_info_print(mpctx->demuxer);
4040 //================== Read SUBTITLES (DVD & TEXT) ==========================
4041 if(vo_spudec==NULL &&
4042 (mpctx->stream->type==STREAMTYPE_DVD || mpctx->stream->type == STREAMTYPE_DVDNAV)){
4043 init_vo_spudec(mpctx);
4046 // after reading video params we should load subtitles because
4047 // we know fps so now we can adjust subtitle time to ~6 seconds AST
4048 // check .sub
4049 current_module="read_subtitles_file";
4050 double sub_fps = mpctx->sh_video ? mpctx->sh_video->fps : 25;
4051 if(sub_name){
4052 for (i = 0; sub_name[i] != NULL; ++i)
4053 add_subtitles(mpctx, sub_name[i], sub_fps, 0);
4055 if(sub_auto) { // auto load sub file ...
4056 char *psub = get_path( "sub/" );
4057 char **tmp = sub_filenames((psub ? psub : ""), mpctx->filename);
4058 int i = 0;
4059 free(psub); // release the buffer created by get_path() above
4060 while (tmp[i]) {
4061 add_subtitles(mpctx, tmp[i], sub_fps, 1);
4062 free(tmp[i++]);
4064 free(tmp);
4066 if (mpctx->set_of_sub_size > 0)
4067 mpctx->sub_counts[SUB_SOURCE_SUBS] = mpctx->set_of_sub_size;
4069 if (select_subtitle(mpctx)) {
4070 if(subdata)
4071 switch (stream_dump_type) {
4072 case 3: list_sub_file(subdata); break;
4073 case 4: dump_mpsub(subdata, mpctx->sh_video->fps); break;
4074 case 6: dump_srt(subdata, mpctx->sh_video->fps); break;
4075 case 7: dump_microdvd(subdata, mpctx->sh_video->fps); break;
4076 case 8: dump_jacosub(subdata, mpctx->sh_video->fps); break;
4077 case 9: dump_sami(subdata, mpctx->sh_video->fps); break;
4081 print_file_properties(mpctx, mpctx->filename);
4083 if(!mpctx->sh_video) goto main; // audio-only
4085 if(!reinit_video_chain(mpctx)) {
4086 if(!mpctx->sh_video){
4087 if(!mpctx->sh_audio) goto goto_next_file;
4088 goto main; // exit_player(_("Fatal error"));
4092 if(mpctx->sh_video->output_flags & 0x08 && vo_spudec)
4093 spudec_set_hw_spu(vo_spudec,mpctx->video_out);
4095 #ifdef CONFIG_FREETYPE
4096 force_load_font = 1;
4097 #endif
4099 //================== MAIN: ==========================
4100 main:
4101 current_module="main";
4103 if (opts->playing_msg) {
4104 char* msg = property_expand_string(mpctx, opts->playing_msg);
4105 mp_msg(MSGT_CPLAYER,MSGL_INFO,"%s",msg);
4106 free(msg);
4110 // Disable the term OSD in verbose mode
4111 if (verbose)
4112 opts->term_osd = 0;
4115 int frame_time_remaining=0; // flag
4116 int blit_frame=0;
4118 // Make sure old OSD does not stay around,
4119 // e.g. with -fixed-vo and same-resolution files
4120 clear_osd_msgs();
4121 update_osd_msg(mpctx);
4123 //================ SETUP AUDIO ==========================
4125 if(mpctx->sh_audio){
4126 reinit_audio_chain(mpctx);
4127 if (mpctx->sh_audio && mpctx->sh_audio->codec)
4128 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_CODEC=%s\n", mpctx->sh_audio->codec->name);
4131 current_module="av_init";
4133 if(mpctx->sh_video){
4134 mpctx->sh_video->timer=0;
4135 if (! ignore_start)
4136 audio_delay += mpctx->sh_video->stream_delay;
4138 if(mpctx->sh_audio){
4139 if (start_volume >= 0)
4140 mixer_setvolume(&mpctx->mixer, start_volume, start_volume);
4141 if (! ignore_start)
4142 audio_delay -= mpctx->sh_audio->stream_delay;
4143 mpctx->delay=-audio_delay;
4146 if(!mpctx->sh_audio){
4147 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Audio: no sound\n");
4148 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused audio chunks.\n",mpctx->d_audio->packs);
4149 ds_free_packs(mpctx->d_audio); // free buffered chunks
4150 //mpctx->d_audio->id=-2; // do not read audio chunks
4151 //uninit_player(mpctx, INITIALIZED_AO); // close device
4153 if(!mpctx->sh_video){
4154 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Video: no video\n");
4155 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused video chunks.\n",mpctx->d_video->packs);
4156 ds_free_packs(mpctx->d_video);
4157 mpctx->d_video->id=-2;
4158 //if(!fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
4161 if (!mpctx->sh_video && !mpctx->sh_audio)
4162 goto goto_next_file;
4164 //if(demuxer->file_format!=DEMUXER_TYPE_AVI) pts_from_bps=0; // it must be 0 for mpeg/asf!
4165 if(force_fps && mpctx->sh_video){
4166 vo_fps = mpctx->sh_video->fps=force_fps;
4167 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
4168 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"FPS forced to be %5.3f (ftime: %5.3f).\n",mpctx->sh_video->fps,mpctx->sh_video->frametime);
4171 mp_input_set_section(mpctx->input, NULL);
4172 //TODO: add desired (stream-based) sections here
4173 if (mpctx->stream->type==STREAMTYPE_TV) mp_input_set_section(mpctx->input, "tv");
4174 if (mpctx->stream->type==STREAMTYPE_DVDNAV) mp_input_set_section(mpctx->input, "dvdnav");
4176 //==================== START PLAYING =======================
4178 if(opts->loop_times>1) opts->loop_times--; else
4179 if(opts->loop_times==1) opts->loop_times = -1;
4181 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Starting playback...\n");
4183 total_time_usage_start=GetTimer();
4184 audio_time_usage=0; video_time_usage=0; vout_time_usage=0;
4185 total_frame_cnt=0; drop_frame_cnt=0; // fix for multifile fps benchmark
4186 play_n_frames=play_n_frames_mf;
4188 if(play_n_frames==0){
4189 mpctx->stop_play=PT_NEXT_ENTRY; goto goto_next_file;
4192 // If there's a timeline force an absolute seek to initialize state
4193 if (seek_to_sec || mpctx->timeline) {
4194 seek(mpctx, seek_to_sec, SEEK_ABSOLUTE);
4195 end_at.pos += seek_to_sec;
4197 if (opts->chapterrange[0] > 0) {
4198 double pts;
4199 if (seek_chapter(mpctx, opts->chapterrange[0]-1, &pts, NULL) >= 0
4200 && pts > -1.0)
4201 seek(mpctx, pts, SEEK_ABSOLUTE);
4204 if (end_at.type == END_AT_SIZE) {
4205 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Option -endpos in MPlayer does not yet support size units.\n");
4206 end_at.type = END_AT_NONE;
4209 #ifdef CONFIG_DVDNAV
4210 mp_dvdnav_context_free(mpctx);
4211 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4212 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
4213 mp_dvdnav_cell_has_changed(mpctx->stream,1);
4215 #endif
4217 get_relative_time(mpctx); // reset current delta
4218 mpctx->time_frame = 0;
4219 mpctx->drop_message_shown = 0;
4220 mpctx->restart_playback = true;
4221 mpctx->total_avsync_change = 0;
4222 mpctx->last_chapter_seek = -1;
4223 // Make sure VO knows current pause state
4224 if (mpctx->sh_video)
4225 vo_control(mpctx->video_out, mpctx->paused ? VOCTRL_PAUSE : VOCTRL_RESUME,
4226 NULL);
4228 while(!mpctx->stop_play){
4229 float aq_sleep_time=0;
4231 if (opts->chapterrange[1] > 0) {
4232 int cur_chapter = get_current_chapter(mpctx);
4233 if(cur_chapter!=-1 && cur_chapter+1 > opts->chapterrange[1])
4234 goto goto_next_file;
4237 if(!mpctx->sh_audio && mpctx->d_audio->sh) {
4238 mpctx->sh_audio = mpctx->d_audio->sh;
4239 mpctx->sh_audio->ds = mpctx->d_audio;
4240 reinit_audio_chain(mpctx);
4243 /*========================== PLAY AUDIO ============================*/
4245 if (mpctx->sh_audio && !mpctx->paused
4246 && (!mpctx->restart_playback || !mpctx->sh_video))
4247 if (!fill_audio_out_buffers(mpctx))
4248 // at eof, all audio at least written to ao
4249 if (!mpctx->sh_video)
4250 mpctx->stop_play = AT_END_OF_FILE;
4253 if(!mpctx->sh_video) {
4254 // handle audio-only case:
4255 double a_pos=0;
4256 // sh_audio can be NULL due to video stream switching
4257 // TODO: handle this better
4258 if (mpctx->sh_audio)
4259 a_pos = playing_audio_pts(mpctx);
4261 print_status(mpctx, a_pos, false);
4263 if(end_at.type == END_AT_TIME && end_at.pos < a_pos)
4264 mpctx->stop_play = PT_NEXT_ENTRY;
4265 update_subtitles(mpctx, &mpctx->opts, NULL, a_pos, mpctx->video_offset,
4266 mpctx->d_sub, 0);
4267 update_osd_msg(mpctx);
4269 } else {
4271 /*========================== PLAY VIDEO ============================*/
4273 vo_pts=mpctx->sh_video->timer*90000.0;
4274 vo_fps=mpctx->sh_video->fps;
4276 blit_frame = mpctx->video_out->frame_loaded;
4277 if (!blit_frame) {
4278 double frame_time = update_video(mpctx);
4279 blit_frame = mpctx->video_out->frame_loaded;
4280 mp_dbg(MSGT_AVSYNC,MSGL_DBG2,"*** ftime=%5.3f ***\n",frame_time);
4281 if (mpctx->sh_video->vf_initialized < 0) {
4282 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL, "\nFATAL: Could not initialize video filters (-vf) or video output (-vo).\n");
4283 mpctx->stop_play = PT_NEXT_ENTRY;
4284 goto goto_next_file;
4286 if (blit_frame) {
4287 struct sh_video *sh_video = mpctx->sh_video;
4288 update_subtitles(mpctx, &mpctx->opts, sh_video, sh_video->pts,
4289 mpctx->video_offset, mpctx->d_sub, 0);
4290 update_teletext(sh_video, mpctx->demuxer, 0);
4291 update_osd_msg(mpctx);
4292 struct vf_instance *vf = mpctx->sh_video->vfilter;
4293 vf->control(vf, VFCTRL_DRAW_EOSD, NULL);
4294 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
4295 vo_osd_changed(0);
4297 if (frame_time < 0)
4298 mpctx->stop_play = AT_END_OF_FILE;
4299 else if (!mpctx->restart_playback) {
4300 mpctx->time_frame += frame_time / opts->playback_speed;
4301 adjust_sync(mpctx, frame_time);
4304 if (mpctx->timeline) {
4305 struct timeline_part *next = mpctx->timeline + mpctx->timeline_part + 1;
4306 if (mpctx->sh_video->pts >= next->start
4307 || mpctx->stop_play == AT_END_OF_FILE
4308 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts) {
4309 seek(mpctx, next->start, SEEK_ABSOLUTE);
4310 continue;
4314 // ==========================================================================
4316 // current_module="draw_osd";
4317 // if(vo_config_count) mpctx->video_out->draw_osd();
4319 current_module="vo_check_events";
4320 vo_check_events(mpctx->video_out);
4322 #ifdef CONFIG_X11
4323 if (stop_xscreensaver) {
4324 current_module = "stop_xscreensaver";
4325 xscreensaver_heartbeat(mpctx->x11_state);
4327 #endif
4328 if (heartbeat_cmd) {
4329 static unsigned last_heartbeat;
4330 unsigned now = GetTimerMS();
4331 if (now - last_heartbeat > 30000) {
4332 last_heartbeat = now;
4333 system(heartbeat_cmd);
4337 frame_time_remaining = sleep_until_update(mpctx, &mpctx->time_frame, &aq_sleep_time);
4339 //====================== FLIP PAGE (VIDEO BLT): =========================
4341 current_module="flip_page";
4342 if (!frame_time_remaining && blit_frame) {
4343 unsigned int t2=GetTimer();
4344 unsigned int pts_us = mpctx->last_time + mpctx->time_frame * 1e6;
4345 int duration = -1;
4346 double pts2 = mpctx->video_out->next_pts2;
4347 if (pts2 != MP_NOPTS_VALUE && opts->correct_pts
4348 && !mpctx->restart_playback) {
4349 // expected A/V sync correction is ignored
4350 double diff = (pts2 - mpctx->sh_video->pts);
4351 diff /= opts->playback_speed;
4352 if (mpctx->time_frame < 0)
4353 diff += mpctx->time_frame;
4354 if (diff < 0)
4355 diff = 0;
4356 if (diff > 10)
4357 diff = 10;
4358 duration = diff * 1e6;
4360 vo_flip_page(mpctx->video_out, pts_us|1, duration);
4362 mpctx->last_vo_flip_duration = (GetTimer() - t2) * 0.000001;
4363 vout_time_usage += mpctx->last_vo_flip_duration;
4364 if (mpctx->video_out->driver->flip_page_timed) {
4365 // No need to adjust sync based on flip speed
4366 mpctx->last_vo_flip_duration = 0;
4367 // For print_status - VO call finishing early is OK for sync
4368 mpctx->time_frame -= get_relative_time(mpctx);
4370 if (mpctx->restart_playback) {
4371 mpctx->syncing_audio = true;
4372 if (mpctx->sh_audio && !mpctx->paused)
4373 fill_audio_out_buffers(mpctx);
4374 mpctx->restart_playback = false;
4375 mpctx->time_frame = 0;
4376 get_relative_time(mpctx);
4378 print_status(mpctx, MP_NOPTS_VALUE, true);
4380 else
4381 print_status(mpctx, MP_NOPTS_VALUE, false);
4383 //============================ Auto QUALITY ============================
4385 /*Output quality adjustments:*/
4386 if (opts->auto_quality > 0) {
4387 current_module="autoq";
4388 // float total=0.000001f * (GetTimer()-aq_total_time);
4389 // if (output_quality < opts->auto_quality && aq_sleep_time > 0.05f * total)
4390 if (output_quality < opts->auto_quality && aq_sleep_time > 0)
4391 ++output_quality;
4392 else
4393 // if(output_quality>0 && aq_sleep_time<-0.05f*total)
4394 if(output_quality>1 && aq_sleep_time<0)
4395 --output_quality;
4396 else
4397 if(output_quality>0 && aq_sleep_time<-0.050f) // 50ms
4398 output_quality=0;
4399 // printf("total: %8.6f sleep: %8.6f q: %d\n",(0.000001f*aq_total_time),aq_sleep_time,output_quality);
4400 set_video_quality(mpctx->sh_video,output_quality);
4403 if (!frame_time_remaining && blit_frame) {
4404 if (play_n_frames >= 0) {
4405 --play_n_frames;
4406 if (play_n_frames <= 0)
4407 mpctx->stop_play = PT_NEXT_ENTRY;
4409 if (mpctx->step_frames > 0) {
4410 mpctx->step_frames--;
4411 if (mpctx->step_frames == 0)
4412 pause_player(mpctx);
4417 // FIXME: add size based support for -endpos
4418 if (end_at.type == END_AT_TIME &&
4419 !frame_time_remaining && end_at.pos <= mpctx->sh_video->pts)
4420 mpctx->stop_play = PT_NEXT_ENTRY;
4422 } // end if(mpctx->sh_video)
4424 #ifdef CONFIG_DVDNAV
4425 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4426 nav_highlight_t hl;
4427 mp_dvdnav_get_highlight (mpctx->stream, &hl);
4428 if (!vo_spudec || !spudec_apply_palette_crop(vo_spudec, hl.palette, hl.sx, hl.sy, hl.ex, hl.ey)) {
4429 osd_set_nav_box (hl.sx, hl.sy, hl.ex, hl.ey);
4430 vo_osd_changed (OSDTYPE_DVDNAV);
4431 } else {
4432 osd_set_nav_box(0, 0, 0, 0);
4433 vo_osd_changed(OSDTYPE_DVDNAV);
4434 vo_osd_changed(OSDTYPE_SPU);
4437 if (mp_dvdnav_stream_has_changed(mpctx->stream)) {
4438 double ar = -1.0;
4439 if (mpctx->sh_video &&
4440 stream_control (mpctx->demuxer->stream,
4441 STREAM_CTRL_GET_ASPECT_RATIO, &ar)
4442 != STREAM_UNSUPPORTED)
4443 mpctx->sh_video->stream_aspect = ar;
4446 #endif
4448 //================= Keyboard events, SEEKing ====================
4450 current_module="key_events";
4453 while (1) {
4454 mp_cmd_t* cmd;
4455 while ((cmd = mp_input_get_cmd(mpctx->input, 0, 0)) != NULL) {
4456 run_command(mpctx, cmd);
4457 mp_cmd_free(cmd);
4458 if (mpctx->stop_play)
4459 break;
4460 if (mpctx->rel_seek_secs || mpctx->abs_seek_pos) {
4461 cmd = mp_input_get_cmd(mpctx->input, 0, 1);
4462 /* Allow seek commands to be combined, but execute the real seek
4463 * before processing other commands */
4464 if (!cmd || cmd->id != MP_CMD_SEEK)
4465 break;
4468 if (!mpctx->paused || mpctx->stop_play || mpctx->rel_seek_secs
4469 || mpctx->abs_seek_pos)
4470 break;
4471 if (mpctx->sh_video) {
4472 update_osd_msg(mpctx);
4473 int hack = vo_osd_changed(0);
4474 vo_osd_changed(hack);
4475 if (hack) {
4476 if (redraw_osd(mpctx->sh_video, mpctx->osd) < 0) {
4477 add_step_frame(mpctx);
4478 break;
4480 else
4481 vo_osd_changed(0);
4484 pause_loop(mpctx);
4488 // handle -sstep
4489 if (step_sec > 0 && !mpctx->paused) {
4490 mpctx->osd_function=OSD_FFW;
4491 mpctx->rel_seek_secs+=step_sec;
4494 edl_update(mpctx);
4496 /* Looping. */
4497 if(mpctx->stop_play==AT_END_OF_FILE && opts->loop_times>=0) {
4498 mp_msg(MSGT_CPLAYER,MSGL_V,"loop_times = %d\n", opts->loop_times);
4500 if(opts->loop_times>1) opts->loop_times--; else
4501 if(opts->loop_times==1) opts->loop_times=-1;
4502 play_n_frames=play_n_frames_mf;
4503 mpctx->stop_play=0;
4504 mpctx->abs_seek_pos=SEEK_ABSOLUTE; mpctx->rel_seek_secs=seek_to_sec;
4507 if(mpctx->rel_seek_secs || mpctx->abs_seek_pos){
4508 seek(mpctx, mpctx->rel_seek_secs, mpctx->abs_seek_pos);
4510 mpctx->rel_seek_secs=0;
4511 mpctx->abs_seek_pos=0;
4514 } // while(!mpctx->stop_play)
4516 mp_msg(MSGT_GLOBAL,MSGL_V,"EOF code: %d \n",mpctx->stop_play);
4518 #ifdef CONFIG_DVBIN
4519 if(mpctx->dvbin_reopen)
4521 mpctx->stop_play = 0;
4522 uninit_player(mpctx, INITIALIZED_ALL-(INITIALIZED_STREAM|INITIALIZED_GETCH2|(opts->fixed_vo?INITIALIZED_VO:0)));
4523 cache_uninit(mpctx->stream);
4524 mpctx->dvbin_reopen = 0;
4525 goto goto_enable_cache;
4527 #endif
4530 goto_next_file: // don't jump here after ao/vo/getch initialization!
4532 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\n");
4534 if (opts->benchmark) {
4535 double tot=video_time_usage+vout_time_usage+audio_time_usage;
4536 double total_time_usage;
4537 total_time_usage_start=GetTimer()-total_time_usage_start;
4538 total_time_usage = (float)total_time_usage_start*0.000001;
4539 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\nBENCHMARKs: VC:%8.3fs VO:%8.3fs A:%8.3fs Sys:%8.3fs = %8.3fs\n",
4540 video_time_usage,vout_time_usage,audio_time_usage,
4541 total_time_usage-tot,total_time_usage);
4542 if(total_time_usage>0.0)
4543 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARK%%: VC:%8.4f%% VO:%8.4f%% A:%8.4f%% Sys:%8.4f%% = %8.4f%%\n",
4544 100.0*video_time_usage/total_time_usage,
4545 100.0*vout_time_usage/total_time_usage,
4546 100.0*audio_time_usage/total_time_usage,
4547 100.0*(total_time_usage-tot)/total_time_usage,
4548 100.0);
4549 if(total_frame_cnt && frame_dropping)
4550 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARKn: disp: %d (%3.2f fps) drop: %d (%d%%) total: %d (%3.2f fps)\n",
4551 total_frame_cnt-drop_frame_cnt,
4552 (total_time_usage>0.5)?((total_frame_cnt-drop_frame_cnt)/total_time_usage):0,
4553 drop_frame_cnt,
4554 100*drop_frame_cnt/total_frame_cnt,
4555 total_frame_cnt,
4556 (total_time_usage>0.5)?(total_frame_cnt/total_time_usage):0);
4559 // time to uninit all, except global stuff:
4560 int uninitialize_parts = INITIALIZED_ALL;
4561 if (opts->fixed_vo)
4562 uninitialize_parts -= INITIALIZED_VO;
4563 if (opts->gapless_audio && mpctx->stop_play == AT_END_OF_FILE)
4564 uninitialize_parts -= INITIALIZED_AO;
4565 uninit_player(mpctx, uninitialize_parts);
4567 if(mpctx->set_of_sub_size > 0) {
4568 current_module="sub_free";
4569 for(i = 0; i < mpctx->set_of_sub_size; ++i) {
4570 sub_free(mpctx->set_of_subtitles[i]);
4571 #ifdef CONFIG_ASS
4572 if(mpctx->set_of_ass_tracks[i])
4573 ass_free_track( mpctx->set_of_ass_tracks[i] );
4574 #endif
4576 mpctx->set_of_sub_size = 0;
4578 vo_sub_last = vo_sub=NULL;
4579 subdata=NULL;
4580 #ifdef CONFIG_ASS
4581 ass_track = NULL;
4582 if(ass_library)
4583 ass_clear_fonts(ass_library);
4584 #endif
4586 if (!mpctx->stop_play) // In case some goto jumped here...
4587 mpctx->stop_play = PT_NEXT_ENTRY;
4589 int playtree_direction = 1;
4591 if(mpctx->stop_play == PT_NEXT_ENTRY || mpctx->stop_play == PT_PREV_ENTRY) {
4592 if(play_tree_iter_step(mpctx->playtree_iter,mpctx->play_tree_step,0) != PLAY_TREE_ITER_ENTRY) {
4593 play_tree_iter_free(mpctx->playtree_iter);
4594 mpctx->playtree_iter = NULL;
4596 mpctx->play_tree_step = 1;
4597 } else if(mpctx->stop_play == PT_UP_NEXT || mpctx->stop_play == PT_UP_PREV) {
4598 int direction = mpctx->stop_play == PT_UP_NEXT ? 1 : -1;
4599 if(mpctx->playtree_iter) {
4600 if(play_tree_iter_up_step(mpctx->playtree_iter,direction,0) != PLAY_TREE_ITER_ENTRY) {
4601 play_tree_iter_free(mpctx->playtree_iter);
4602 mpctx->playtree_iter = NULL;
4605 } else if (mpctx->stop_play == PT_STOP) {
4606 play_tree_iter_free(mpctx->playtree_iter);
4607 mpctx->playtree_iter = NULL;
4608 } else { // NEXT PREV SRC
4609 playtree_direction = mpctx->stop_play == PT_PREV_SRC ? -1 : 1;
4612 while(mpctx->playtree_iter != NULL) {
4613 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, playtree_direction);
4614 if(mpctx->filename == NULL) {
4615 if(play_tree_iter_step(mpctx->playtree_iter, playtree_direction, 0) != PLAY_TREE_ITER_ENTRY) {
4616 play_tree_iter_free(mpctx->playtree_iter);
4617 mpctx->playtree_iter = NULL;
4619 } else
4620 break;
4623 if (mpctx->playtree_iter != NULL || opts->player_idle_mode) {
4624 if(!mpctx->playtree_iter) mpctx->filename = NULL;
4625 mpctx->stop_play = 0;
4626 goto play_next_file;
4630 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4632 return 1;
4634 #endif /* DISABLE_MAIN */