configure: only set NEED_GLOB on Windows
[mplayer.git] / mplayer.c
blob44b6789603a9bf9891f5bb46482be832b441a170
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>
26 #include <assert.h>
28 #include "config.h"
29 #include "talloc.h"
31 #if defined(__MINGW32__) || defined(__CYGWIN__)
32 #define _UWIN 1 /*disable Non-underscored versions of non-ANSI functions as otherwise int eof would conflict with eof()*/
33 #include <windows.h>
34 #endif
35 #include <string.h>
36 #include <unistd.h>
38 // #include <sys/mman.h>
39 #include <sys/types.h>
40 #ifndef __MINGW32__
41 #include <sys/ioctl.h>
42 #include <sys/wait.h>
43 #else
44 #define SIGHUP 1 /* hangup */
45 #define SIGQUIT 3 /* quit */
46 #define SIGKILL 9 /* kill (cannot be caught or ignored) */
47 #define SIGBUS 10 /* bus error */
48 #define SIGPIPE 13 /* broken pipe */
49 #endif
51 #include <sys/time.h>
52 #include <sys/stat.h>
54 #include <signal.h>
55 #include <time.h>
56 #include <fcntl.h>
57 #include <limits.h>
59 #include <errno.h>
61 #include "mp_msg.h"
62 #include "av_log.h"
65 #include "m_option.h"
66 #include "m_config.h"
67 #include "mplayer.h"
68 #include "access_mpcontext.h"
69 #include "m_property.h"
71 #include "libavutil/avstring.h"
73 #include "sub/subreader.h"
74 #include "sub/find_subfiles.h"
75 #include "sub/dec_sub.h"
77 #include "mp_osd.h"
78 #include "libvo/video_out.h"
80 #include "sub/font_load.h"
81 #include "sub/sub.h"
82 #include "ffmpeg_files/intreadwrite.h"
83 #include "sub/av_sub.h"
84 #include "libmpcodecs/dec_teletext.h"
85 #include "cpudetect.h"
86 #include "version.h"
88 #ifdef CONFIG_X11
89 #include "libvo/x11_common.h"
90 #endif
92 #include "libao2/audio_out.h"
94 #include "codec-cfg.h"
96 #include "edl.h"
98 #include "sub/spudec.h"
99 #include "sub/vobsub.h"
101 #include "osdep/getch2.h"
102 #include "osdep/timer.h"
104 #include "input/input.h"
106 int slave_mode=0;
107 int enable_mouse_movements=0;
108 float start_volume = -1;
110 #include "osdep/priority.h"
112 char *heartbeat_cmd;
114 #ifdef HAVE_RTC
115 #ifdef __linux__
116 #include <linux/rtc.h>
117 #else
118 #include <rtc.h>
119 #define RTC_IRQP_SET RTCIO_IRQP_SET
120 #define RTC_PIE_ON RTCIO_PIE_ON
121 #endif /* __linux__ */
122 #endif /* HAVE_RTC */
124 #include "stream/tv.h"
125 #include "stream/stream_radio.h"
126 #ifdef CONFIG_DVBIN
127 #include "stream/dvbin.h"
128 #endif
129 #include "stream/cache2.h"
131 //**************************************************************************//
132 // Playtree
133 //**************************************************************************//
134 #include "playtree.h"
135 #include "playtreeparser.h"
137 //**************************************************************************//
138 // Config
139 //**************************************************************************//
140 #include "parser-cfg.h"
141 #include "parser-mpcmd.h"
143 //**************************************************************************//
144 // Config file
145 //**************************************************************************//
147 static int cfg_inc_verbose(m_option_t *conf){ ++verbose; return 0;}
149 #include "path.h"
151 //**************************************************************************//
152 //**************************************************************************//
153 // Input media streaming & demultiplexer:
154 //**************************************************************************//
156 static int max_framesize=0;
158 #include "stream/stream.h"
159 #include "libmpdemux/demuxer.h"
160 #include "libmpdemux/stheader.h"
162 #ifdef CONFIG_DVDREAD
163 #include "stream/stream_dvd.h"
164 #endif
165 #include "stream/stream_dvdnav.h"
167 #include "libmpcodecs/dec_audio.h"
168 #include "libmpcodecs/dec_video.h"
169 #include "libmpcodecs/mp_image.h"
170 #include "libmpcodecs/vf.h"
171 #include "libmpcodecs/vd.h"
173 #include "mixer.h"
175 #include "mp_core.h"
176 #include "options.h"
177 #include "defaultopts.h"
179 static const char help_text[]=_(
180 "Usage: mplayer [options] [url|path/]filename\n"
181 "\n"
182 "Basic options: (complete list in the man page)\n"
183 " -vo <drv> select video output driver ('-vo help' for a list)\n"
184 " -ao <drv> select audio output driver ('-ao help' for a list)\n"
185 #ifdef CONFIG_VCD
186 " vcd://<trackno> play (S)VCD (Super Video CD) track (raw device, no mount)\n"
187 #endif
188 #ifdef CONFIG_DVDREAD
189 " dvd://<titleno> play DVD title from device instead of plain file\n"
190 #endif
191 " -alang/-slang select DVD audio/subtitle language (by 2-char country code)\n"
192 " -ss <position> seek to given (seconds or hh:mm:ss) position\n"
193 " -nosound do not play sound\n"
194 " -fs fullscreen playback (or -vm, -zoom, details in the man page)\n"
195 " -x <x> -y <y> set display resolution (for use with -vm or -zoom)\n"
196 " -sub <file> specify subtitle file to use (also see -subfps, -subdelay)\n"
197 " -playlist <file> specify playlist file\n"
198 " -vid x -aid y select video (x) and audio (y) stream to play\n"
199 " -fps x -srate y change video (x fps) and audio (y Hz) rate\n"
200 " -pp <quality> enable postprocessing filter (details in the man page)\n"
201 " -framedrop enable frame dropping (for slow machines)\n"
202 "\n"
203 "Basic keys: (complete list in the man page, also check input.conf)\n"
204 " <- or -> seek backward/forward 10 seconds\n"
205 " down or up seek backward/forward 1 minute\n"
206 " pgdown or pgup seek backward/forward 10 minutes\n"
207 " < or > step backward/forward in playlist\n"
208 " p or SPACE pause movie (press any key to continue)\n"
209 " q or ESC stop playing and quit program\n"
210 " + or - adjust audio delay by +/- 0.1 second\n"
211 " o cycle OSD mode: none / seekbar / seekbar + timer\n"
212 " * or / increase or decrease PCM volume\n"
213 " x or z adjust subtitle delay by +/- 0.1 second\n"
214 " r or t adjust subtitle position up/down, also see -vf expand\n"
215 " double click toggle fullscreen\n"
216 " right click pause (press again to continue)\n"
217 "\n"
218 " * * * SEE THE MAN PAGE FOR DETAILS, FURTHER (ADVANCED) OPTIONS AND KEYS * * *\n"
219 "\n");
222 #define Exit_SIGILL_RTCpuSel _(\
223 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
224 " It may be a bug in our new runtime CPU-detection code...\n"\
225 " Please read DOCS/HTML/en/bugreports.html.\n")
227 #define Exit_SIGILL _(\
228 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
229 " It usually happens when you run it on a CPU different than the one it was\n"\
230 " compiled/optimized for.\n"\
231 " Verify this!\n")
233 #define Exit_SIGSEGV_SIGFPE _(\
234 "- MPlayer crashed by bad usage of CPU/FPU/RAM.\n"\
235 " Recompile MPlayer with --enable-debug and make a 'gdb' backtrace and\n"\
236 " disassembly. Details in DOCS/HTML/en/bugreports_what.html#bugreports_crash.\n")
238 #define Exit_SIGCRASH _(\
239 "- MPlayer crashed. This shouldn't happen.\n"\
240 " It can be a bug in the MPlayer code _or_ in your drivers _or_ in your\n"\
241 " gcc version. If you think it's MPlayer's fault, please read\n"\
242 " DOCS/HTML/en/bugreports.html and follow the instructions there. We can't and\n"\
243 " won't help unless you provide this information when reporting a possible bug.\n")
245 #define SystemTooSlow _("\n\n"\
246 " ************************************************\n"\
247 " **** Your system is too SLOW to play this! ****\n"\
248 " ************************************************\n\n"\
249 "Possible reasons, problems, workarounds:\n"\
250 "- Most common: broken/buggy _audio_ driver\n"\
251 " - Try -ao sdl or use the OSS emulation of ALSA.\n"\
252 " - Experiment with different values for -autosync, 30 is a good start.\n"\
253 "- Slow video output\n"\
254 " - Try a different -vo driver (-vo help for a list) or try -framedrop!\n"\
255 "- Slow CPU\n"\
256 " - Don't try to play a big DVD/DivX on a slow CPU! Try some of the lavdopts,\n"\
257 " e.g. -vfm ffmpeg -lavdopts lowres=1:fast:skiploopfilter=all.\n"\
258 "- Broken file\n"\
259 " - Try various combinations of -nobps -ni -forceidx -mc 0.\n"\
260 "- Slow media (NFS/SMB mounts, DVD, VCD etc)\n"\
261 " - Try -cache 8192.\n"\
262 "- Are you using -cache to play a non-interleaved AVI file?\n"\
263 " - Try -nocache.\n"\
264 "Read DOCS/HTML/en/video.html for tuning/speedup tips.\n"\
265 "If none of this helps you, read DOCS/HTML/en/bugreports.html.\n\n")
268 //**************************************************************************//
269 //**************************************************************************//
271 #include "mp_fifo.h"
273 // benchmark:
274 double video_time_usage=0;
275 double vout_time_usage=0;
276 static double audio_time_usage=0;
277 static int total_time_usage_start=0;
278 static int total_frame_cnt=0;
279 static int drop_frame_cnt=0; // total number of dropped frames
281 // options:
282 static int output_quality=0;
284 // seek:
285 static double seek_to_sec;
286 static off_t seek_to_byte=0;
287 static off_t step_sec=0;
289 static m_time_size_t end_at = { .type = END_AT_NONE, .pos = 0 };
291 // codecs:
292 char **audio_codec_list=NULL; // override audio codec
293 char **video_codec_list=NULL; // override video codec
294 char **audio_fm_list=NULL; // override audio codec family
295 char **video_fm_list=NULL; // override video codec family
297 // this dvdsub_id was selected via slang
298 // use this to allow dvdnav to follow -slang across stream resets,
299 // in particular the subtitle ID for a language changes
300 int dvdsub_lang_id;
301 int vobsub_id=-1;
302 static char* spudec_ifo=NULL;
303 int forced_subs_only=0;
304 int file_filter=1;
306 // cache2:
307 int stream_cache_size=-1;
309 // dump:
310 int stream_dump_type=0;
312 // A-V sync:
313 static float default_max_pts_correction=-1;//0.01f;
314 float audio_delay=0;
315 static int ignore_start=0;
317 double force_fps=0;
318 static int force_srate=0;
319 int frame_dropping=0; // option 0=no drop 1= drop vo 2= drop decode
320 static int play_n_frames=-1;
321 static int play_n_frames_mf=-1;
323 // sub:
324 char *font_name=NULL;
325 char *sub_font_name=NULL;
326 extern int font_fontconfig;
327 float font_factor=0.75;
328 float sub_delay=0;
329 float sub_fps=0;
330 int subcc_enabled=0;
331 int suboverlap_enabled = 1;
333 #include "sub/ass_mp.h"
335 char* current_module=NULL; // for debugging
338 // ---
340 #ifdef CONFIG_MENU
341 #include "m_struct.h"
342 #include "libmenu/menu.h"
343 static const vf_info_t* const libmenu_vfs[] = {
344 &vf_info_menu,
345 NULL
347 static vf_instance_t* vf_menu = NULL;
348 int use_menu = 0;
349 static char* menu_cfg = NULL;
350 static char* menu_root = "main";
351 #endif
354 edl_record_ptr edl_records = NULL; ///< EDL entries memory area
355 edl_record_ptr next_edl_record = NULL; ///< only for traversing edl_records
356 FILE* edl_fd = NULL; ///< fd to write to when in -edlout mode.
357 int use_filedir_conf;
358 int use_filename_title;
360 #include "mpcommon.h"
361 #include "command.h"
363 #include "metadata.h"
365 void *mpctx_get_video_out(MPContext *mpctx)
367 return mpctx->video_out;
370 void *mpctx_get_demuxer(MPContext *mpctx)
372 return mpctx->demuxer;
375 void *mpctx_get_playtree_iter(MPContext *mpctx)
377 return mpctx->playtree_iter;
380 void *mpctx_get_mixer(MPContext *mpctx)
382 return &mpctx->mixer;
385 int mpctx_get_global_sub_size(MPContext *mpctx)
387 return mpctx->global_sub_size;
390 int mpctx_get_osd_function(MPContext *mpctx)
392 return mpctx->osd_function;
395 static float get_relative_time(struct MPContext *mpctx)
397 unsigned int new_time = GetTimer();
398 unsigned int delta = new_time - mpctx->last_time;
399 mpctx->last_time = new_time;
400 return delta * 0.000001;
403 static int is_valid_metadata_type(struct MPContext *mpctx, metadata_t type) {
404 switch (type)
406 /* check for valid video stream */
407 case META_VIDEO_CODEC:
408 case META_VIDEO_BITRATE:
409 case META_VIDEO_RESOLUTION:
411 if (!mpctx->sh_video)
412 return 0;
413 break;
416 /* check for valid audio stream */
417 case META_AUDIO_CODEC:
418 case META_AUDIO_BITRATE:
419 case META_AUDIO_SAMPLES:
421 if (!mpctx->sh_audio)
422 return 0;
423 break;
426 /* check for valid demuxer */
427 case META_INFO_TITLE:
428 case META_INFO_ARTIST:
429 case META_INFO_ALBUM:
430 case META_INFO_YEAR:
431 case META_INFO_COMMENT:
432 case META_INFO_TRACK:
433 case META_INFO_GENRE:
435 if (!mpctx->demuxer)
436 return 0;
437 break;
440 default:
441 break;
444 return 1;
447 static char *get_demuxer_info(struct MPContext *mpctx, char *tag) {
448 char **info = mpctx->demuxer->info;
449 int n;
451 if (!info || !tag)
452 return talloc_strdup(NULL, "");
454 for (n = 0; info[2*n] != NULL ; n++)
455 if (!strcasecmp (info[2*n], tag))
456 break;
458 return talloc_strdup(NULL, info[2*n+1] ? info[2*n+1] : "");
461 char *get_metadata(struct MPContext *mpctx, metadata_t type)
463 sh_audio_t * const sh_audio = mpctx->sh_audio;
464 sh_video_t * const sh_video = mpctx->sh_video;
466 if (!is_valid_metadata_type(mpctx, type))
467 return NULL;
469 switch (type) {
470 case META_NAME:
471 return talloc_strdup(NULL, mp_basename(mpctx->filename));
472 case META_VIDEO_CODEC:
473 if (sh_video->format == 0x10000001)
474 return talloc_strdup(NULL, "mpeg1");
475 else if (sh_video->format == 0x10000002)
476 return talloc_strdup(NULL, "mpeg2");
477 else if (sh_video->format == 0x10000004)
478 return talloc_strdup(NULL, "mpeg4");
479 else if (sh_video->format == 0x10000005)
480 return talloc_strdup(NULL, "h264");
481 else if (sh_video->format >= 0x20202020)
482 return talloc_asprintf(NULL, "%.4s", (char *) &sh_video->format);
483 else
484 return talloc_asprintf(NULL, "0x%08X", sh_video->format);
485 case META_VIDEO_BITRATE:
486 return talloc_asprintf(NULL, "%d kbps",
487 (int) (sh_video->i_bps * 8 / 1024));
488 case META_VIDEO_RESOLUTION:
489 return talloc_asprintf(NULL, "%d x %d", sh_video->disp_w,
490 sh_video->disp_h);
491 case META_AUDIO_CODEC:
492 if (sh_audio->codec && sh_audio->codec->name)
493 return talloc_strdup(NULL, sh_audio->codec->name);
494 return talloc_strdup(NULL, "");
495 case META_AUDIO_BITRATE:
496 return talloc_asprintf(NULL, "%d kbps",
497 (int) (sh_audio->i_bps * 8/1000));
498 case META_AUDIO_SAMPLES:
499 return talloc_asprintf(NULL, "%d Hz, %d ch.", sh_audio->samplerate,
500 sh_audio->channels);
502 /* check for valid demuxer */
503 case META_INFO_TITLE:
504 return get_demuxer_info(mpctx, "Title");
506 case META_INFO_ARTIST:
507 return get_demuxer_info(mpctx, "Artist");
509 case META_INFO_ALBUM:
510 return get_demuxer_info(mpctx, "Album");
512 case META_INFO_YEAR:
513 return get_demuxer_info(mpctx, "Year");
515 case META_INFO_COMMENT:
516 return get_demuxer_info(mpctx, "Comment");
518 case META_INFO_TRACK:
519 return get_demuxer_info(mpctx, "Track");
521 case META_INFO_GENRE:
522 return get_demuxer_info(mpctx, "Genre");
524 default:
525 break;
528 return talloc_strdup(NULL, "");
531 static void print_file_properties(struct MPContext *mpctx, const char *filename)
533 double start_pts = MP_NOPTS_VALUE;
534 double video_start_pts = MP_NOPTS_VALUE;
535 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_FILENAME=%s\n",
536 filename_recode(filename));
537 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_DEMUXER=%s\n", mpctx->demuxer->desc->name);
538 if (mpctx->sh_video) {
539 /* Assume FOURCC if all bytes >= 0x20 (' ') */
540 if (mpctx->sh_video->format >= 0x20202020)
541 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=%.4s\n", (char *)&mpctx->sh_video->format);
542 else
543 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=0x%08X\n", mpctx->sh_video->format);
544 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_BITRATE=%d\n", mpctx->sh_video->i_bps*8);
545 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_WIDTH=%d\n", mpctx->sh_video->disp_w);
546 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_HEIGHT=%d\n", mpctx->sh_video->disp_h);
547 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FPS=%5.3f\n", mpctx->sh_video->fps);
548 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_ASPECT=%1.4f\n", mpctx->sh_video->aspect);
549 video_start_pts = ds_get_next_pts(mpctx->d_video);
551 if (mpctx->sh_audio) {
552 /* Assume FOURCC if all bytes >= 0x20 (' ') */
553 if (mpctx->sh_audio->format >= 0x20202020)
554 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_FORMAT=%.4s\n", (char *)&mpctx->sh_audio->format);
555 else
556 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_FORMAT=%d\n", mpctx->sh_audio->format);
557 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_BITRATE=%d\n", mpctx->sh_audio->i_bps*8);
558 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_RATE=%d\n", mpctx->sh_audio->samplerate);
559 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_NCH=%d\n", mpctx->sh_audio->channels);
560 start_pts = ds_get_next_pts(mpctx->d_audio);
562 if (video_start_pts != MP_NOPTS_VALUE) {
563 if (start_pts == MP_NOPTS_VALUE || !mpctx->sh_audio ||
564 (mpctx->sh_video && video_start_pts < start_pts))
565 start_pts = video_start_pts;
567 if (start_pts != MP_NOPTS_VALUE)
568 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_START_TIME=%.2f\n", start_pts);
569 else
570 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_START_TIME=unknown\n");
571 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_LENGTH=%.2f\n", get_time_length(mpctx));
572 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_SEEKABLE=%d\n",
573 mpctx->stream->seek && (!mpctx->demuxer || mpctx->demuxer->seekable));
574 if (mpctx->demuxer) {
575 if (mpctx->demuxer->num_chapters == 0)
576 stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_NUM_CHAPTERS, &mpctx->demuxer->num_chapters);
577 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_CHAPTERS=%d\n", mpctx->demuxer->num_chapters);
581 /// step size of mixer changes
582 int volstep = 3;
584 #ifdef CONFIG_DVDNAV
585 static void mp_dvdnav_context_free(MPContext *ctx){
586 if (ctx->nav_smpi) free_mp_image(ctx->nav_smpi);
587 ctx->nav_smpi = NULL;
588 free(ctx->nav_buffer);
589 ctx->nav_buffer = NULL;
590 ctx->nav_start = NULL;
591 ctx->nav_in_size = 0;
593 #endif
595 static void uninit_subs(struct demuxer *demuxer)
597 for (int i = 0; i < MAX_S_STREAMS; i++) {
598 struct sh_sub *sh = demuxer->s_streams[i];
599 if (sh && sh->initialized)
600 sub_uninit(sh);
604 void uninit_player(struct MPContext *mpctx, unsigned int mask){
605 mask &= mpctx->initialized_flags;
607 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n*** uninit(0x%X)\n",mask);
609 if(mask&INITIALIZED_ACODEC){
610 mpctx->initialized_flags&=~INITIALIZED_ACODEC;
611 current_module="uninit_acodec";
612 if(mpctx->sh_audio) uninit_audio(mpctx->sh_audio);
613 mpctx->sh_audio=NULL;
614 mpctx->mixer.afilter = NULL;
617 if (mask & INITIALIZED_SUB) {
618 mpctx->initialized_flags &= ~INITIALIZED_SUB;
619 if (mpctx->d_sub->sh)
620 sub_switchoff(mpctx->d_sub->sh, mpctx->osd);
623 if(mask&INITIALIZED_VCODEC){
624 mpctx->initialized_flags&=~INITIALIZED_VCODEC;
625 current_module="uninit_vcodec";
626 if(mpctx->sh_video) uninit_video(mpctx->sh_video);
627 mpctx->sh_video=NULL;
628 #ifdef CONFIG_MENU
629 vf_menu=NULL;
630 #endif
633 if(mask&INITIALIZED_DEMUXER){
634 mpctx->initialized_flags&=~INITIALIZED_DEMUXER;
635 current_module="free_demuxer";
636 if (mpctx->num_sources) {
637 mpctx->demuxer = mpctx->sources[0].demuxer;
638 for (int i = 1; i < mpctx->num_sources; i++) {
639 uninit_subs(mpctx->sources[i].demuxer);
640 free_stream(mpctx->sources[i].stream);
641 free_demuxer(mpctx->sources[i].demuxer);
644 talloc_free(mpctx->sources);
645 mpctx->sources = NULL;
646 mpctx->num_sources = 0;
647 talloc_free(mpctx->timeline);
648 mpctx->timeline = NULL;
649 mpctx->num_timeline_parts = 0;
650 talloc_free(mpctx->chapters);
651 mpctx->chapters = NULL;
652 mpctx->num_chapters = 0;
653 mpctx->video_offset = 0;
654 if(mpctx->demuxer){
655 mpctx->stream=mpctx->demuxer->stream;
656 uninit_subs(mpctx->demuxer);
657 free_demuxer(mpctx->demuxer);
659 mpctx->demuxer=NULL;
662 // kill the cache process:
663 if(mask&INITIALIZED_STREAM){
664 mpctx->initialized_flags&=~INITIALIZED_STREAM;
665 current_module="uninit_stream";
666 if(mpctx->stream) free_stream(mpctx->stream);
667 mpctx->stream=NULL;
670 if(mask&INITIALIZED_VO){
671 mpctx->initialized_flags&=~INITIALIZED_VO;
672 current_module="uninit_vo";
673 vo_destroy(mpctx->video_out);
674 mpctx->video_out=NULL;
675 #ifdef CONFIG_DVDNAV
676 mp_dvdnav_context_free(mpctx);
677 #endif
680 // Must be after libvo uninit, as few vo drivers (svgalib) have tty code.
681 if(mask&INITIALIZED_GETCH2){
682 mpctx->initialized_flags&=~INITIALIZED_GETCH2;
683 current_module="uninit_getch2";
684 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[uninit getch2]]]\n");
685 // restore terminal:
686 getch2_disable();
689 if(mask&INITIALIZED_VOBSUB){
690 mpctx->initialized_flags&=~INITIALIZED_VOBSUB;
691 current_module="uninit_vobsub";
692 if(vo_vobsub) vobsub_close(vo_vobsub);
693 vo_vobsub=NULL;
696 if (mask&INITIALIZED_SPUDEC){
697 mpctx->initialized_flags&=~INITIALIZED_SPUDEC;
698 current_module="uninit_spudec";
699 spudec_free(vo_spudec);
700 vo_spudec=NULL;
703 if(mask&INITIALIZED_AO){
704 mpctx->initialized_flags&=~INITIALIZED_AO;
705 current_module="uninit_ao";
706 if (mpctx->edl_muted) mixer_mute(&mpctx->mixer);
707 if (mpctx->ao)
708 ao_uninit(mpctx->ao, mpctx->stop_play != AT_END_OF_FILE);
709 mpctx->ao = NULL;
712 current_module=NULL;
715 void exit_player_with_rc(struct MPContext *mpctx, enum exit_reason how, int rc)
717 if (mpctx->user_muted && !mpctx->edl_muted) mixer_mute(&mpctx->mixer);
718 uninit_player(mpctx, INITIALIZED_ALL);
719 #if defined(__MINGW32__) || defined(__CYGWIN__)
720 timeEndPeriod(1);
721 #endif
722 #ifdef CONFIG_X11
723 vo_uninit(mpctx->x11_state); // Close the X11 connection (if any is open).
724 #endif
726 current_module="uninit_input";
727 mp_input_uninit(mpctx->input);
728 #ifdef CONFIG_MENU
729 if (use_menu)
730 menu_uninit();
731 #endif
733 #ifdef CONFIG_FREETYPE
734 current_module="uninit_font";
735 if (mpctx->osd && mpctx->osd->sub_font != vo_font)
736 free_font_desc(mpctx->osd->sub_font);
737 free_font_desc(vo_font);
738 vo_font = NULL;
739 done_freetype();
740 #endif
741 osd_free(mpctx->osd);
743 #ifdef CONFIG_ASS
744 ass_library_done(ass_library);
745 ass_library = NULL;
746 #endif
748 current_module="exit_player";
750 if(mpctx->playtree_iter)
751 play_tree_iter_free(mpctx->playtree_iter);
752 mpctx->playtree_iter = NULL;
753 if(mpctx->playtree)
754 play_tree_free(mpctx->playtree, 1);
755 mpctx->playtree = NULL;
757 talloc_free(mpctx->key_fifo);
759 free(edl_records); // free mem allocated for EDL
760 edl_records = NULL;
761 switch(how) {
762 case EXIT_QUIT:
763 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Quit");
764 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=QUIT\n");
765 break;
766 case EXIT_EOF:
767 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","End of file");
768 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=EOF\n");
769 break;
770 case EXIT_ERROR:
771 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Fatal error");
772 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=ERROR\n");
773 break;
774 default:
775 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=NONE\n");
777 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"max framesize was %d bytes\n",max_framesize);
779 // must be last since e.g. mp_msg uses option values
780 // that will be freed by this.
781 if (mpctx->mconfig)
782 m_config_free(mpctx->mconfig);
783 mpctx->mconfig = NULL;
785 exit(rc);
788 static void exit_player(struct MPContext *mpctx, enum exit_reason how)
790 exit_player_with_rc(mpctx, how, 1);
793 #ifndef __MINGW32__
794 static void child_sighandler(int x){
795 pid_t pid;
796 while((pid=waitpid(-1,NULL,WNOHANG)) > 0);
798 #endif
800 #ifdef CONFIG_CRASH_DEBUG
801 static char *prog_path;
802 static int crash_debug = 0;
803 #endif
805 static void exit_sighandler(int x){
806 static int sig_count=0;
807 #ifdef CONFIG_CRASH_DEBUG
808 if (!crash_debug || x != SIGTRAP)
809 #endif
810 ++sig_count;
811 if(sig_count==5)
813 /* We're crashing bad and can't uninit cleanly :(
814 * by popular request, we make one last (dirty)
815 * effort to restore the user's
816 * terminal. */
817 getch2_disable();
818 exit(1);
820 if(sig_count==6) exit(1);
821 if(sig_count>6){
822 // can't stop :(
823 #ifndef __MINGW32__
824 kill(getpid(),SIGKILL);
825 #endif
827 mp_msg(MSGT_CPLAYER, MSGL_FATAL, "\n");
828 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,
829 "\nMPlayer interrupted by signal %d in module: %s\n", x,
830 current_module ? current_module : "unknown");
831 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SIGNAL=%d\n", x);
832 if(sig_count<=1)
833 switch(x){
834 case SIGINT:
835 case SIGPIPE:
836 case SIGQUIT:
837 case SIGTERM:
838 case SIGKILL:
839 async_quit_request = 1;
840 return; // killed from keyboard (^C) or killed [-9]
841 case SIGILL:
842 #if CONFIG_RUNTIME_CPUDETECT
843 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL_RTCpuSel);
844 #else
845 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL);
846 #endif
847 case SIGFPE:
848 case SIGSEGV:
849 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGSEGV_SIGFPE);
850 default:
851 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGCRASH);
852 #ifdef CONFIG_CRASH_DEBUG
853 if (crash_debug) {
854 int gdb_pid;
855 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forking...\n");
856 gdb_pid = fork();
857 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forked...\n");
858 if (gdb_pid == 0) { // We are the child
859 char spid[20];
860 snprintf(spid, sizeof(spid), "%i", getppid());
861 getch2_disable(); // allow terminal to work properly with gdb
862 if (execlp("gdb", "gdb", prog_path, spid, "-ex", "bt", NULL) == -1)
863 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't start gdb\n");
864 } else if (gdb_pid < 0)
865 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't fork\n");
866 else {
867 waitpid(gdb_pid, NULL, 0);
869 if (x == SIGTRAP) return;
871 #endif
873 getch2_disable();
874 exit(1);
877 #include "cfg-mplayer.h"
879 static int cfg_include(m_option_t *conf, char *filename)
881 return m_config_parse_config_file(conf->priv, filename);
884 #define DEF_CONFIG "# Write your default config options here!\n\n\n"
886 static void parse_cfgfiles(struct MPContext *mpctx, m_config_t* conf)
888 struct MPOpts *opts = &mpctx->opts;
889 char *conffile;
890 int conffile_fd;
891 if (!(opts->noconfig & 2) &&
892 m_config_parse_config_file(conf, MPLAYER_CONFDIR "/mplayer.conf") < 0)
893 exit_player(mpctx, EXIT_NONE);
894 if ((conffile = get_path("")) == NULL) {
895 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"Cannot find HOME directory.\n");
896 } else {
897 #ifdef __MINGW32__
898 mkdir(conffile);
899 #else
900 mkdir(conffile, 0777);
901 #endif
902 free(conffile);
903 if ((conffile = get_path("config")) == NULL) {
904 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"get_path(\"config\") problem\n");
905 } else {
906 if ((conffile_fd = open(conffile, O_CREAT | O_EXCL | O_WRONLY, 0666)) != -1) {
907 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Creating config file: %s\n", conffile);
908 write(conffile_fd, DEF_CONFIG, sizeof(DEF_CONFIG) - 1);
909 close(conffile_fd);
911 if (!(opts->noconfig & 1) &&
912 m_config_parse_config_file(conf, conffile) < 0)
913 exit_player(mpctx, EXIT_NONE);
914 free(conffile);
919 #define PROFILE_CFG_PROTOCOL "protocol."
921 static void load_per_protocol_config (m_config_t* conf, const char *const file)
923 char *str;
924 char protocol[strlen (PROFILE_CFG_PROTOCOL) + strlen (file) + 1];
925 m_profile_t *p;
927 /* does filename actually uses a protocol ? */
928 str = strstr (file, "://");
929 if (!str)
930 return;
932 sprintf (protocol, "%s%s", PROFILE_CFG_PROTOCOL, file);
933 protocol[strlen (PROFILE_CFG_PROTOCOL)+strlen(file)-strlen(str)] = '\0';
934 p = m_config_get_profile (conf, protocol);
935 if (p)
937 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading protocol-related profile '%s'\n", protocol);
938 m_config_set_profile(conf,p);
942 #define PROFILE_CFG_EXTENSION "extension."
944 static void load_per_extension_config (m_config_t* conf, const char *const file)
946 char *str;
947 char extension[strlen (PROFILE_CFG_EXTENSION) + 8];
948 m_profile_t *p;
950 /* does filename actually have an extension ? */
951 str = strrchr (file, '.');
952 if (!str)
953 return;
955 sprintf (extension, PROFILE_CFG_EXTENSION);
956 strncat (extension, ++str, 7);
957 p = m_config_get_profile (conf, extension);
958 if (p)
960 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", extension);
961 m_config_set_profile(conf,p);
965 #define PROFILE_CFG_VO "vo."
966 #define PROFILE_CFG_AO "ao."
968 static void load_per_output_config (m_config_t* conf, char *cfg, char *out)
970 char profile[strlen (cfg) + strlen (out) + 1];
971 m_profile_t *p;
973 sprintf (profile, "%s%s", cfg, out);
974 p = m_config_get_profile (conf, profile);
975 if (p)
977 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", profile);
978 m_config_set_profile(conf,p);
983 * Tries to load a config file
984 * @return 0 if file was not found, 1 otherwise
986 static int try_load_config(m_config_t *conf, const char *file)
988 struct stat st;
989 if (stat(file, &st))
990 return 0;
991 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Loading config '%s'\n", file);
992 m_config_parse_config_file (conf, file);
993 return 1;
996 static void load_per_file_config (m_config_t* conf, const char *const file)
998 char *confpath;
999 char cfg[PATH_MAX];
1000 const char *name;
1002 if (strlen(file) > PATH_MAX - 14) {
1003 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Filename is too long, can not load file or directory specific config files\n");
1004 return;
1006 sprintf (cfg, "%s.conf", file);
1008 name = mp_basename(cfg);
1009 if (use_filedir_conf) {
1010 char dircfg[PATH_MAX];
1011 strcpy(dircfg, cfg);
1012 strcpy(dircfg + (name - cfg), "mplayer.conf");
1013 try_load_config(conf, dircfg);
1015 if (try_load_config(conf, cfg))
1016 return;
1019 if ((confpath = get_path (name)) != NULL)
1021 try_load_config(conf, confpath);
1023 free (confpath);
1027 /* When libmpdemux performs a blocking operation (network connection or
1028 * cache filling) if the operation fails we use this function to check
1029 * if it was interrupted by the user.
1030 * The function returns a new value for eof. */
1031 static int libmpdemux_was_interrupted(struct MPContext *mpctx, int stop_play)
1033 mp_cmd_t* cmd;
1034 if((cmd = mp_input_get_cmd(mpctx->input, 0, 0)) != NULL) {
1035 switch(cmd->id) {
1036 case MP_CMD_QUIT:
1037 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
1038 case MP_CMD_PLAY_TREE_STEP: {
1039 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_ENTRY : PT_PREV_ENTRY;
1040 mpctx->play_tree_step = (cmd->args[0].v.i == 0) ? 1 : cmd->args[0].v.i;
1041 } break;
1042 case MP_CMD_PLAY_TREE_UP_STEP: {
1043 stop_play = (cmd->args[0].v.i > 0) ? PT_UP_NEXT : PT_UP_PREV;
1044 } break;
1045 case MP_CMD_PLAY_ALT_SRC_STEP: {
1046 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_SRC : PT_PREV_SRC;
1047 } break;
1049 mp_cmd_free(cmd);
1051 return stop_play;
1054 static int playtree_add_playlist(struct MPContext *mpctx, play_tree_t* entry)
1056 play_tree_add_bpf(entry,mpctx->filename);
1059 if(!entry) {
1060 entry = mpctx->playtree_iter->tree;
1061 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1062 return PT_NEXT_ENTRY;
1064 if(mpctx->playtree_iter->tree == entry ) { // Loop with a single file
1065 if(play_tree_iter_up_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1066 return PT_NEXT_ENTRY;
1069 play_tree_remove(entry,1,1);
1070 return PT_NEXT_SRC;
1072 play_tree_insert_entry(mpctx->playtree_iter->tree,entry);
1073 play_tree_set_params_from(entry,mpctx->playtree_iter->tree);
1074 entry = mpctx->playtree_iter->tree;
1075 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1076 return PT_NEXT_ENTRY;
1078 play_tree_remove(entry,1,1);
1080 return PT_NEXT_SRC;
1083 void add_subtitles(struct MPContext *mpctx, char *filename, float fps, int noerr)
1085 struct MPOpts *opts = &mpctx->opts;
1086 sub_data *subd = NULL;
1087 struct ass_track *asst = NULL;
1088 bool is_native_ass = false;
1090 if (filename == NULL || mpctx->set_of_sub_size >= MAX_SUBTITLE_FILES)
1091 return;
1093 #ifdef CONFIG_ASS
1094 if (opts->ass_enabled) {
1095 #ifdef CONFIG_ICONV
1096 asst = mp_ass_read_stream(ass_library, filename, sub_cp);
1097 #else
1098 asst = mp_ass_read_stream(ass_library, filename, 0);
1099 #endif
1100 is_native_ass = asst;
1101 if (!asst) {
1102 subd = sub_read_file(filename, fps, &mpctx->opts);
1103 if (subd) {
1104 asst = mp_ass_read_subdata(ass_library, subd, fps);
1105 sub_free(subd);
1106 subd = NULL;
1109 } else
1110 #endif
1111 subd = sub_read_file(filename, fps, &mpctx->opts);
1114 if (!asst && !subd) {
1115 mp_tmsg(MSGT_CPLAYER, noerr ? MSGL_WARN : MSGL_ERR,
1116 "Cannot load subtitles: %s\n", filename_recode(filename));
1117 return;
1120 mpctx->set_of_ass_tracks[mpctx->set_of_sub_size] = asst;
1121 mpctx->set_of_subtitles[mpctx->set_of_sub_size] = subd;
1122 mpctx->track_was_native_ass[mpctx->set_of_sub_size] = is_native_ass;
1123 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_ID=%d\n", mpctx->set_of_sub_size);
1124 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_FILENAME=%s\n",
1125 filename_recode(filename));
1126 ++mpctx->set_of_sub_size;
1127 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "SUB: Added subtitle file (%d): %s\n", mpctx->set_of_sub_size,
1128 filename_recode(filename));
1131 void init_vo_spudec(struct MPContext *mpctx)
1133 spudec_free(vo_spudec);
1134 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
1135 vo_spudec = NULL;
1137 // we currently can't work without video stream
1138 if (!mpctx->sh_video)
1139 return;
1141 if (spudec_ifo) {
1142 unsigned int palette[16], width, height;
1143 current_module="spudec_init_vobsub";
1144 if (vobsub_parse_ifo(NULL,spudec_ifo, palette, &width, &height, 1, -1, NULL) >= 0)
1145 vo_spudec=spudec_new_scaled(palette, width, height, NULL, 0);
1148 #ifdef CONFIG_DVDREAD
1149 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVD) {
1150 current_module="spudec_init_dvdread";
1151 vo_spudec=spudec_new_scaled(((dvd_priv_t *)(mpctx->stream->priv))->cur_pgc->palette,
1152 mpctx->sh_video->disp_w, mpctx->sh_video->disp_h,
1153 NULL, 0);
1155 #endif
1157 #ifdef CONFIG_DVDNAV
1158 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVDNAV) {
1159 unsigned int *palette = mp_dvdnav_get_spu_clut(mpctx->stream);
1160 current_module="spudec_init_dvdnav";
1161 vo_spudec=spudec_new_scaled(palette, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, NULL, 0);
1163 #endif
1165 if (vo_spudec==NULL) {
1166 sh_sub_t *sh = mpctx->d_sub->sh;
1167 current_module="spudec_init_normal";
1168 vo_spudec=spudec_new_scaled(NULL, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, sh->extradata, sh->extradata_len);
1169 spudec_set_font_factor(vo_spudec,font_factor);
1172 if (vo_spudec!=NULL) {
1173 mpctx->initialized_flags|=INITIALIZED_SPUDEC;
1174 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
1179 * In Mac OS X the SDL-lib is built upon Cocoa. The easiest way to
1180 * make it all work is to use the builtin SDL-bootstrap code, which
1181 * will be done automatically by replacing our main() if we include SDL.h.
1183 #if defined(__APPLE__) && defined(CONFIG_SDL)
1184 #ifdef CONFIG_SDL_SDL_H
1185 #include <SDL/SDL.h>
1186 #else
1187 #include <SDL.h>
1188 #endif
1189 #endif
1192 * \brief append a formatted string
1193 * \param buf buffer to print into
1194 * \param pos position of terminating 0 in buf
1195 * \param len maximum number of characters in buf, not including terminating 0
1196 * \param format printf format string
1198 static void saddf(char *buf, unsigned *pos, int len, const char *format, ...)
1200 va_list va;
1201 va_start(va, format);
1202 *pos += vsnprintf(&buf[*pos], len - *pos, format, va);
1203 va_end(va);
1204 if (*pos >= len ) {
1205 buf[len] = 0;
1206 *pos = len;
1211 * \brief append time in the hh:mm:ss.f format
1212 * \param buf buffer to print into
1213 * \param pos position of terminating 0 in buf
1214 * \param len maximum number of characters in buf, not including terminating 0
1215 * \param time time value to convert/append
1217 static void sadd_hhmmssf(char *buf, unsigned *pos, int len, float time) {
1218 int64_t tenths = 10 * time;
1219 int f1 = tenths % 10;
1220 int ss = (tenths / 10) % 60;
1221 int mm = (tenths / 600) % 60;
1222 int hh = tenths / 36000;
1223 if (time <= 0) {
1224 saddf(buf, pos, len, "unknown");
1225 return;
1227 if (hh > 0)
1228 saddf(buf, pos, len, "%2d:", hh);
1229 if (hh > 0 || mm > 0)
1230 saddf(buf, pos, len, "%02d:", mm);
1231 saddf(buf, pos, len, "%02d.%1d", ss, f1);
1234 static void print_status(struct MPContext *mpctx, double a_pos, bool at_frame)
1236 struct MPOpts *opts = &mpctx->opts;
1237 sh_video_t * const sh_video = mpctx->sh_video;
1239 if (mpctx->sh_audio && a_pos == MP_NOPTS_VALUE)
1240 a_pos = playing_audio_pts(mpctx);
1241 if (mpctx->sh_audio && sh_video && at_frame) {
1242 mpctx->last_av_difference = a_pos - mpctx->video_pts - audio_delay;
1243 if (mpctx->time_frame > 0)
1244 mpctx->last_av_difference += mpctx->time_frame * opts->playback_speed;
1245 if (mpctx->last_av_difference > 0.5 && drop_frame_cnt > 50
1246 && !mpctx->drop_message_shown) {
1247 mp_tmsg(MSGT_AVSYNC,MSGL_WARN,SystemTooSlow);
1248 mpctx->drop_message_shown = true;
1251 if (opts->quiet)
1252 return;
1255 int width;
1256 char *line;
1257 unsigned pos = 0;
1258 get_screen_size();
1259 if (screen_width > 0)
1260 width = screen_width;
1261 else
1262 width = 80;
1263 #if defined(__MINGW32__) || defined(__CYGWIN__) || defined(__OS2__)
1264 /* Windows command line is broken (MinGW's rxvt works, but we
1265 * should not depend on that). */
1266 width--;
1267 #endif
1268 line = malloc(width + 1); // one additional char for the terminating null
1270 // Audio time
1271 if (mpctx->sh_audio) {
1272 saddf(line, &pos, width, "A:%6.1f ", a_pos);
1273 if (!sh_video) {
1274 float len = get_time_length(mpctx);
1275 saddf(line, &pos, width, "(");
1276 sadd_hhmmssf(line, &pos, width, a_pos);
1277 saddf(line, &pos, width, ") of %.1f (", len);
1278 sadd_hhmmssf(line, &pos, width, len);
1279 saddf(line, &pos, width, ") ");
1283 // Video time
1284 if (sh_video)
1285 saddf(line, &pos, width, "V:%6.1f ", mpctx->video_pts);
1287 // A-V sync
1288 if (mpctx->sh_audio && sh_video)
1289 saddf(line, &pos, width, "A-V:%7.3f ct:%7.3f ",
1290 mpctx->last_av_difference, mpctx->total_avsync_change);
1292 // Video stats
1293 if (sh_video)
1294 saddf(line, &pos, width, "%3d/%3d ",
1295 (int)sh_video->num_frames,
1296 (int)sh_video->num_frames_decoded);
1298 // CPU usage
1299 if (sh_video) {
1300 if (sh_video->timer > 0.5)
1301 saddf(line, &pos, width, "%2d%% %2d%% %4.1f%% ",
1302 (int)(100.0*video_time_usage*opts->playback_speed/(double)sh_video->timer),
1303 (int)(100.0*vout_time_usage*opts->playback_speed/(double)sh_video->timer),
1304 (100.0*audio_time_usage*opts->playback_speed/(double)sh_video->timer));
1305 else
1306 saddf(line, &pos, width, "??%% ??%% ??,?%% ");
1307 } else if (mpctx->sh_audio) {
1308 if (mpctx->delay > 0.5)
1309 saddf(line, &pos, width, "%4.1f%% ",
1310 100.0*audio_time_usage/(double)mpctx->delay);
1311 else
1312 saddf(line, &pos, width, "??,?%% ");
1315 // VO stats
1316 if (sh_video)
1317 saddf(line, &pos, width, "%d %d ", drop_frame_cnt, output_quality);
1319 #ifdef CONFIG_STREAM_CACHE
1320 // cache stats
1321 if (stream_cache_size > 0)
1322 saddf(line, &pos, width, "%d%% ", cache_fill_status(mpctx->stream));
1323 #endif
1325 // other
1326 if (opts->playback_speed != 1)
1327 saddf(line, &pos, width, "%4.2fx ", opts->playback_speed);
1329 // end
1330 if (erase_to_end_of_line) {
1331 line[pos] = 0;
1332 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s%s\r", line, erase_to_end_of_line);
1333 } else {
1334 memset(&line[pos], ' ', width - pos);
1335 line[width] = 0;
1336 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s\r", line);
1338 free(line);
1341 struct stream_dump_progress {
1342 uint64_t count;
1343 unsigned start_time;
1344 unsigned last_print_time;
1347 static void stream_dump_progress_start(struct stream_dump_progress *p)
1349 p->start_time = p->last_print_time = GetTimerMS();
1350 p->count = 0;
1353 static void stream_dump_progress(struct stream_dump_progress *p,
1354 uint64_t len, stream_t *stream)
1356 p->count += len;
1357 unsigned t = GetTimerMS();
1358 if (t - p->last_print_time < 1000)
1359 return;
1361 uint64_t start = stream->start_pos;
1362 uint64_t end = stream->end_pos;
1363 uint64_t pos = stream->pos;
1365 p->last_print_time = t;
1366 /* TODO: pretty print sizes; ETA */
1367 if (end > start && pos >= start && pos <= end) {
1368 mp_tmsg(MSGT_STATUSLINE, MSGL_STATUS,
1369 "dump: %"PRIu64" bytes written (~%.1f%%)",
1370 p->count, 100.0 * (pos - start) / (end - start));
1371 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "\r");
1372 } else {
1373 mp_tmsg(MSGT_STATUSLINE, MSGL_STATUS,
1374 "dump: %"PRIu64" bytes written", p->count);
1375 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "\r");
1379 static void stream_dump_progress_end(struct stream_dump_progress *p, char *name)
1381 mp_msg(MSGT_CPLAYER, MSGL_INFO, "dump: %"PRIu64" bytes written to '%s'.\n",
1382 p->count, name);
1386 * \brief build a chain of audio filters that converts the input format
1387 * to the ao's format, taking into account the current playback_speed.
1388 * sh_audio describes the requested input format of the chain.
1389 * ao describes the requested output format of the chain.
1391 static int build_afilter_chain(struct MPContext *mpctx)
1393 struct sh_audio *sh_audio = mpctx->sh_audio;
1394 struct ao *ao = mpctx->ao;
1395 struct MPOpts *opts = &mpctx->opts;
1396 int new_srate;
1397 int result;
1398 if (!sh_audio)
1400 mpctx->mixer.afilter = NULL;
1401 return 0;
1403 if(af_control_any_rev(sh_audio->afilter,
1404 AF_CONTROL_PLAYBACK_SPEED | AF_CONTROL_SET,
1405 &opts->playback_speed)) {
1406 new_srate = sh_audio->samplerate;
1407 } else {
1408 new_srate = sh_audio->samplerate * opts->playback_speed;
1409 if (new_srate != ao->samplerate) {
1410 // limits are taken from libaf/af_resample.c
1411 if (new_srate < 8000)
1412 new_srate = 8000;
1413 if (new_srate > 192000)
1414 new_srate = 192000;
1415 opts->playback_speed = (float)new_srate / (float)sh_audio->samplerate;
1418 result = init_audio_filters(sh_audio, new_srate,
1419 &ao->samplerate, &ao->channels, &ao->format);
1420 mpctx->mixer.afilter = sh_audio->afilter;
1421 return result;
1425 typedef struct mp_osd_msg mp_osd_msg_t;
1426 struct mp_osd_msg {
1427 /// Previous message on the stack.
1428 mp_osd_msg_t* prev;
1429 /// Message text.
1430 char msg[128];
1431 int id,level,started;
1432 /// Display duration in ms.
1433 unsigned time;
1436 /// OSD message stack.
1437 static mp_osd_msg_t* osd_msg_stack = NULL;
1440 * \brief Add a message on the OSD message stack
1442 * If a message with the same id is already present in the stack
1443 * it is pulled on top of the stack, otherwise a new message is created.
1446 static void set_osd_msg_va(int id, int level, int time, const char *fmt,
1447 va_list ap)
1449 mp_osd_msg_t *msg,*last=NULL;
1450 int r;
1452 // look if the id is already in the stack
1453 for(msg = osd_msg_stack ; msg && msg->id != id ;
1454 last = msg, msg = msg->prev);
1455 // not found: alloc it
1456 if(!msg) {
1457 msg = calloc(1,sizeof(mp_osd_msg_t));
1458 msg->prev = osd_msg_stack;
1459 osd_msg_stack = msg;
1460 } else if(last) { // found, but it's not on top of the stack
1461 last->prev = msg->prev;
1462 msg->prev = osd_msg_stack;
1463 osd_msg_stack = msg;
1465 // write the msg
1466 r = vsnprintf(msg->msg, 128, fmt, ap);
1467 if(r >= 128) msg->msg[127] = 0;
1468 // set id and time
1469 msg->id = id;
1470 msg->level = level;
1471 msg->time = time;
1475 void set_osd_msg(int id, int level, int time, const char *fmt, ...)
1477 va_list ap;
1478 va_start(ap, fmt);
1479 set_osd_msg_va(id, level, time, fmt, ap);
1480 va_end(ap);
1483 void set_osd_tmsg(int id, int level, int time, const char *fmt, ...)
1485 va_list ap;
1486 va_start(ap, fmt);
1487 set_osd_msg_va(id, level, time, mp_gtext(fmt), ap);
1488 va_end(ap);
1493 * \brief Remove a message from the OSD stack
1495 * This function can be used to get rid of a message right away.
1499 void rm_osd_msg(int id) {
1500 mp_osd_msg_t *msg,*last=NULL;
1502 // Search for the msg
1503 for(msg = osd_msg_stack ; msg && msg->id != id ;
1504 last = msg, msg = msg->prev);
1505 if(!msg) return;
1507 // Detach it from the stack and free it
1508 if(last)
1509 last->prev = msg->prev;
1510 else
1511 osd_msg_stack = msg->prev;
1512 free(msg);
1516 * \brief Remove all messages from the OSD stack
1520 static void clear_osd_msgs(void) {
1521 mp_osd_msg_t* msg = osd_msg_stack, *prev = NULL;
1522 while(msg) {
1523 prev = msg->prev;
1524 free(msg);
1525 msg = prev;
1527 osd_msg_stack = NULL;
1531 * \brief Get the current message from the OSD stack.
1533 * This function decrements the message timer and destroys the old ones.
1534 * The message that should be displayed is returned (if any).
1538 static mp_osd_msg_t* get_osd_msg(struct MPContext *mpctx)
1540 struct MPOpts *opts = &mpctx->opts;
1541 mp_osd_msg_t *msg,*prev,*last = NULL;
1542 static unsigned last_update = 0;
1543 unsigned now = GetTimerMS();
1544 unsigned diff;
1545 char hidden_dec_done = 0;
1547 if (mpctx->osd_visible) {
1548 // 36000000 means max timed visibility is 1 hour into the future, if
1549 // the difference is greater assume it's wrapped around from below 0
1550 if (mpctx->osd_visible - now > 36000000) {
1551 mpctx->osd_visible = 0;
1552 vo_osd_progbar_type = -1; // disable
1553 vo_osd_changed(OSDTYPE_PROGBAR);
1554 mpctx->osd_function = mpctx->paused ? OSD_PAUSE : OSD_PLAY;
1557 if (mpctx->osd_show_percentage_until - now > 36000000)
1558 mpctx->osd_show_percentage_until = 0;
1560 if(!last_update) last_update = now;
1561 diff = now >= last_update ? now - last_update : 0;
1563 last_update = now;
1565 // Look for the first message in the stack with high enough level.
1566 for(msg = osd_msg_stack ; msg ; last = msg, msg = prev) {
1567 prev = msg->prev;
1568 if (msg->level > opts->osd_level && hidden_dec_done)
1569 continue;
1570 // The message has a high enough level or it is the first hidden one
1571 // in both cases we decrement the timer or kill it.
1572 if(!msg->started || msg->time > diff) {
1573 if(msg->started) msg->time -= diff;
1574 else msg->started = 1;
1575 // display it
1576 if (msg->level <= opts->osd_level)
1577 return msg;
1578 hidden_dec_done = 1;
1579 continue;
1581 // kill the message
1582 free(msg);
1583 if(last) {
1584 last->prev = prev;
1585 msg = last;
1586 } else {
1587 osd_msg_stack = prev;
1588 msg = NULL;
1591 // Nothing found
1592 return NULL;
1596 * \brief Display the OSD bar.
1598 * Display the OSD bar or fall back on a simple message.
1602 void set_osd_bar(struct MPContext *mpctx, int type,const char* name,double min,double max,double val) {
1603 struct MPOpts *opts = &mpctx->opts;
1604 if (opts->osd_level < 1)
1605 return;
1607 if(mpctx->sh_video) {
1608 mpctx->osd_visible = (GetTimerMS() + 1000) | 1;
1609 vo_osd_progbar_type = type;
1610 vo_osd_progbar_value = 256*(val-min)/(max-min);
1611 vo_osd_changed(OSDTYPE_PROGBAR);
1612 return;
1615 set_osd_msg(OSD_MSG_BAR, 1, opts->osd_duration, "%s: %d %%",
1616 name, ROUND(100*(val-min)/(max-min)));
1620 * \brief Display text subtitles on the OSD
1622 void set_osd_subtitle(struct MPContext *mpctx, subtitle *subs)
1624 int i;
1625 vo_sub = subs;
1626 vo_osd_changed(OSDTYPE_SUBTITLE);
1627 if (!mpctx->sh_video) {
1628 // reverse order, since newest set_osd_msg is displayed first
1629 for (i = SUB_MAX_TEXT - 1; i >= 0; i--) {
1630 if (!subs || i >= subs->lines || !subs->text[i])
1631 rm_osd_msg(OSD_MSG_SUB_BASE + i);
1632 else {
1633 // HACK: currently display time for each sub line except the last is set to 2 seconds.
1634 int display_time = i == subs->lines - 1 ? 180000 : 2000;
1635 set_osd_msg(OSD_MSG_SUB_BASE + i, 1, display_time, "%s", subs->text[i]);
1642 * \brief Update the OSD message line.
1644 * This function displays the current message on the vo OSD or on the term.
1645 * If the stack is empty and the OSD level is high enough the timer
1646 * is displayed (only on the vo OSD).
1650 static void update_osd_msg(struct MPContext *mpctx)
1652 struct MPOpts *opts = &mpctx->opts;
1653 mp_osd_msg_t *msg;
1654 struct osd_state *osd = mpctx->osd;
1655 char osd_text_timer[128];
1657 if (mpctx->add_osd_seek_info) {
1658 double percentage = get_percent_pos(mpctx);
1659 set_osd_bar(mpctx, 0, "Position", 0, 100, percentage);
1660 if (mpctx->sh_video)
1661 mpctx->osd_show_percentage_until = (GetTimerMS() + 1000) | 1;
1662 mpctx->add_osd_seek_info = false;
1665 // Look if we have a msg
1666 if((msg = get_osd_msg(mpctx))) {
1667 if (strcmp(osd->osd_text, msg->msg)) {
1668 strncpy(osd->osd_text, msg->msg, 127);
1669 if(mpctx->sh_video) vo_osd_changed(OSDTYPE_OSD); else
1670 if(opts->term_osd)
1671 mp_msg(MSGT_CPLAYER,MSGL_STATUS, "%s%s\n", opts->term_osd_esc,
1672 msg->msg);
1674 return;
1677 if(mpctx->sh_video) {
1678 // fallback on the timer
1679 if (opts->osd_level >= 2) {
1680 int len = get_time_length(mpctx);
1681 int percentage = -1;
1682 char percentage_text[10];
1683 char fractions_text[4];
1684 double fpts = get_current_time(mpctx);
1685 int pts = fpts;
1687 if (mpctx->osd_show_percentage_until)
1688 percentage = get_percent_pos(mpctx);
1690 if (percentage >= 0)
1691 snprintf(percentage_text, 9, " (%d%%)", percentage);
1692 else
1693 percentage_text[0] = 0;
1695 if (opts->osd_fractions == 1) {
1696 //print fractions as sub-second timestamp
1697 snprintf(fractions_text, sizeof(fractions_text), ".%02d",
1698 (int)((fpts - pts) * 100));
1699 } else if (opts->osd_fractions == 2) {
1700 /* Print fractions by estimating the frame count within the
1701 * second.
1703 * Rounding or cutting off numbers after the decimal point
1704 * causes problems because of float's precision and movies
1705 * whose first frame is not exactly at timestamp 0. Therefore,
1706 * we add 0.2 and cut off at the decimal point, which proved
1707 * to be good heuristic.
1709 double fps = mpctx->sh_video->fps;
1710 if (fps <= 1 || fps > 99)
1711 strcpy(fractions_text, ".??");
1712 else
1713 snprintf(fractions_text, sizeof(fractions_text), ".%02d",
1714 (int) ( (fpts - pts) * fps + 0.2 ) );
1715 } else {
1716 //do not print fractions
1717 fractions_text[0] = 0;
1720 if (opts->osd_level == 3)
1721 snprintf(osd_text_timer, 63,
1722 "%c %02d:%02d:%02d%s / %02d:%02d:%02d%s",
1723 mpctx->osd_function,pts/3600,(pts/60)%60,pts%60,
1724 fractions_text, len/3600, (len/60)%60, len%60,
1725 percentage_text);
1726 else
1727 snprintf(osd_text_timer, 63, "%c %02d:%02d:%02d%s%s",
1728 mpctx->osd_function,pts/3600,(pts/60)%60,
1729 pts%60, fractions_text, percentage_text);
1730 } else
1731 osd_text_timer[0]=0;
1733 if (strcmp(osd->osd_text, osd_text_timer)) {
1734 strncpy(osd->osd_text, osd_text_timer, 63);
1735 vo_osd_changed(OSDTYPE_OSD);
1737 return;
1740 // Clear the term osd line
1741 if (opts->term_osd && osd->osd_text[0]) {
1742 osd->osd_text[0] = 0;
1743 printf("%s\n", opts->term_osd_esc);
1747 ///@}
1748 // OSDMsgStack
1751 void reinit_audio_chain(struct MPContext *mpctx)
1753 struct MPOpts *opts = &mpctx->opts;
1754 struct ao *ao;
1755 if (!mpctx->sh_audio)
1756 return;
1757 if (!(mpctx->initialized_flags & INITIALIZED_ACODEC)) {
1758 current_module="init_audio_codec";
1759 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1760 if(!init_best_audio_codec(mpctx->sh_audio,audio_codec_list,audio_fm_list)){
1761 goto init_error;
1763 mpctx->initialized_flags|=INITIALIZED_ACODEC;
1764 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1768 current_module="af_preinit";
1769 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1770 mpctx->initialized_flags |= INITIALIZED_AO;
1771 mpctx->ao = ao_create();
1772 mpctx->ao->samplerate = force_srate;
1773 mpctx->ao->format = opts->audio_output_format;
1775 ao = mpctx->ao;
1777 // first init to detect best values
1778 if(!init_audio_filters(mpctx->sh_audio, // preliminary init
1779 // input:
1780 mpctx->sh_audio->samplerate,
1781 // output:
1782 &ao->samplerate, &ao->channels, &ao->format)) {
1783 mp_tmsg(MSGT_CPLAYER,MSGL_ERR, "Error at audio filter chain "
1784 "pre-init!\n");
1785 exit_player(mpctx, EXIT_ERROR);
1787 if (!ao->initialized) {
1788 current_module="ao2_init";
1789 ao->buffersize = opts->ao_buffersize;
1790 ao_init(ao, opts->audio_driver_list);
1791 if (!ao->initialized) {
1792 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Could not open/initialize audio device -> no sound.\n");
1793 goto init_error;
1795 ao->buffer.start = talloc_new(ao);
1796 mp_msg(MSGT_CPLAYER,MSGL_INFO,"AO: [%s] %dHz %dch %s (%d bytes per sample)\n",
1797 ao->driver->info->short_name,
1798 ao->samplerate, ao->channels,
1799 af_fmt2str_short(ao->format),
1800 af_fmt2bits(ao->format)/8 );
1801 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Description: %s\nAO: Author: %s\n",
1802 ao->driver->info->name, ao->driver->info->author);
1803 if (strlen(ao->driver->info->comment) > 0)
1804 mp_msg(MSGT_CPLAYER, MSGL_V, "AO: Comment: %s\n",
1805 ao->driver->info->comment);
1808 // init audio filters:
1809 current_module="af_init";
1810 if (!build_afilter_chain(mpctx)) {
1811 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Couldn't find matching filter/ao format!\n");
1812 goto init_error;
1814 mpctx->mixer.ao = ao;
1815 mpctx->mixer.volstep = volstep;
1816 mpctx->syncing_audio = true;
1817 return;
1819 init_error:
1820 uninit_player(mpctx, INITIALIZED_ACODEC|INITIALIZED_AO); // close codec and possibly AO
1821 mpctx->sh_audio=mpctx->d_audio->sh=NULL; // -> nosound
1822 mpctx->d_audio->id = -2;
1826 ///@}
1827 // Command2Property
1830 // Return pts value corresponding to the end point of audio written to the
1831 // ao so far.
1832 static double written_audio_pts(struct MPContext *mpctx)
1834 sh_audio_t *sh_audio = mpctx->sh_audio;
1835 demux_stream_t *d_audio = mpctx->d_audio;
1836 // first calculate the end pts of audio that has been output by decoder
1837 double a_pts = sh_audio->pts;
1838 if (a_pts != MP_NOPTS_VALUE)
1839 // Good, decoder supports new way of calculating audio pts.
1840 // sh_audio->pts is the timestamp of the latest input packet with
1841 // known pts that the decoder has decoded. sh_audio->pts_bytes is
1842 // the amount of bytes the decoder has written after that timestamp.
1843 a_pts += sh_audio->pts_bytes / (double) sh_audio->o_bps;
1844 else {
1845 // Decoder doesn't support new way of calculating pts (or we're
1846 // being called before it has decoded anything with known timestamp).
1847 // Use the old method of audio pts calculation: take the timestamp
1848 // of last packet with known pts the decoder has read data from,
1849 // and add amount of bytes read after the beginning of that packet
1850 // divided by input bps. This will be inaccurate if the input/output
1851 // ratio is not constant for every audio packet or if it is constant
1852 // but not accurately known in sh_audio->i_bps.
1854 a_pts = d_audio->pts;
1855 // ds_tell_pts returns bytes read after last timestamp from
1856 // demuxing layer, decoder might use sh_audio->a_in_buffer for bytes
1857 // it has read but not decoded
1858 if (sh_audio->i_bps)
1859 a_pts += (ds_tell_pts(d_audio) - sh_audio->a_in_buffer_len) /
1860 (double)sh_audio->i_bps;
1862 // Now a_pts hopefully holds the pts for end of audio from decoder.
1863 // Substract data in buffers between decoder and audio out.
1865 // Decoded but not filtered
1866 a_pts -= sh_audio->a_buffer_len / (double)sh_audio->o_bps;
1868 // Data buffered in audio filters, measured in bytes of "missing" output
1869 double buffered_output = af_calc_delay(sh_audio->afilter);
1871 // Data that was ready for ao but was buffered because ao didn't fully
1872 // accept everything to internal buffers yet
1873 buffered_output += mpctx->ao->buffer.len;
1875 // Filters divide audio length by playback_speed, so multiply by it
1876 // to get the length in original units without speedup or slowdown
1877 a_pts -= buffered_output * mpctx->opts.playback_speed / mpctx->ao->bps;
1879 return a_pts + mpctx->video_offset;
1882 // Return pts value corresponding to currently playing audio.
1883 double playing_audio_pts(struct MPContext *mpctx)
1885 return written_audio_pts(mpctx) - mpctx->opts.playback_speed *
1886 ao_get_delay(mpctx->ao);
1889 static bool is_av_sub(int type)
1891 return type == 'b' || type == 'p' || type == 'x';
1894 void update_subtitles(struct MPContext *mpctx, double refpts,
1895 double sub_offset, bool reset)
1897 struct MPOpts *opts = &mpctx->opts;
1898 struct sh_video *sh_video = mpctx->sh_video;
1899 struct demux_stream *d_sub = mpctx->d_sub;
1900 double curpts = refpts + sub_delay;
1901 unsigned char *packet=NULL;
1902 int len;
1903 struct sh_sub *sh_sub = d_sub->sh;
1904 int type = sh_sub ? sh_sub->type : 'v';
1905 static subtitle subs;
1906 if (reset) {
1907 if (sh_sub)
1908 sub_reset(sh_sub, mpctx->osd);
1909 sub_clear_text(&subs, MP_NOPTS_VALUE);
1910 if (vo_sub)
1911 set_osd_subtitle(mpctx, NULL);
1912 if (vo_spudec) {
1913 spudec_reset(vo_spudec);
1914 vo_osd_changed(OSDTYPE_SPU);
1916 #ifdef CONFIG_FFMPEG
1917 if (is_av_sub(type))
1918 reset_avsub(sh_sub);
1919 #endif
1920 return;
1922 // find sub
1923 if (mpctx->subdata) {
1924 if (sub_fps==0) sub_fps = sh_video ? sh_video->fps : 25;
1925 current_module = "find_sub";
1926 find_sub(mpctx, mpctx->subdata, curpts *
1927 (mpctx->subdata->sub_uses_time ? 100. : sub_fps));
1928 if (vo_sub)
1929 mpctx->vo_sub_last = vo_sub;
1932 // DVD sub:
1933 if (vobsub_id >= 0 || type == 'v') {
1934 int timestamp;
1935 current_module = "spudec";
1936 /* Get a sub packet from the DVD or a vobsub */
1937 while(1) {
1938 // Vobsub
1939 len = 0;
1940 if (vo_vobsub) {
1941 if (curpts >= 0) {
1942 len = vobsub_get_packet(vo_vobsub, curpts,
1943 (void**)&packet, &timestamp);
1944 if (len > 0) {
1945 mp_dbg(MSGT_CPLAYER,MSGL_V,"\rVOB sub: len=%d v_pts=%5.3f v_timer=%5.3f sub=%5.3f ts=%d \n",len,refpts,sh_video->timer,timestamp / 90000.0,timestamp);
1948 } else {
1949 // DVD sub
1950 len = ds_get_packet_sub(d_sub, (unsigned char**)&packet);
1951 if (len > 0) {
1952 // XXX This is wrong, sh_video->pts can be arbitrarily
1953 // much behind demuxing position. Unfortunately using
1954 // d_video->pts which would have been the simplest
1955 // improvement doesn't work because mpeg specific hacks
1956 // in video.c set d_video->pts to 0.
1957 float x = d_sub->pts - refpts;
1958 if (x > -20 && x < 20) // prevent missing subs on pts reset
1959 timestamp = 90000*d_sub->pts;
1960 else timestamp = 90000*curpts;
1961 mp_dbg(MSGT_CPLAYER, MSGL_V, "\rDVD sub: len=%d "
1962 "v_pts=%5.3f s_pts=%5.3f ts=%d \n", len,
1963 refpts, d_sub->pts, timestamp);
1966 if (len<=0 || !packet) break;
1967 // create it only here, since with some broken demuxers we might
1968 // type = v but no DVD sub and we currently do not change the
1969 // "original frame size" ever after init, leading to wrong-sized
1970 // PGS subtitles.
1971 if (!vo_spudec)
1972 vo_spudec = spudec_new(NULL);
1973 if (vo_vobsub || timestamp >= 0)
1974 spudec_assemble(vo_spudec, packet, len, timestamp);
1976 } else if (is_text_sub(type) || is_av_sub(type) || type == 'd') {
1977 if (type == 'd' && !d_sub->demuxer->teletext) {
1978 tt_stream_props tsp = {0};
1979 void *ptr = &tsp;
1980 if (teletext_control(NULL, TV_VBI_CONTROL_START, &ptr) == VBI_CONTROL_TRUE)
1981 d_sub->demuxer->teletext = ptr;
1983 if (d_sub->non_interleaved)
1984 ds_get_next_pts(d_sub);
1986 while (d_sub->first) {
1987 double subpts = ds_get_next_pts(d_sub) + sub_offset;
1988 if (subpts > curpts) {
1989 // Libass handled subs can be fed to it in advance
1990 if (!opts->ass_enabled || !is_text_sub(type))
1991 break;
1992 // Try to avoid demuxing whole file at once
1993 if (d_sub->non_interleaved && subpts > curpts + 1)
1994 break;
1996 double duration = d_sub->first->duration;
1997 len = ds_get_packet_sub(d_sub, &packet);
1998 if (is_av_sub(type)) {
1999 #ifdef CONFIG_FFMPEG
2000 int ret = decode_avsub(sh_sub, packet, len, subpts, duration);
2001 if (ret < 0)
2002 mp_msg(MSGT_SPUDEC, MSGL_WARN, "lavc failed decoding "
2003 "subtitle\n");
2004 #endif
2005 continue;
2007 if (type == 'm') {
2008 if (len < 2) continue;
2009 len = FFMIN(len - 2, AV_RB16(packet));
2010 packet += 2;
2012 if (type == 'd') {
2013 if (d_sub->demuxer->teletext) {
2014 uint8_t *p = packet;
2015 p++;
2016 len--;
2017 while (len >= 46) {
2018 int sublen = p[1];
2019 if (p[0] == 2 || p[0] == 3)
2020 teletext_control(d_sub->demuxer->teletext,
2021 TV_VBI_CONTROL_DECODE_DVB, p + 2);
2022 p += sublen + 2;
2023 len -= sublen + 2;
2026 continue;
2028 if (sh_sub && sh_sub->active) {
2029 sub_decode(sh_sub, mpctx->osd, packet, len, subpts, duration);
2030 continue;
2032 if (subpts != MP_NOPTS_VALUE) {
2033 if (duration < 0)
2034 sub_clear_text(&subs, MP_NOPTS_VALUE);
2035 if (type == 'a') { // ssa/ass subs without libass => convert to plaintext
2036 int i;
2037 unsigned char* p = packet;
2038 for (i=0; i < 8 && *p != '\0'; p++)
2039 if (*p == ',')
2040 i++;
2041 if (*p == '\0') /* Broken line? */
2042 continue;
2043 len -= p - packet;
2044 packet = p;
2046 double endpts = MP_NOPTS_VALUE;
2047 if (subpts != MP_NOPTS_VALUE && duration >= 0)
2048 endpts = subpts + duration;
2049 sub_add_text(&subs, packet, len, endpts);
2050 set_osd_subtitle(mpctx, &subs);
2052 if (d_sub->non_interleaved)
2053 ds_get_next_pts(d_sub);
2055 if (!opts->ass_enabled)
2056 if (sub_clear_text(&subs, curpts))
2057 set_osd_subtitle(mpctx, &subs);
2059 if (vo_spudec) {
2060 spudec_heartbeat(vo_spudec, 90000*curpts);
2061 if (spudec_changed(vo_spudec))
2062 vo_osd_changed(OSDTYPE_SPU);
2065 current_module=NULL;
2068 static void update_teletext(sh_video_t *sh_video, demuxer_t *demuxer, int reset)
2070 int page_changed;
2072 if (!demuxer->teletext)
2073 return;
2075 //Also forcing page update when such ioctl is not supported or call error occured
2076 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_IS_CHANGED,&page_changed)!=VBI_CONTROL_TRUE)
2077 page_changed=1;
2079 if(!page_changed)
2080 return;
2082 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_GET_VBIPAGE,&vo_osd_teletext_page)!=VBI_CONTROL_TRUE)
2083 vo_osd_teletext_page=NULL;
2084 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_GET_HALF_PAGE,&vo_osd_teletext_half)!=VBI_CONTROL_TRUE)
2085 vo_osd_teletext_half=0;
2086 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_GET_MODE,&vo_osd_teletext_mode)!=VBI_CONTROL_TRUE)
2087 vo_osd_teletext_mode=0;
2088 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_GET_FORMAT,&vo_osd_teletext_format)!=VBI_CONTROL_TRUE)
2089 vo_osd_teletext_format=0;
2090 vo_osd_changed(OSDTYPE_TELETEXT);
2092 teletext_control(demuxer->teletext,TV_VBI_CONTROL_MARK_UNCHANGED,NULL);
2095 static int check_framedrop(struct MPContext *mpctx, double frame_time) {
2096 struct MPOpts *opts = &mpctx->opts;
2097 // check for frame-drop:
2098 current_module = "check_framedrop";
2099 if (mpctx->sh_audio && !mpctx->ao->untimed && !mpctx->d_audio->eof) {
2100 static int dropped_frames;
2101 float delay = opts->playback_speed * ao_get_delay(mpctx->ao);
2102 float d = delay-mpctx->delay;
2103 ++total_frame_cnt;
2104 // we should avoid dropping too many frames in sequence unless we
2105 // are too late. and we allow 100ms A-V delay here:
2106 if (d < -dropped_frames*frame_time-0.100 && !mpctx->paused
2107 && !mpctx->restart_playback) {
2108 ++drop_frame_cnt;
2109 ++dropped_frames;
2110 return frame_dropping;
2111 } else
2112 dropped_frames = 0;
2114 return 0;
2118 #ifdef HAVE_RTC
2119 int rtc_fd = -1;
2120 #endif
2122 static float timing_sleep(struct MPContext *mpctx, float time_frame)
2124 #ifdef HAVE_RTC
2125 if (rtc_fd >= 0){
2126 // -------- RTC -----------
2127 current_module="sleep_rtc";
2128 while (time_frame > 0.000) {
2129 unsigned long rtc_ts;
2130 if (read(rtc_fd, &rtc_ts, sizeof(rtc_ts)) <= 0)
2131 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC read error: %s\n", strerror(errno));
2132 time_frame -= get_relative_time(mpctx);
2134 } else
2135 #endif
2137 // assume kernel HZ=100 for softsleep, works with larger HZ but with
2138 // unnecessarily high CPU usage
2139 struct MPOpts *opts = &mpctx->opts;
2140 float margin = opts->softsleep ? 0.011 : 0;
2141 current_module = "sleep_timer";
2142 while (time_frame > margin) {
2143 usec_sleep(1000000 * (time_frame - margin));
2144 time_frame -= get_relative_time(mpctx);
2146 if (opts->softsleep){
2147 current_module = "sleep_soft";
2148 if (time_frame < 0)
2149 mp_tmsg(MSGT_AVSYNC, MSGL_WARN, "Warning! Softsleep underflow!\n");
2150 while (time_frame > 0)
2151 time_frame -= get_relative_time(mpctx); // burn the CPU
2154 return time_frame;
2157 static int select_subtitle(MPContext *mpctx)
2159 struct MPOpts *opts = &mpctx->opts;
2160 // find the best sub to use
2161 int id;
2162 int found = 0;
2163 mpctx->global_sub_pos = -1; // no subs by default
2164 if (vobsub_id >= 0) {
2165 // if user asks for a vobsub id, use that first.
2166 id = vobsub_id;
2167 found = mp_property_do("sub_vob", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
2170 if (!found && opts->sub_id >= 0) {
2171 // if user asks for a dvd sub id, use that next.
2172 id = opts->sub_id;
2173 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
2176 if (!found) {
2177 // if there are text subs to use, use those. (autosubs come last here)
2178 id = 0;
2179 found = mp_property_do("sub_file", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
2182 if (!found && opts->sub_id == -1) {
2183 // finally select subs by language and container hints
2184 if (opts->sub_id == -1)
2185 opts->sub_id =
2186 demuxer_sub_track_by_lang_and_default(mpctx->d_sub->demuxer,
2187 opts->sub_lang);
2188 if (opts->sub_id >= 0) {
2189 id = opts->sub_id;
2190 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
2193 return found;
2196 #ifdef CONFIG_DVDNAV
2197 #ifndef FF_B_TYPE
2198 #define FF_B_TYPE 3
2199 #endif
2200 /// store decoded video image
2201 static mp_image_t * mp_dvdnav_copy_mpi(mp_image_t *to_mpi,
2202 mp_image_t *from_mpi) {
2203 mp_image_t *mpi;
2205 /// Do not store B-frames
2206 if (from_mpi->pict_type == FF_B_TYPE)
2207 return to_mpi;
2209 if (to_mpi &&
2210 to_mpi->w == from_mpi->w &&
2211 to_mpi->h == from_mpi->h &&
2212 to_mpi->imgfmt == from_mpi->imgfmt)
2213 mpi = to_mpi;
2214 else {
2215 if (to_mpi)
2216 free_mp_image(to_mpi);
2217 if (from_mpi->w == 0 || from_mpi->h == 0)
2218 return NULL;
2219 mpi = alloc_mpi(from_mpi->w,from_mpi->h,from_mpi->imgfmt);
2222 copy_mpi(mpi,from_mpi);
2223 return mpi;
2226 static void mp_dvdnav_reset_stream (MPContext *ctx) {
2227 struct MPOpts *opts = &ctx->opts;
2228 if (ctx->sh_video) {
2229 /// clear video pts
2230 ctx->d_video->pts = 0.0f;
2231 ctx->sh_video->pts = 0.0f;
2232 ctx->sh_video->i_pts = 0.0f;
2233 ctx->sh_video->last_pts = 0.0f;
2234 ctx->sh_video->num_buffered_pts = 0;
2235 ctx->sh_video->num_frames = 0;
2236 ctx->sh_video->num_frames_decoded = 0;
2237 ctx->sh_video->timer = 0.0f;
2238 ctx->sh_video->stream_delay = 0.0f;
2239 ctx->sh_video->timer = 0;
2240 ctx->demuxer->stream_pts = MP_NOPTS_VALUE;
2243 if (ctx->sh_audio) {
2244 /// free audio packets and reset
2245 ds_free_packs(ctx->d_audio);
2246 audio_delay -= ctx->sh_audio->stream_delay;
2247 ctx->delay =- audio_delay;
2248 ao_reset(ctx->ao);
2249 resync_audio_stream(ctx->sh_audio);
2252 audio_delay = 0.0f;
2253 ctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(ctx->stream);
2254 if (opts->sub_lang && opts->sub_id == dvdsub_lang_id) {
2255 dvdsub_lang_id = mp_dvdnav_sid_from_lang(ctx->stream, opts->sub_lang);
2256 if (dvdsub_lang_id != opts->sub_id) {
2257 opts->sub_id = dvdsub_lang_id;
2258 select_subtitle(ctx);
2262 /// clear all EOF related flags
2263 ctx->d_video->eof = ctx->d_audio->eof = ctx->stream->eof = 0;
2266 /// Restore last decoded DVDNAV (still frame)
2267 static mp_image_t *mp_dvdnav_restore_smpi(struct MPContext *mpctx,
2268 int *in_size,
2269 unsigned char **start,
2270 mp_image_t *decoded_frame)
2272 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2273 return decoded_frame;
2275 /// a change occured in dvdnav stream
2276 if (mp_dvdnav_cell_has_changed(mpctx->stream,0)) {
2277 mp_dvdnav_read_wait(mpctx->stream, 1, 1);
2278 mp_dvdnav_context_free(mpctx);
2279 mp_dvdnav_reset_stream(mpctx);
2280 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
2281 mp_dvdnav_cell_has_changed(mpctx->stream,1);
2284 if (*in_size < 0) {
2285 float len;
2287 /// Display still frame, if any
2288 if (mpctx->nav_smpi && !mpctx->nav_buffer)
2289 decoded_frame = mpctx->nav_smpi;
2291 /// increment video frame : continue playing after still frame
2292 len = get_time_length(mpctx);
2293 if (mpctx->sh_video->pts >= len &&
2294 mpctx->sh_video->pts > 0.0 && len > 0.0) {
2295 mp_dvdnav_skip_still(mpctx->stream);
2296 mp_dvdnav_skip_wait(mpctx->stream);
2298 mpctx->sh_video->pts += 1 / mpctx->sh_video->fps;
2300 if (mpctx->nav_buffer) {
2301 *start = mpctx->nav_start;
2302 *in_size = mpctx->nav_in_size;
2303 if (mpctx->nav_start)
2304 memcpy(*start,mpctx->nav_buffer,mpctx->nav_in_size);
2308 return decoded_frame;
2311 /// Save last decoded DVDNAV (still frame)
2312 static void mp_dvdnav_save_smpi(struct MPContext *mpctx, int in_size,
2313 unsigned char *start,
2314 mp_image_t *decoded_frame)
2316 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2317 return;
2319 free(mpctx->nav_buffer);
2321 mpctx->nav_buffer = malloc(in_size);
2322 mpctx->nav_start = start;
2323 mpctx->nav_in_size = mpctx->nav_buffer ? in_size : -1;
2324 if (mpctx->nav_buffer)
2325 memcpy(mpctx->nav_buffer,start,in_size);
2327 if (decoded_frame && mpctx->nav_smpi != decoded_frame)
2328 mpctx->nav_smpi = mp_dvdnav_copy_mpi(mpctx->nav_smpi,decoded_frame);
2330 #endif /* CONFIG_DVDNAV */
2332 /* Modify video timing to match the audio timeline. There are two main
2333 * reasons this is needed. First, video and audio can start from different
2334 * positions at beginning of file or after a seek (MPlayer starts both
2335 * immediately even if they have different pts). Second, the file can have
2336 * audio timestamps that are inconsistent with the duration of the audio
2337 * packets, for example two consecutive timestamp values differing by
2338 * one second but only a packet with enough samples for half a second
2339 * of playback between them.
2341 static void adjust_sync(struct MPContext *mpctx, double frame_time)
2343 current_module = "av_sync";
2345 if (!mpctx->sh_audio || mpctx->syncing_audio)
2346 return;
2348 double a_pts = written_audio_pts(mpctx) - mpctx->delay;
2349 double v_pts = mpctx->sh_video->pts;
2350 double av_delay = a_pts - v_pts;
2351 // Try to sync vo_flip() so it will *finish* at given time
2352 av_delay += mpctx->last_vo_flip_duration;
2353 av_delay -= audio_delay; // This much pts difference is desired
2355 double change = av_delay * 0.1;
2356 double max_change = default_max_pts_correction >= 0 ?
2357 default_max_pts_correction : frame_time * 0.1;
2358 if (change < -max_change)
2359 change = -max_change;
2360 else if (change > max_change)
2361 change = max_change;
2362 mpctx->delay += change;
2363 mpctx->total_avsync_change += change;
2366 #define ASYNC_PLAY_DONE -3
2367 static int audio_start_sync(struct MPContext *mpctx, int playsize)
2369 struct ao *ao = mpctx->ao;
2370 struct MPOpts *opts = &mpctx->opts;
2371 sh_audio_t * const sh_audio = mpctx->sh_audio;
2372 int res;
2374 // Timing info may not be set without
2375 res = decode_audio(sh_audio, &ao->buffer, 1);
2376 if (res < 0)
2377 return res;
2379 int bytes;
2380 bool did_retry = false;
2381 while (1) {
2382 double written_pts = written_audio_pts(mpctx);
2383 double ptsdiff = written_pts - mpctx->video_pts - mpctx->delay
2384 - audio_delay;
2385 bytes = ptsdiff * ao->bps / mpctx->opts.playback_speed;
2386 bytes -= bytes % (ao->channels * af_fmt2bits(ao->format) / 8);
2388 // ogg demuxers give packets without timing
2389 if (written_pts <= 1 && sh_audio->pts == MP_NOPTS_VALUE) {
2390 if (!did_retry) {
2391 // Try to read more data to see packets that have pts
2392 int res = decode_audio(sh_audio, &ao->buffer, ao->bps);
2393 if (res < 0)
2394 return res;
2395 did_retry = true;
2396 continue;
2398 bytes = 0;
2401 if (fabs(ptsdiff) > 300) // pts reset or just broken?
2402 bytes = 0;
2404 if (bytes > 0)
2405 break;
2407 mpctx->syncing_audio = false;
2408 int a = FFMIN(-bytes, FFMAX(playsize, 20000));
2409 int res = decode_audio(sh_audio, &ao->buffer, a);
2410 bytes += ao->buffer.len;
2411 if (bytes >= 0) {
2412 memmove(ao->buffer.start,
2413 ao->buffer.start + ao->buffer.len - bytes, bytes);
2414 ao->buffer.len = bytes;
2415 if (res < 0)
2416 return res;
2417 return decode_audio(sh_audio, &ao->buffer, playsize);
2419 ao->buffer.len = 0;
2420 if (res < 0)
2421 return res;
2423 int fillbyte = 0;
2424 if ((ao->format & AF_FORMAT_SIGN_MASK) == AF_FORMAT_US)
2425 fillbyte = 0x80;
2426 if (bytes >= playsize) {
2427 /* This case could fall back to the one below with
2428 * bytes = playsize, but then silence would keep accumulating
2429 * in a_out_buffer if the AO accepts less data than it asks for
2430 * in playsize. */
2431 char *p = malloc(playsize);
2432 memset(p, fillbyte, playsize);
2433 playsize = ao_play(ao, p, playsize, 0);
2434 free(p);
2435 mpctx->delay += opts->playback_speed*playsize/(double)ao->bps;
2436 return ASYNC_PLAY_DONE;
2438 mpctx->syncing_audio = false;
2439 decode_audio_prepend_bytes(&ao->buffer, bytes, fillbyte);
2440 return decode_audio(sh_audio, &ao->buffer, playsize);
2443 static int fill_audio_out_buffers(struct MPContext *mpctx)
2445 struct MPOpts *opts = &mpctx->opts;
2446 struct ao *ao = mpctx->ao;
2447 unsigned int t;
2448 double tt;
2449 int playsize;
2450 int playflags=0;
2451 bool audio_eof = false;
2452 bool partial_fill = false;
2453 sh_audio_t * const sh_audio = mpctx->sh_audio;
2454 bool modifiable_audio_format = !(ao->format & AF_FORMAT_SPECIAL_MASK);
2455 int unitsize = ao->channels * af_fmt2bits(ao->format) / 8;
2457 current_module="play_audio";
2459 if (ao->untimed && mpctx->sh_video && mpctx->delay > 0)
2460 return 0;
2462 // all the current uses of ao->pts seem to be in aos that handle
2463 // sync completely wrong; there should be no need to use ao->pts
2464 // in get_space()
2465 ao->pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2466 playsize = ao_get_space(ao);
2468 // Fill buffer if needed:
2469 current_module="decode_audio";
2470 t = GetTimer();
2472 if (!opts->initial_audio_sync || !modifiable_audio_format)
2473 mpctx->syncing_audio = false;
2475 int res;
2476 if (mpctx->syncing_audio && mpctx->sh_video)
2477 res = audio_start_sync(mpctx, playsize);
2478 else
2479 res = decode_audio(sh_audio, &ao->buffer, playsize);
2480 if (res < 0) { // EOF, error or format change
2481 if (res == -2) {
2482 /* The format change isn't handled too gracefully. A more precise
2483 * implementation would require draining buffered old-format audio
2484 * while displaying video, then doing the output format switch.
2486 uninit_player(mpctx, INITIALIZED_AO);
2487 reinit_audio_chain(mpctx);
2488 return -1;
2489 } else if (res == ASYNC_PLAY_DONE)
2490 return 0;
2491 else if (mpctx->d_audio->eof)
2492 audio_eof = true;
2494 t = GetTimer() - t;
2495 tt = t*0.000001f; audio_time_usage+=tt;
2496 if (mpctx->timeline && modifiable_audio_format) {
2497 double endpts = mpctx->timeline[mpctx->timeline_part + 1].start;
2498 double bytes = (endpts - written_audio_pts(mpctx) + audio_delay)
2499 * ao->bps / opts->playback_speed;
2500 if (playsize > bytes) {
2501 playsize = FFMAX(bytes, 0);
2502 playflags |= AOPLAY_FINAL_CHUNK;
2503 audio_eof = true;
2504 partial_fill = true;
2508 assert(ao->buffer.len % unitsize == 0);
2509 if (playsize > ao->buffer.len) {
2510 partial_fill = true;
2511 playsize = ao->buffer.len;
2512 if (audio_eof)
2513 playflags |= AOPLAY_FINAL_CHUNK;
2515 playsize -= playsize % unitsize;
2516 if (!playsize)
2517 return partial_fill && audio_eof ? -2 : -partial_fill;
2519 // play audio:
2520 current_module="play_audio";
2522 // Is this pts value actually useful for the aos that access it?
2523 // They're obviously badly broken in the way they handle av sync;
2524 // would not having access to this make them more broken?
2525 ao->pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2526 int played = ao_play(ao, ao->buffer.start, playsize, playflags);
2527 assert(played % unitsize == 0);
2528 ao->buffer_playable_size = playsize - played;
2530 if (played > 0) {
2531 ao->buffer.len -= played;
2532 memmove(ao->buffer.start, ao->buffer.start + played, ao->buffer.len);
2533 mpctx->delay += opts->playback_speed * played / ao->bps;
2534 } else if (audio_eof && ao_get_delay(ao) < .04) {
2535 // Sanity check to avoid hanging in case current ao doesn't output
2536 // partial chunks and doesn't check for AOPLAY_FINAL_CHUNK
2537 return -2;
2540 return -partial_fill;
2543 static int sleep_until_near_frame(struct MPContext *mpctx, float *time_frame,
2544 bool sync_to_audio, float *aq_sleep_time)
2546 struct MPOpts *opts = &mpctx->opts;
2547 double audio_limit = 2;
2548 current_module="calc_sleep_time";
2550 if (mpctx->restart_playback)
2551 return 0;
2553 *time_frame -= get_relative_time(mpctx); // reset timer
2555 if (sync_to_audio) {
2556 float delay = ao_get_delay(mpctx->ao);
2557 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "delay=%f\n", delay);
2559 if (opts->autosync) {
2561 * Adjust this raw delay value by calculating the expected
2562 * delay for this frame and generating a new value which is
2563 * weighted between the two. The higher autosync is, the
2564 * closer to the delay value gets to that which "-nosound"
2565 * would have used, and the longer it will take for A/V
2566 * sync to settle at the right value (but it eventually will.)
2567 * This settling time is very short for values below 100.
2569 float predicted = mpctx->delay / opts->playback_speed + *time_frame;
2570 float difference = delay - predicted;
2571 delay = predicted + difference / (float)opts->autosync;
2574 *time_frame = delay - mpctx->delay / opts->playback_speed;
2576 // delay = amount of audio buffered in soundcard/driver
2577 delay = FFMIN(delay, 0.5);
2578 delay = FFMAX(delay, 0.1);
2579 audio_limit = delay;
2580 } else {
2581 // If we're lagging more than 200 ms behind the right playback rate,
2582 // don't try to "catch up".
2583 // If benchmark is set always output frames as fast as possible
2584 // without sleeping.
2585 if (*time_frame < -0.2 || opts->benchmark)
2586 *time_frame = 0;
2589 double t = *time_frame - mpctx->video_out->flip_queue_offset;
2591 if (t <= 0.05)
2592 return 0;
2594 t -= 0.05;
2595 if (t > audio_limit * 0.6)
2596 t = audio_limit * 0.5;
2597 *aq_sleep_time += t;
2598 mp_input_get_cmd(mpctx->input, t * 1000 + 1, 1);
2599 return 1;
2602 int reinit_video_chain(struct MPContext *mpctx)
2604 struct MPOpts *opts = &mpctx->opts;
2605 sh_video_t * const sh_video = mpctx->sh_video;
2606 if (!sh_video)
2607 return 0;
2608 double ar=-1.0;
2609 //================== Init VIDEO (codec & libvo) ==========================
2610 if (!opts->fixed_vo || !(mpctx->initialized_flags & INITIALIZED_VO)) {
2611 current_module="preinit_libvo";
2613 //shouldn't we set dvideo->id=-2 when we fail?
2614 //if((mpctx->video_out->preinit(vo_subdevice))!=0){
2615 if(!(mpctx->video_out=init_best_video_out(opts, mpctx->x11_state, mpctx->key_fifo, mpctx->input))){
2616 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Error opening/initializing the selected video_out (-vo) device.\n");
2617 goto err_out;
2619 mpctx->initialized_flags|=INITIALIZED_VO;
2622 if(stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_ASPECT_RATIO, &ar) != STREAM_UNSUPPORTED)
2623 mpctx->sh_video->stream_aspect = ar;
2624 current_module="init_video_filters";
2626 char* vf_arg[] = { "_oldargs_", (char*)mpctx->video_out , NULL };
2627 sh_video->vfilter = vf_open_filter(opts, NULL,"vo",vf_arg);
2629 #ifdef CONFIG_MENU
2630 if(use_menu) {
2631 char* vf_arg[] = { "_oldargs_", menu_root, NULL };
2632 vf_menu = vf_open_plugin(opts,libmenu_vfs,sh_video->vfilter,"menu",vf_arg);
2633 if(!vf_menu) {
2634 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Can't open libmenu video filter with root menu %s.\n",menu_root);
2635 use_menu = 0;
2638 if(vf_menu)
2639 sh_video->vfilter = vf_menu;
2640 #endif
2642 #ifdef CONFIG_ASS
2643 if(opts->ass_enabled) {
2644 int i;
2645 int insert = 1;
2646 if (opts->vf_settings)
2647 for (i = 0; opts->vf_settings[i].name; ++i)
2648 if (strcmp(opts->vf_settings[i].name, "ass") == 0) {
2649 insert = 0;
2650 break;
2652 if (insert) {
2653 extern vf_info_t vf_info_ass;
2654 const vf_info_t* libass_vfs[] = {&vf_info_ass, NULL};
2655 char* vf_arg[] = {"auto", "1", NULL};
2656 int retcode = 0;
2657 struct vf_instance *vf_ass = vf_open_plugin_noerr(opts, libass_vfs,
2658 sh_video->vfilter,
2659 "ass", vf_arg,
2660 &retcode);
2661 if (vf_ass)
2662 sh_video->vfilter = vf_ass;
2663 else if (retcode == -1) // vf_ass open() returns -1 if there's VO EOSD
2664 mp_msg(MSGT_CPLAYER, MSGL_V, "[ass] vf_ass not needed\n");
2665 else
2666 mp_msg(MSGT_CPLAYER,MSGL_ERR, "ASS: cannot add video filter\n");
2669 #endif
2671 sh_video->vfilter = append_filters(sh_video->vfilter, opts->vf_settings);
2673 #ifdef CONFIG_ASS
2674 if (opts->ass_enabled)
2675 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_INIT_EOSD, ass_library);
2676 #endif
2678 current_module="init_video_codec";
2680 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2681 init_best_video_codec(sh_video,video_codec_list,video_fm_list);
2682 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2684 if(!sh_video->initialized){
2685 if(!opts->fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
2686 goto err_out;
2689 mpctx->initialized_flags|=INITIALIZED_VCODEC;
2691 if (sh_video->codec)
2692 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODEC=%s\n", sh_video->codec->name);
2694 sh_video->last_pts = MP_NOPTS_VALUE;
2695 sh_video->num_buffered_pts = 0;
2696 sh_video->next_frame_time = 0;
2698 if (opts->auto_quality > 0) {
2699 // Auto quality option enabled
2700 output_quality=get_video_quality_max(sh_video);
2701 if (opts->auto_quality > output_quality)
2702 opts->auto_quality = output_quality;
2703 else
2704 output_quality = opts->auto_quality;
2705 mp_msg(MSGT_CPLAYER,MSGL_V,"AutoQ: setting quality to %d.\n",output_quality);
2706 set_video_quality(sh_video,output_quality);
2709 // ========== Init display (sh_video->disp_w*sh_video->disp_h/out_fmt) ============
2711 current_module="init_vo";
2713 return 1;
2715 err_out:
2716 mpctx->sh_video = mpctx->d_video->sh = NULL;
2717 return 0;
2720 static double update_video_nocorrect_pts(struct MPContext *mpctx)
2722 struct sh_video *sh_video = mpctx->sh_video;
2723 double frame_time = 0;
2724 struct vo *video_out = mpctx->video_out;
2725 while (1) {
2726 current_module = "filter_video";
2727 // In nocorrect-pts mode there is no way to properly time these frames
2728 if (vo_get_buffered_frame(video_out, 0) >= 0)
2729 break;
2730 if (vf_output_queued_frame(sh_video->vfilter))
2731 break;
2732 unsigned char *packet = NULL;
2733 frame_time = sh_video->next_frame_time;
2734 if (mpctx->restart_playback)
2735 frame_time = 0;
2736 int in_size = video_read_frame(sh_video, &sh_video->next_frame_time,
2737 &packet, force_fps);
2738 if (in_size < 0) {
2739 #ifdef CONFIG_DVDNAV
2740 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
2741 if (mp_dvdnav_is_eof(mpctx->stream))
2742 return -1;
2743 if (mpctx->d_video)
2744 mpctx->d_video->eof = 0;
2745 if (mpctx->d_audio)
2746 mpctx->d_audio->eof = 0;
2747 mpctx->stream->eof = 0;
2748 } else
2749 #endif
2750 return -1;
2752 if (in_size > max_framesize)
2753 max_framesize = in_size;
2754 sh_video->timer += frame_time;
2755 if (mpctx->sh_audio)
2756 mpctx->delay -= frame_time;
2757 // video_read_frame can change fps (e.g. for ASF video)
2758 vo_fps = sh_video->fps;
2759 int framedrop_type = check_framedrop(mpctx, frame_time);
2760 current_module = "decode video";
2762 void *decoded_frame;
2763 #ifdef CONFIG_DVDNAV
2764 decoded_frame = mp_dvdnav_restore_smpi(mpctx, &in_size, &packet, NULL);
2765 if (in_size >= 0 && !decoded_frame)
2766 #endif
2767 decoded_frame = decode_video(sh_video, packet, in_size, framedrop_type,
2768 sh_video->pts);
2769 #ifdef CONFIG_DVDNAV
2770 // Save last still frame for future display
2771 mp_dvdnav_save_smpi(mpctx, in_size, packet, decoded_frame);
2772 #endif
2773 if (decoded_frame) {
2774 current_module = "filter video";
2775 filter_video(sh_video, decoded_frame, sh_video->pts);
2777 break;
2779 return frame_time;
2782 static void determine_frame_pts(struct MPContext *mpctx)
2784 struct sh_video *sh_video = mpctx->sh_video;
2785 struct MPOpts *opts = &mpctx->opts;
2787 if (opts->user_pts_assoc_mode) {
2788 sh_video->pts_assoc_mode = opts->user_pts_assoc_mode;
2789 } else if (sh_video->pts_assoc_mode == 0) {
2790 if (mpctx->d_video->demuxer->timestamp_type == TIMESTAMP_TYPE_PTS
2791 && sh_video->codec_reordered_pts != MP_NOPTS_VALUE)
2792 sh_video->pts_assoc_mode = 1;
2793 else
2794 sh_video->pts_assoc_mode = 2;
2795 } else {
2796 int probcount1 = sh_video->num_reordered_pts_problems;
2797 int probcount2 = sh_video->num_sorted_pts_problems;
2798 if (sh_video->pts_assoc_mode == 2) {
2799 int tmp = probcount1;
2800 probcount1 = probcount2;
2801 probcount2 = tmp;
2803 if (probcount1 >= probcount2 * 1.5 + 2) {
2804 sh_video->pts_assoc_mode = 3 - sh_video->pts_assoc_mode;
2805 mp_msg(MSGT_CPLAYER, MSGL_V, "Switching to pts association mode "
2806 "%d.\n", sh_video->pts_assoc_mode);
2809 sh_video->pts = sh_video->pts_assoc_mode == 1 ?
2810 sh_video->codec_reordered_pts : sh_video->sorted_pts;
2813 static double update_video(struct MPContext *mpctx)
2815 struct sh_video *sh_video = mpctx->sh_video;
2816 struct vo *video_out = mpctx->video_out;
2817 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_SET_OSD_OBJ,
2818 mpctx->osd); // hack for vf_expand
2819 if (!mpctx->opts.correct_pts)
2820 return update_video_nocorrect_pts(mpctx);
2822 double pts;
2824 while (1) {
2825 current_module = "filter_video";
2826 if (!mpctx->hrseek_active
2827 && vo_get_buffered_frame(video_out, false) >= 0)
2828 break;
2829 // XXX Time used in this call is not counted in any performance
2830 // timer now
2831 if (vf_output_queued_frame(sh_video->vfilter))
2832 break;
2833 unsigned char *packet = NULL;
2834 int in_size = ds_get_packet_pts(mpctx->d_video, &packet, &pts);
2835 if (pts != MP_NOPTS_VALUE)
2836 pts += mpctx->video_offset;
2837 bool hit_eof = false;
2838 if (in_size < 0) {
2839 // try to extract last frames in case of decoder lag
2840 in_size = 0;
2841 pts = MP_NOPTS_VALUE;
2842 hit_eof = true;
2844 if (in_size > max_framesize)
2845 max_framesize = in_size;
2846 current_module = "decode video";
2847 if (pts >= mpctx->hrseek_pts - .005)
2848 mpctx->hrseek_framedrop = false;
2849 int framedrop_type = mpctx->hrseek_framedrop ? 1 :
2850 check_framedrop(mpctx, sh_video->frametime);
2851 void *decoded_frame = decode_video(sh_video, packet, in_size,
2852 framedrop_type, pts);
2853 if (decoded_frame) {
2854 determine_frame_pts(mpctx);
2855 current_module = "filter video";
2856 filter_video(sh_video, decoded_frame, sh_video->pts);
2857 } else if (hit_eof) {
2858 if (vo_get_buffered_frame(video_out, true) < 0)
2859 return -1;
2861 break;
2864 if (!video_out->frame_loaded)
2865 return 0;
2867 pts = video_out->next_pts;
2868 if (pts == MP_NOPTS_VALUE) {
2869 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Video pts after filters MISSING\n");
2870 // Try to use decoder pts from before filters
2871 pts = sh_video->pts;
2872 if (pts == MP_NOPTS_VALUE)
2873 pts = sh_video->last_pts;
2875 if (mpctx->hrseek_active && pts < mpctx->hrseek_pts - .005) {
2876 vo_skip_frame(video_out);
2877 return 0;
2879 mpctx->hrseek_active = false;
2880 sh_video->pts = pts;
2881 if (sh_video->last_pts == MP_NOPTS_VALUE)
2882 sh_video->last_pts = sh_video->pts;
2883 else if (sh_video->last_pts > sh_video->pts) {
2884 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Decreasing video pts: %f < %f\n",
2885 sh_video->pts, sh_video->last_pts);
2886 /* If the difference in pts is small treat it as jitter around the
2887 * right value (possibly caused by incorrect timestamp ordering) and
2888 * just show this frame immediately after the last one.
2889 * Treat bigger differences as timestamp resets and start counting
2890 * timing of later frames from the position of this one. */
2891 if (sh_video->last_pts - sh_video->pts > 0.5)
2892 sh_video->last_pts = sh_video->pts;
2893 else
2894 sh_video->pts = sh_video->last_pts;
2896 double frame_time = sh_video->pts - sh_video->last_pts;
2897 sh_video->last_pts = sh_video->pts;
2898 sh_video->timer += frame_time;
2899 if (mpctx->sh_audio)
2900 mpctx->delay -= frame_time;
2901 return frame_time;
2904 void pause_player(struct MPContext *mpctx)
2906 if (mpctx->paused)
2907 return;
2908 mpctx->paused = 1;
2909 mpctx->step_frames = 0;
2910 mpctx->time_frame -= get_relative_time(mpctx);
2912 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2913 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2915 if (mpctx->ao && mpctx->sh_audio)
2916 ao_pause(mpctx->ao); // pause audio, keep data if possible
2919 void unpause_player(struct MPContext *mpctx)
2921 if (!mpctx->paused)
2922 return;
2923 mpctx->paused = 0;
2925 if (mpctx->ao && mpctx->sh_audio)
2926 ao_resume(mpctx->ao);
2927 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok
2928 && !mpctx->step_frames)
2929 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL); // resume video
2930 (void)get_relative_time(mpctx); // ignore time that passed during pause
2933 void add_step_frame(struct MPContext *mpctx)
2935 mpctx->step_frames++;
2936 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2937 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2938 unpause_player(mpctx);
2941 static void pause_loop(struct MPContext *mpctx)
2943 struct MPOpts *opts = &mpctx->opts;
2944 mp_cmd_t* cmd;
2945 #ifdef CONFIG_STREAM_CACHE
2946 int old_cache_fill = stream_cache_size > 0 ?
2947 cache_fill_status(mpctx->stream) : 0;
2948 #endif
2949 if (!opts->quiet) {
2950 if (opts->term_osd && !mpctx->sh_video) {
2951 set_osd_tmsg(OSD_MSG_PAUSE, 1, 0, " ===== PAUSE =====");
2952 update_osd_msg(mpctx);
2953 } else
2954 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "\n%s\r",
2955 mp_gtext(" ===== PAUSE ====="));
2956 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_PAUSED\n");
2959 while ( (cmd = mp_input_get_cmd(mpctx->input, 20, 1)) == NULL
2960 || cmd->id == MP_CMD_SET_MOUSE_POS || cmd->pausing == 4) {
2961 if (cmd) {
2962 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
2963 run_command(mpctx, cmd);
2964 mp_cmd_free(cmd);
2965 continue;
2967 if (mpctx->sh_video && mpctx->video_out)
2968 vo_check_events(mpctx->video_out);
2969 #ifdef CONFIG_MENU
2970 if (vf_menu)
2971 vf_menu_pause_update(vf_menu);
2972 #endif
2973 usec_sleep(20000);
2974 update_osd_msg(mpctx);
2975 int hack = vo_osd_changed(0);
2976 vo_osd_changed(hack);
2977 if (hack)
2978 break;
2979 #ifdef CONFIG_STREAM_CACHE
2980 if (!opts->quiet && stream_cache_size > 0) {
2981 int new_cache_fill = cache_fill_status(mpctx->stream);
2982 if (new_cache_fill != old_cache_fill) {
2983 if (opts->term_osd && !mpctx->sh_video) {
2984 set_osd_tmsg(OSD_MSG_PAUSE, 1, 0, "%s %d%%",
2985 mp_gtext(" ===== PAUSE ====="),
2986 new_cache_fill);
2987 update_osd_msg(mpctx);
2988 } else
2989 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "%s %d%%\r",
2990 mp_gtext(" ===== PAUSE ====="),
2991 new_cache_fill);
2992 old_cache_fill = new_cache_fill;
2995 #endif
3000 // Find the right mute status and record position for new file position
3001 static void edl_seek_reset(MPContext *mpctx)
3003 mpctx->edl_muted = 0;
3004 next_edl_record = edl_records;
3006 while (next_edl_record) {
3007 if (next_edl_record->start_sec >= get_current_time(mpctx))
3008 break;
3010 if (next_edl_record->action == EDL_MUTE)
3011 mpctx->edl_muted = !mpctx->edl_muted;
3012 next_edl_record = next_edl_record->next;
3014 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
3015 mixer_mute(&mpctx->mixer);
3019 // Execute EDL command for the current position if one exists
3020 static void edl_update(MPContext *mpctx)
3022 if (!next_edl_record)
3023 return;
3025 if (!mpctx->sh_video) {
3026 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot use EDL without video, disabling.\n");
3027 free_edl(edl_records);
3028 next_edl_record = NULL;
3029 edl_records = NULL;
3030 return;
3033 if (get_current_time(mpctx) >= next_edl_record->start_sec) {
3034 if (next_edl_record->action == EDL_SKIP) {
3035 mpctx->osd_function = OSD_FFW;
3036 queue_seek(mpctx, MPSEEK_RELATIVE, next_edl_record->length_sec, 0);
3037 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_SKIP: start [%f], stop "
3038 "[%f], length [%f]\n", next_edl_record->start_sec,
3039 next_edl_record->stop_sec, next_edl_record->length_sec);
3041 else if (next_edl_record->action == EDL_MUTE) {
3042 mpctx->edl_muted = !mpctx->edl_muted;
3043 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
3044 mixer_mute(&mpctx->mixer);
3045 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_MUTE: [%f]\n",
3046 next_edl_record->start_sec );
3048 next_edl_record = next_edl_record->next;
3052 static void reinit_decoders(struct MPContext *mpctx)
3054 reinit_video_chain(mpctx);
3055 reinit_audio_chain(mpctx);
3056 mp_property_do("sub", M_PROPERTY_SET, &(int){mpctx->global_sub_pos}, mpctx);
3059 static void seek_reset(struct MPContext *mpctx, bool reset_ao)
3061 if (mpctx->sh_video) {
3062 current_module = "seek_video_reset";
3063 resync_video_stream(mpctx->sh_video);
3064 mpctx->sh_video->timer = 0;
3065 vo_seek_reset(mpctx->video_out);
3066 mpctx->sh_video->timer = 0;
3067 mpctx->sh_video->num_buffered_pts = 0;
3068 mpctx->sh_video->last_pts = MP_NOPTS_VALUE;
3069 mpctx->delay = 0;
3070 mpctx->time_frame = 0;
3071 mpctx->restart_playback = true;
3072 // Not all demuxers set d_video->pts during seek, so this value
3073 // (which is used by at least vobsub and edl code below) may
3074 // be completely wrong (probably 0).
3075 mpctx->sh_video->pts = mpctx->d_video->pts + mpctx->video_offset;
3076 mpctx->video_pts = mpctx->sh_video->pts;
3077 update_subtitles(mpctx, mpctx->sh_video->pts, mpctx->video_offset,
3078 true);
3079 update_teletext(mpctx->sh_video, mpctx->demuxer, 1);
3082 if (mpctx->sh_audio) {
3083 current_module = "seek_audio_reset";
3084 resync_audio_stream(mpctx->sh_audio);
3085 if (reset_ao)
3086 ao_reset(mpctx->ao);
3087 mpctx->ao->buffer.len = mpctx->ao->buffer_playable_size;
3088 mpctx->sh_audio->a_buffer_len = 0;
3089 if (!mpctx->sh_video)
3090 update_subtitles(mpctx, mpctx->sh_audio->pts,
3091 mpctx->video_offset, true);
3094 if (vo_vobsub && mpctx->sh_video) {
3095 current_module = "seek_vobsub_reset";
3096 vobsub_seek(vo_vobsub, mpctx->sh_video->pts);
3099 edl_seek_reset(mpctx);
3101 mpctx->hrseek_active = false;
3102 mpctx->hrseek_framedrop = false;
3103 mpctx->total_avsync_change = 0;
3104 audio_time_usage = 0; video_time_usage = 0; vout_time_usage = 0;
3105 drop_frame_cnt = 0;
3107 current_module = NULL;
3110 static bool timeline_set_part(struct MPContext *mpctx, int i)
3112 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
3113 struct timeline_part *n = mpctx->timeline + i;
3114 mpctx->timeline_part = i;
3115 mpctx->video_offset = n->start - n->source_start;
3116 if (n->source == p->source)
3117 return false;
3118 enum stop_play_reason orig_stop_play = mpctx->stop_play;
3119 if (!mpctx->sh_video && mpctx->stop_play == KEEP_PLAYING)
3120 mpctx->stop_play = AT_END_OF_FILE; // let audio uninit drain data
3121 uninit_player(mpctx, INITIALIZED_VCODEC | (mpctx->opts.fixed_vo ? 0 : INITIALIZED_VO) | (mpctx->opts.gapless_audio ? 0 : INITIALIZED_AO) | INITIALIZED_ACODEC | INITIALIZED_SUB);
3122 mpctx->stop_play = orig_stop_play;
3123 mpctx->demuxer = n->source->demuxer;
3124 mpctx->d_video = mpctx->demuxer->video;
3125 mpctx->d_audio = mpctx->demuxer->audio;
3126 mpctx->d_sub = mpctx->demuxer->sub;
3127 mpctx->sh_video = mpctx->d_video->sh;
3128 mpctx->sh_audio = mpctx->d_audio->sh;
3129 return true;
3132 // Given pts, switch playback to the corresponding part.
3133 // Return offset within that part.
3134 static double timeline_set_from_time(struct MPContext *mpctx, double pts,
3135 bool *need_reset)
3137 if (pts < 0)
3138 pts = 0;
3139 for (int i = 0; i < mpctx->num_timeline_parts; i++) {
3140 struct timeline_part *p = mpctx->timeline + i;
3141 if (pts < (p+1)->start) {
3142 *need_reset = timeline_set_part(mpctx, i);
3143 return pts - p->start + p->source_start;
3146 return -1;
3150 // return -1 if seek failed (non-seekable stream?), 0 otherwise
3151 static int seek(MPContext *mpctx, struct seek_params seek,
3152 bool timeline_fallthrough)
3154 struct MPOpts *opts = &mpctx->opts;
3156 current_module = "seek";
3157 if (mpctx->stop_play == AT_END_OF_FILE)
3158 mpctx->stop_play = KEEP_PLAYING;
3159 bool hr_seek = mpctx->demuxer->accurate_seek && opts->correct_pts;
3160 hr_seek &= seek.exact >= 0 && seek.type != MPSEEK_FACTOR;
3161 hr_seek &= opts->hr_seek == 0 && seek.type == MPSEEK_ABSOLUTE
3162 || opts->hr_seek > 0 || seek.exact > 0;
3163 if (seek.type == MPSEEK_FACTOR
3164 || seek.type == MPSEEK_ABSOLUTE
3165 && seek.amount < mpctx->last_chapter_pts
3166 || seek.amount < 0)
3167 mpctx->last_chapter_seek = -1;
3168 if (mpctx->timeline && seek.type == MPSEEK_FACTOR) {
3169 seek.amount *= mpctx->timeline[mpctx->num_timeline_parts].start;
3170 seek.type = MPSEEK_ABSOLUTE;
3172 if ((mpctx->demuxer->accurate_seek || mpctx->timeline)
3173 && seek.type == MPSEEK_RELATIVE) {
3174 seek.type = MPSEEK_ABSOLUTE;
3175 seek.direction = seek.amount > 0 ? 1 : -1;
3176 seek.amount += get_current_time(mpctx);
3179 /* At least the liba52 decoder wants to read from the input stream
3180 * during initialization, so reinit must be done after the demux_seek()
3181 * call that clears possible stream EOF. */
3182 bool need_reset = false;
3183 double demuxer_amount = seek.amount;
3184 if (mpctx->timeline) {
3185 demuxer_amount = timeline_set_from_time(mpctx, seek.amount,
3186 &need_reset);
3187 if (demuxer_amount == -1) {
3188 mpctx->stop_play = AT_END_OF_FILE;
3189 // Clear audio from current position
3190 if (mpctx->sh_audio) {
3191 ao_reset(mpctx->ao);
3192 mpctx->sh_audio->a_buffer_len = 0;
3194 return -1;
3197 int demuxer_style = 0;
3198 switch (seek.type) {
3199 case MPSEEK_FACTOR:
3200 demuxer_style |= SEEK_FACTOR; // fallthrough
3201 case MPSEEK_ABSOLUTE:
3202 demuxer_style |= SEEK_ABSOLUTE;
3204 if (hr_seek || seek.direction < 0)
3205 demuxer_style |= SEEK_BACKWARD;
3206 else if (seek.direction > 0)
3207 demuxer_style |= SEEK_FORWARD;
3209 int seekresult = demux_seek(mpctx->demuxer, demuxer_amount, audio_delay,
3210 demuxer_style);
3211 if (need_reset)
3212 reinit_decoders(mpctx);
3213 if (seekresult == 0)
3214 return -1;
3216 seek_reset(mpctx, !timeline_fallthrough);
3218 /* Use the target time as "current position" for further relative
3219 * seeks etc until a new video frame has been decoded */
3220 if (seek.type == MPSEEK_ABSOLUTE)
3221 mpctx->video_pts = seek.amount;
3223 if (hr_seek) {
3224 mpctx->hrseek_active = true;
3225 mpctx->hrseek_framedrop = true;
3226 mpctx->hrseek_pts = seek.amount;
3229 mpctx->start_timestamp = GetTimerMS();
3231 return 0;
3234 void queue_seek(struct MPContext *mpctx, enum seek_type type, double amount,
3235 int exact)
3237 struct seek_params *seek = &mpctx->seek;
3238 switch (type) {
3239 case MPSEEK_RELATIVE:
3240 if (seek->type == MPSEEK_FACTOR)
3241 return; // Well... not common enough to bother doing better
3242 seek->amount += amount;
3243 seek->exact = FFMAX(seek->exact, exact);
3244 if (seek->type == MPSEEK_NONE)
3245 seek->exact = exact;
3246 if (seek->type == MPSEEK_ABSOLUTE)
3247 return;
3248 if (seek->amount == 0) {
3249 *seek = (struct seek_params){0};
3250 return;
3252 seek->type = MPSEEK_RELATIVE;
3253 return;
3254 case MPSEEK_ABSOLUTE:
3255 case MPSEEK_FACTOR:
3256 *seek = (struct seek_params) {
3257 .type = type,
3258 .amount = amount,
3259 .exact = exact,
3261 return;
3262 case MPSEEK_NONE:
3263 *seek = (struct seek_params){0};
3264 return;
3266 abort();
3270 double get_time_length(struct MPContext *mpctx)
3272 if (mpctx->timeline)
3273 return mpctx->timeline[mpctx->num_timeline_parts].start;
3275 struct demuxer *demuxer = mpctx->demuxer;
3276 double get_time_ans;
3277 // <= 0 means DEMUXER_CTRL_NOTIMPL or DEMUXER_CTRL_DONTKNOW
3278 if (demux_control(demuxer, DEMUXER_CTRL_GET_TIME_LENGTH,
3279 (void *) &get_time_ans) > 0)
3280 return get_time_ans;
3282 struct sh_video *sh_video = mpctx->d_video->sh;
3283 struct sh_audio *sh_audio = mpctx->d_audio->sh;
3284 if (sh_video && sh_video->i_bps && sh_audio && sh_audio->i_bps)
3285 return (double) (demuxer->movi_end - demuxer->movi_start) /
3286 (sh_video->i_bps + sh_audio->i_bps);
3287 if (sh_video && sh_video->i_bps)
3288 return (double) (demuxer->movi_end - demuxer->movi_start) /
3289 sh_video->i_bps;
3290 if (sh_audio && sh_audio->i_bps)
3291 return (double) (demuxer->movi_end - demuxer->movi_start) /
3292 sh_audio->i_bps;
3293 return 0;
3296 /* If there are timestamps from stream level then use those (for example
3297 * DVDs can have consistent times there while the MPEG-level timestamps
3298 * reset). */
3299 double get_current_time(struct MPContext *mpctx)
3301 struct demuxer *demuxer = mpctx->demuxer;
3302 if (demuxer->stream_pts != MP_NOPTS_VALUE)
3303 return demuxer->stream_pts;
3304 struct sh_video *sh_video = demuxer->video->sh;
3305 if (sh_video)
3306 return mpctx->video_pts;
3307 return playing_audio_pts(mpctx);
3310 int get_percent_pos(struct MPContext *mpctx)
3312 struct demuxer *demuxer = mpctx->demuxer;
3313 int ans = 0;
3314 if (mpctx->timeline)
3315 ans = get_current_time(mpctx) * 100 /
3316 mpctx->timeline[mpctx->num_timeline_parts].start;
3317 else if (demux_control(demuxer, DEMUXER_CTRL_GET_PERCENT_POS, &ans) > 0)
3319 else {
3320 int len = (demuxer->movi_end - demuxer->movi_start) / 100;
3321 off_t pos = demuxer->filepos > 0 ?
3322 demuxer->filepos : stream_tell(demuxer->stream);
3323 if (len > 0)
3324 ans = (pos - demuxer->movi_start) / len;
3325 else
3326 ans = 0;
3328 if (ans < 0)
3329 ans = 0;
3330 if (ans > 100)
3331 ans = 100;
3332 return ans;
3335 // -2 is no chapters, -1 is before first chapter
3336 int get_current_chapter(struct MPContext *mpctx)
3338 double current_pts = get_current_time(mpctx);
3339 if (!mpctx->chapters)
3340 return FFMAX(mpctx->last_chapter_seek,
3341 demuxer_get_current_chapter(mpctx->demuxer, current_pts));
3343 int i;
3344 for (i = 1; i < mpctx->num_chapters; i++)
3345 if (current_pts < mpctx->chapters[i].start)
3346 break;
3347 return FFMAX(mpctx->last_chapter_seek, i - 1);
3350 // currently returns a string allocated with malloc, not talloc
3351 char *chapter_display_name(struct MPContext *mpctx, int chapter)
3353 if (!mpctx->chapters || !mpctx->sh_video)
3354 return demuxer_chapter_display_name(mpctx->demuxer, chapter);
3355 return talloc_strdup(NULL, mpctx->chapters[chapter].name);
3358 int seek_chapter(struct MPContext *mpctx, int chapter, double *seek_pts,
3359 char **chapter_name)
3361 mpctx->last_chapter_seek = -1;
3362 if (!mpctx->chapters || !mpctx->sh_video) {
3363 int res = demuxer_seek_chapter(mpctx->demuxer, chapter, seek_pts,
3364 chapter_name);
3365 if (res >= 0) {
3366 if (*seek_pts == -1)
3367 seek_reset(mpctx, true);
3368 else {
3369 mpctx->last_chapter_seek = res;
3370 mpctx->last_chapter_pts = *seek_pts;
3373 return res;
3376 if (chapter >= mpctx->num_chapters)
3377 return -1;
3378 if (chapter < 0)
3379 chapter = 0;
3380 *seek_pts = mpctx->chapters[chapter].start;
3381 mpctx->last_chapter_seek = chapter;
3382 mpctx->last_chapter_pts = *seek_pts;
3383 if (chapter_name)
3384 *chapter_name = talloc_strdup(NULL, mpctx->chapters[chapter].name);
3385 return chapter;
3389 static void run_playloop(struct MPContext *mpctx)
3391 struct MPOpts *opts = &mpctx->opts;
3392 float aq_sleep_time = 0;
3393 bool full_audio_buffers = false;
3395 if (opts->chapterrange[1] > 0) {
3396 int cur_chapter = get_current_chapter(mpctx);
3397 if (cur_chapter!=-1 && cur_chapter + 1 > opts->chapterrange[1])
3398 mpctx->stop_play = PT_NEXT_ENTRY;
3401 if (!mpctx->sh_audio && mpctx->d_audio->sh) {
3402 mpctx->sh_audio = mpctx->d_audio->sh;
3403 mpctx->sh_audio->ds = mpctx->d_audio;
3404 reinit_audio_chain(mpctx);
3407 /*========================== PLAY AUDIO ============================*/
3409 if (mpctx->sh_audio && !mpctx->paused
3410 && (!mpctx->restart_playback || !mpctx->sh_video)) {
3411 int status = fill_audio_out_buffers(mpctx);
3412 full_audio_buffers = status >= 0 && !mpctx->ao->untimed;
3413 if (status == -2)
3414 // at eof, all audio at least written to ao
3415 if (!mpctx->sh_video)
3416 mpctx->stop_play = AT_END_OF_FILE;
3420 if (!mpctx->sh_video) {
3421 mpctx->restart_playback = false;
3422 if (mpctx->step_frames) {
3423 mpctx->step_frames = 0;
3424 pause_player(mpctx);
3426 // handle audio-only case:
3427 double a_pos = 0, a_buf = 0;
3428 // sh_audio can be NULL due to video stream switching
3429 // TODO: handle this better
3430 if (mpctx->sh_audio) {
3431 a_buf = ao_get_delay(mpctx->ao);
3432 a_pos = written_audio_pts(mpctx) - mpctx->opts.playback_speed *
3433 a_buf;
3436 print_status(mpctx, a_pos, false);
3438 update_subtitles(mpctx, a_pos, mpctx->video_offset, false);
3439 update_osd_msg(mpctx);
3440 if (end_at.type == END_AT_TIME && end_at.pos < a_pos) {
3441 mpctx->stop_play = AT_END_OF_FILE;
3442 } else if (mpctx->timeline && mpctx->stop_play == AT_END_OF_FILE
3443 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts
3444 && mpctx->sh_audio) {
3445 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
3446 if (!opts->gapless_audio && p->source != (p+1)->source
3447 && a_buf > 0.05) {
3448 mpctx->stop_play = KEEP_PLAYING;
3449 mp_input_get_cmd(mpctx->input, (a_buf-.05) * 1000, true);
3450 } else {
3451 seek(mpctx, (struct seek_params){ .type = MPSEEK_ABSOLUTE,
3452 .amount = (p+1)->start },
3453 true);
3455 } else if (!mpctx->stop_play) {
3456 int sleep_time = 100;
3457 if (mpctx->sh_audio) {
3458 if (mpctx->ao->untimed)
3459 sleep_time = 0;
3460 else if (full_audio_buffers)
3461 sleep_time = FFMAX(20, a_buf * 1000 - 50);
3462 else
3463 sleep_time = 20;
3464 sleep_time = FFMIN(sleep_time, 100);
3466 mp_input_get_cmd(mpctx->input, sleep_time, true);
3468 } else {
3470 /*========================== PLAY VIDEO ============================*/
3472 vo_pts = mpctx->sh_video->timer * 90000.0;
3473 vo_fps = mpctx->sh_video->fps;
3475 bool blit_frame = mpctx->video_out->frame_loaded;
3476 if (!blit_frame || mpctx->hrseek_active) {
3477 double frame_time = update_video(mpctx);
3478 blit_frame = mpctx->video_out->frame_loaded;
3479 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "*** ftime=%5.3f ***\n", frame_time);
3480 if (mpctx->sh_video->vf_initialized < 0) {
3481 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
3482 "\nFATAL: Could not initialize video filters (-vf) "
3483 "or video output (-vo).\n");
3484 mpctx->stop_play = PT_NEXT_ENTRY;
3485 return;
3487 if (frame_time < 0)
3488 mpctx->stop_play = AT_END_OF_FILE;
3489 else if (!mpctx->restart_playback) {
3490 mpctx->time_frame += frame_time / opts->playback_speed;
3491 adjust_sync(mpctx, frame_time);
3494 if (mpctx->timeline) {
3495 struct timeline_part *next =
3496 mpctx->timeline + mpctx->timeline_part + 1;
3497 if (mpctx->sh_video->pts >= next->start
3498 || mpctx->stop_play == AT_END_OF_FILE
3499 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts) {
3500 seek(mpctx, (struct seek_params){ .type = MPSEEK_ABSOLUTE,
3501 .amount = next->start },
3502 true);
3503 return;
3507 // ==========================================================================
3509 current_module = "vo_check_events";
3510 vo_check_events(mpctx->video_out);
3512 #ifdef CONFIG_X11
3513 if (stop_xscreensaver) {
3514 current_module = "stop_xscreensaver";
3515 xscreensaver_heartbeat(mpctx->x11_state);
3517 #endif
3518 if (heartbeat_cmd) {
3519 static unsigned last_heartbeat;
3520 unsigned now = GetTimerMS();
3521 if (now - last_heartbeat > 30000) {
3522 last_heartbeat = now;
3523 system(heartbeat_cmd);
3527 bool frame_time_remaining = sleep_until_near_frame(mpctx,
3528 &mpctx->time_frame,
3529 full_audio_buffers,
3530 &aq_sleep_time);
3532 //====================== FLIP PAGE (VIDEO BLT): =========================
3534 current_module = "flip_page";
3535 if (!frame_time_remaining && blit_frame) {
3536 struct sh_video *sh_video = mpctx->sh_video;
3537 mpctx->video_pts = sh_video->pts;
3538 update_subtitles(mpctx, sh_video->pts, mpctx->video_offset, false);
3539 update_teletext(sh_video, mpctx->demuxer, 0);
3540 update_osd_msg(mpctx);
3541 struct vf_instance *vf = sh_video->vfilter;
3542 vf->control(vf, VFCTRL_DRAW_EOSD, mpctx->osd);
3543 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
3544 vo_osd_changed(0);
3546 mpctx->time_frame -= mpctx->video_out->flip_queue_offset;
3547 aq_sleep_time += mpctx->time_frame;
3548 // flag 256 means: libvo driver does its timing (dvb card)
3549 if (mpctx->time_frame > 0.001
3550 && !(mpctx->sh_video->output_flags & VFCAP_TIMER))
3551 mpctx->time_frame = timing_sleep(mpctx, mpctx->time_frame);
3552 mpctx->time_frame += mpctx->video_out->flip_queue_offset;
3554 unsigned int t2 = GetTimer();
3555 /* Playing with playback speed it's possible to get pathological
3556 * cases with mpctx->time_frame negative enough to cause an
3557 * overflow in pts_us calculation, thus the FFMAX. */
3558 double time_frame = FFMAX(mpctx->time_frame, -1);
3559 unsigned int pts_us = mpctx->last_time + time_frame * 1e6;
3560 int duration = -1;
3561 double pts2 = mpctx->video_out->next_pts2;
3562 if (pts2 != MP_NOPTS_VALUE && opts->correct_pts
3563 && !mpctx->restart_playback) {
3564 // expected A/V sync correction is ignored
3565 double diff = (pts2 - mpctx->video_pts);
3566 diff /= opts->playback_speed;
3567 if (mpctx->time_frame < 0)
3568 diff += mpctx->time_frame;
3569 if (diff < 0)
3570 diff = 0;
3571 if (diff > 10)
3572 diff = 10;
3573 duration = diff * 1e6;
3575 vo_flip_page(mpctx->video_out, pts_us | 1, duration);
3577 mpctx->last_vo_flip_duration = (GetTimer() - t2) * 0.000001;
3578 vout_time_usage += mpctx->last_vo_flip_duration;
3579 if (mpctx->video_out->driver->flip_page_timed) {
3580 // No need to adjust sync based on flip speed
3581 mpctx->last_vo_flip_duration = 0;
3582 // For print_status - VO call finishing early is OK for sync
3583 mpctx->time_frame -= get_relative_time(mpctx);
3585 if (mpctx->restart_playback) {
3586 mpctx->syncing_audio = true;
3587 if (mpctx->sh_audio && !mpctx->paused)
3588 fill_audio_out_buffers(mpctx);
3589 mpctx->restart_playback = false;
3590 mpctx->time_frame = 0;
3591 get_relative_time(mpctx);
3593 print_status(mpctx, MP_NOPTS_VALUE, true);
3594 } else
3595 print_status(mpctx, MP_NOPTS_VALUE, false);
3597 //============================ Auto QUALITY ============================
3599 /*Output quality adjustments:*/
3600 if (opts->auto_quality > 0) {
3601 current_module = "autoq";
3602 if (output_quality < opts->auto_quality && aq_sleep_time > 0)
3603 ++output_quality;
3604 else
3605 if (output_quality>1 && aq_sleep_time<0)
3606 --output_quality;
3607 else if (output_quality>0 && aq_sleep_time<-0.050f) // 50ms
3608 output_quality = 0;
3609 set_video_quality(mpctx->sh_video, output_quality);
3612 if (!frame_time_remaining && blit_frame) {
3613 if (play_n_frames >= 0) {
3614 --play_n_frames;
3615 if (play_n_frames <= 0)
3616 mpctx->stop_play = PT_NEXT_ENTRY;
3618 if (mpctx->step_frames > 0) {
3619 mpctx->step_frames--;
3620 if (mpctx->step_frames == 0)
3621 pause_player(mpctx);
3625 // FIXME: add size based support for -endpos
3626 if (end_at.type == END_AT_TIME &&
3627 !frame_time_remaining && end_at.pos <= mpctx->sh_video->pts)
3628 mpctx->stop_play = PT_NEXT_ENTRY;
3630 } // end if(mpctx->sh_video)
3632 #ifdef CONFIG_DVDNAV
3633 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
3634 nav_highlight_t hl;
3635 mp_dvdnav_get_highlight(mpctx->stream, &hl);
3636 if (!vo_spudec || !spudec_apply_palette_crop(vo_spudec, hl.palette, hl.sx, hl.sy, hl.ex, hl.ey)) {
3637 osd_set_nav_box(hl.sx, hl.sy, hl.ex, hl.ey);
3638 vo_osd_changed(OSDTYPE_DVDNAV);
3639 } else {
3640 osd_set_nav_box(0, 0, 0, 0);
3641 vo_osd_changed(OSDTYPE_DVDNAV);
3642 vo_osd_changed(OSDTYPE_SPU);
3645 if (mp_dvdnav_stream_has_changed(mpctx->stream)) {
3646 double ar = -1.0;
3647 if (mpctx->sh_video &&
3648 stream_control(mpctx->demuxer->stream,
3649 STREAM_CTRL_GET_ASPECT_RATIO, &ar)
3650 != STREAM_UNSUPPORTED)
3651 mpctx->sh_video->stream_aspect = ar;
3654 #endif
3656 //================= Keyboard events, SEEKing ====================
3658 current_module = "key_events";
3660 while (1) {
3661 mp_cmd_t *cmd;
3662 while ((cmd = mp_input_get_cmd(mpctx->input, 0, 1)) != NULL) {
3663 /* Allow running consecutive seek commands to combine them,
3664 * but execute the seek before running other commands.
3665 * If the user seeks continuously (keeps arrow key down)
3666 * try to finish showing a frame from one location before doing
3667 * another seek (which could lead to unchanging display). */
3668 if (mpctx->seek.type && cmd->id != MP_CMD_SEEK
3669 || mpctx->restart_playback && cmd->id == MP_CMD_SEEK
3670 && GetTimerMS() - mpctx->start_timestamp < 300)
3671 break;
3672 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
3673 run_command(mpctx, cmd);
3674 mp_cmd_free(cmd);
3675 if (mpctx->stop_play)
3676 break;
3678 if (!mpctx->paused || mpctx->stop_play || mpctx->seek.type
3679 || mpctx->restart_playback)
3680 break;
3681 if (mpctx->sh_video) {
3682 update_osd_msg(mpctx);
3683 int hack = vo_osd_changed(0);
3684 vo_osd_changed(hack);
3685 if (hack) {
3686 if (redraw_osd(mpctx->sh_video, mpctx->osd) < 0) {
3687 add_step_frame(mpctx);
3688 break;
3689 } else
3690 vo_osd_changed(0);
3693 pause_loop(mpctx);
3696 // handle -sstep
3697 if (step_sec > 0 && !mpctx->paused) {
3698 mpctx->osd_function = OSD_FFW;
3699 queue_seek(mpctx, MPSEEK_RELATIVE, step_sec, 0);
3702 edl_update(mpctx);
3704 /* Looping. */
3705 if (mpctx->stop_play==AT_END_OF_FILE && opts->loop_times>=0) {
3706 mp_msg(MSGT_CPLAYER, MSGL_V, "loop_times = %d\n", opts->loop_times);
3708 if (opts->loop_times>1)
3709 opts->loop_times--;
3710 else if (opts->loop_times==1)
3711 opts->loop_times = -1;
3712 play_n_frames = play_n_frames_mf;
3713 mpctx->stop_play = 0;
3714 queue_seek(mpctx, MPSEEK_ABSOLUTE, 0, 0);
3717 if (mpctx->seek.type) {
3718 seek(mpctx, mpctx->seek, false);
3719 mpctx->seek = (struct seek_params){0};
3724 static int read_keys(void *ctx, int fd)
3726 getch2(ctx);
3727 return mplayer_get_key(ctx, 0);
3730 static bool attachment_is_font(struct demux_attachment *att)
3732 if (!att->name || !att->type || !att->data || !att->data_size)
3733 return false;
3734 // match against MIME types
3735 if (strcmp(att->type, "application/x-truetype-font") == 0
3736 || strcmp(att->type, "application/x-font") == 0)
3737 return true;
3738 // fallback: match against file extension
3739 if (strlen(att->name) > 4) {
3740 char *ext = att->name + strlen(att->name) - 4;
3741 if (strcasecmp(ext, ".ttf") == 0 || strcasecmp(ext, ".ttc") == 0
3742 || strcasecmp(ext, ".otf") == 0)
3743 return true;
3745 return false;
3748 static int select_audio(demuxer_t *demuxer, int audio_id, char **audio_lang)
3750 if (audio_id == -1)
3751 audio_id = demuxer_audio_track_by_lang_and_default(demuxer, audio_lang);
3752 if (audio_id != -1) // -1 (automatic) is the default behaviour of demuxers
3753 demuxer_switch_audio(demuxer, audio_id);
3754 if (audio_id == -2) { // some demuxers don't yet know how to switch to no sound
3755 demuxer->audio->id = -2;
3756 demuxer->audio->sh = NULL;
3758 return demuxer->audio->id;
3761 static void print_version(const char* name)
3763 mp_msg(MSGT_CPLAYER, MSGL_INFO, MP_TITLE, name);
3765 /* Test for CPU capabilities (and corresponding OS support) for optimizing */
3766 GetCpuCaps(&gCpuCaps);
3767 #if ARCH_X86
3768 mp_msg(MSGT_CPLAYER, MSGL_V,
3769 "CPUflags: MMX: %d MMX2: %d 3DNow: %d 3DNowExt: %d SSE: %d SSE2: %d SSSE3: %d\n",
3770 gCpuCaps.hasMMX, gCpuCaps.hasMMX2,
3771 gCpuCaps.has3DNow, gCpuCaps.has3DNowExt,
3772 gCpuCaps.hasSSE, gCpuCaps.hasSSE2, gCpuCaps.hasSSSE3);
3773 #if CONFIG_RUNTIME_CPUDETECT
3774 mp_tmsg(MSGT_CPLAYER,MSGL_V, "Compiled with runtime CPU detection.\n");
3775 #else
3776 mp_tmsg(MSGT_CPLAYER,MSGL_V, "Compiled for x86 CPU with extensions:");
3777 if (HAVE_MMX)
3778 mp_msg(MSGT_CPLAYER,MSGL_V," MMX");
3779 if (HAVE_MMX2)
3780 mp_msg(MSGT_CPLAYER,MSGL_V," MMX2");
3781 if (HAVE_AMD3DNOW)
3782 mp_msg(MSGT_CPLAYER,MSGL_V," 3DNow");
3783 if (HAVE_AMD3DNOWEXT)
3784 mp_msg(MSGT_CPLAYER,MSGL_V," 3DNowExt");
3785 if (HAVE_SSE)
3786 mp_msg(MSGT_CPLAYER,MSGL_V," SSE");
3787 if (HAVE_SSE2)
3788 mp_msg(MSGT_CPLAYER,MSGL_V," SSE2");
3789 if (HAVE_SSSE3)
3790 mp_msg(MSGT_CPLAYER,MSGL_V," SSSE3");
3791 if (HAVE_CMOV)
3792 mp_msg(MSGT_CPLAYER,MSGL_V," CMOV");
3793 mp_msg(MSGT_CPLAYER,MSGL_V,"\n");
3794 #endif /* CONFIG_RUNTIME_CPUDETECT */
3795 #endif /* ARCH_X86 */
3798 #ifdef PTW32_STATIC_LIB
3799 static void detach_ptw32(void)
3801 pthread_win32_thread_detach_np();
3802 pthread_win32_process_detach_np();
3804 #endif
3806 /* This preprocessor directive is a hack to generate a mplayer-nomain.o object
3807 * file for some tools to link against. */
3808 #ifndef DISABLE_MAIN
3809 int main(int argc,char* argv[]){
3810 #ifdef PTW32_STATIC_LIB
3811 pthread_win32_process_attach_np();
3812 pthread_win32_thread_attach_np();
3813 atexit(detach_ptw32);
3814 #endif
3815 if (argc > 1 && !strcmp(argv[1], "-leak-report"))
3816 talloc_enable_leak_report();
3818 char * mem_ptr;
3820 // movie info:
3822 /* Flag indicating whether MPlayer should exit without playing anything. */
3823 int opt_exit = 0;
3824 int i;
3826 struct MPContext *mpctx = &(struct MPContext){
3827 .osd_function = OSD_PLAY,
3828 .begin_skip = MP_NOPTS_VALUE,
3829 .play_tree_step = 1,
3830 .global_sub_pos = -1,
3831 .set_of_sub_pos = -1,
3832 .file_format = DEMUXER_TYPE_UNKNOWN,
3833 .last_dvb_step = 1,
3836 InitTimer();
3837 srand(GetTimerMS());
3839 mp_msg_init();
3840 set_av_log_callback();
3842 #ifdef CONFIG_X11
3843 mpctx->x11_state = vo_x11_init_state();
3844 #endif
3845 struct MPOpts *opts = &mpctx->opts;
3846 set_default_mplayer_options(opts);
3847 // Create the config context and register the options
3848 mpctx->mconfig = m_config_new(opts, cfg_include);
3849 m_config_register_options(mpctx->mconfig,mplayer_opts);
3850 m_config_register_options(mpctx->mconfig, common_opts);
3851 mp_input_register_options(mpctx->mconfig);
3853 // Preparse the command line
3854 m_config_preparse_command_line(mpctx->mconfig,argc,argv);
3856 #if (defined(__MINGW32__) || defined(__CYGWIN__)) && defined(CONFIG_WIN32DLL)
3857 set_path_env();
3858 #endif
3860 #ifdef CONFIG_TV
3861 stream_tv_defaults.immediate = 1;
3862 #endif
3864 parse_cfgfiles(mpctx, mpctx->mconfig);
3866 mpctx->playtree = m_config_parse_mp_command_line(mpctx->mconfig, argc, argv);
3867 if(mpctx->playtree == NULL)
3868 opt_exit = 1;
3869 else {
3870 mpctx->playtree = play_tree_cleanup(mpctx->playtree);
3871 if(mpctx->playtree) {
3872 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,mpctx->mconfig);
3873 if(mpctx->playtree_iter) {
3874 if(play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
3875 play_tree_iter_free(mpctx->playtree_iter);
3876 mpctx->playtree_iter = NULL;
3878 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,1);
3882 mpctx->key_fifo = mp_fifo_create(opts);
3884 print_version("MPlayer2");
3886 #if defined(__MINGW32__) || defined(__CYGWIN__)
3888 HMODULE kernel32 = GetModuleHandle("Kernel32.dll");
3889 BOOL WINAPI (*setDEP)(DWORD) = NULL;
3890 BOOL WINAPI (*setDllDir)(LPCTSTR) = NULL;
3891 if (kernel32) {
3892 setDEP = GetProcAddress(kernel32, "SetProcessDEPPolicy");
3893 setDllDir = GetProcAddress(kernel32, "SetDllDirectoryA");
3895 if (setDEP) setDEP(3);
3896 if (setDllDir) setDllDir("");
3898 // stop Windows from showing all kinds of annoying error dialogs
3899 SetErrorMode(0x8003);
3900 // request 1ms timer resolution
3901 timeBeginPeriod(1);
3902 #endif
3904 #ifdef CONFIG_PRIORITY
3905 set_priority();
3906 #endif
3908 if (codec_path)
3909 set_codec_path(codec_path);
3911 if(opts->video_driver_list && strcmp(opts->video_driver_list[0],"help")==0){
3912 list_video_out();
3913 opt_exit = 1;
3916 if(opts->audio_driver_list && strcmp(opts->audio_driver_list[0],"help")==0){
3917 list_audio_out();
3918 opt_exit = 1;
3921 /* Check codecs.conf. */
3922 if(!codecs_file || !parse_codec_cfg(codecs_file)){
3923 if(!parse_codec_cfg(mem_ptr=get_path("codecs.conf"))){
3924 if(!parse_codec_cfg(MPLAYER_CONFDIR "/codecs.conf")){
3925 if(!parse_codec_cfg(NULL)){
3926 exit_player_with_rc(mpctx, EXIT_NONE, 0);
3928 mp_tmsg(MSGT_CPLAYER,MSGL_V,"Using built-in default codecs.conf.\n");
3931 free( mem_ptr ); // release the buffer created by get_path()
3934 if(audio_codec_list && strcmp(audio_codec_list[0],"help")==0){
3935 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available audio codecs:\n");
3936 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AUDIO_CODECS\n");
3937 list_codecs(1);
3938 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3939 opt_exit = 1;
3941 if(video_codec_list && strcmp(video_codec_list[0],"help")==0){
3942 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available video codecs:\n");
3943 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODECS\n");
3944 list_codecs(0);
3945 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3946 opt_exit = 1;
3948 if(video_fm_list && strcmp(video_fm_list[0],"help")==0){
3949 vfm_help();
3950 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3951 opt_exit = 1;
3953 if(audio_fm_list && strcmp(audio_fm_list[0],"help")==0){
3954 afm_help();
3955 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3956 opt_exit = 1;
3958 if(af_cfg.list && strcmp(af_cfg.list[0],"help")==0){
3959 af_help();
3960 printf("\n");
3961 opt_exit = 1;
3963 #ifdef CONFIG_X11
3964 if(vo_fstype_list && strcmp(vo_fstype_list[0],"help")==0){
3965 fstype_help();
3966 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3967 opt_exit = 1;
3969 #endif
3970 if((opts->demuxer_name && strcmp(opts->demuxer_name,"help")==0) ||
3971 (opts->audio_demuxer_name && strcmp(opts->audio_demuxer_name,"help")==0) ||
3972 (opts->sub_demuxer_name && strcmp(opts->sub_demuxer_name,"help")==0)){
3973 demuxer_help();
3974 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
3975 opt_exit = 1;
3977 if (opts->list_properties) {
3978 property_print_help();
3979 opt_exit = 1;
3982 if(opt_exit)
3983 exit_player(mpctx, EXIT_NONE);
3985 if (!mpctx->filename && !opts->player_idle_mode) {
3986 // no file/vcd/dvd -> show HELP:
3987 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", mp_gtext(help_text));
3988 exit_player_with_rc(mpctx, EXIT_NONE, 0);
3991 /* Display what configure line was used */
3992 mp_msg(MSGT_CPLAYER, MSGL_V, "Configuration: " CONFIGURATION "\n");
3994 // Many users forget to include command line in bugreports...
3995 if( mp_msg_test(MSGT_CPLAYER,MSGL_V) ){
3996 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "CommandLine:");
3997 for(i=1;i<argc;i++)mp_msg(MSGT_CPLAYER, MSGL_INFO," '%s'",argv[i]);
3998 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
4001 //------ load global data first ------
4003 mpctx->osd = osd_create();
4005 // check font
4006 #ifdef CONFIG_FREETYPE
4007 init_freetype();
4008 #endif
4009 #ifdef CONFIG_FONTCONFIG
4010 if(font_fontconfig <= 0)
4012 #endif
4013 #ifdef CONFIG_BITMAP_FONT
4014 if(font_name){
4015 vo_font=read_font_desc(font_name,font_factor,verbose>1);
4016 if(!vo_font) mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load bitmap font: %s\n",
4017 filename_recode(font_name));
4018 } else {
4019 // try default:
4020 vo_font=read_font_desc( mem_ptr=get_path("font/font.desc"),font_factor,verbose>1);
4021 free(mem_ptr); // release the buffer created by get_path()
4022 if(!vo_font)
4023 vo_font=read_font_desc(MPLAYER_DATADIR "/font/font.desc",font_factor,verbose>1);
4025 if (sub_font_name)
4026 mpctx->osd->sub_font = read_font_desc(sub_font_name, font_factor, verbose>1);
4027 else
4028 mpctx->osd->sub_font = vo_font;
4029 #endif
4030 #ifdef CONFIG_FONTCONFIG
4032 #endif
4034 #ifdef CONFIG_ASS
4035 ass_library = mp_ass_init();
4036 #endif
4038 #ifdef HAVE_RTC
4039 if(opts->rtc)
4041 char *rtc_device = opts->rtc_device;
4042 // seteuid(0); /* Can't hurt to try to get root here */
4043 if ((rtc_fd = open(rtc_device ? rtc_device : "/dev/rtc", O_RDONLY)) < 0)
4044 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Failed to open %s: %s (it should be readable by the user.)\n",
4045 rtc_device ? rtc_device : "/dev/rtc", strerror(errno));
4046 else {
4047 unsigned long irqp = 1024; /* 512 seemed OK. 128 is jerky. */
4049 if (ioctl(rtc_fd, RTC_IRQP_SET, irqp) < 0) {
4050 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Linux RTC init error in ioctl (rtc_irqp_set %lu): %s\n", irqp, strerror(errno));
4051 mp_tmsg(MSGT_CPLAYER, MSGL_HINT, "Try adding \"echo %lu > /proc/sys/dev/rtc/max-user-freq\" to your system startup scripts.\n", irqp);
4052 close (rtc_fd);
4053 rtc_fd = -1;
4054 } else if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
4055 /* variable only by the root */
4056 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC init error in ioctl (rtc_pie_on): %s\n", strerror(errno));
4057 close (rtc_fd);
4058 rtc_fd = -1;
4059 } else
4060 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Using Linux hardware RTC timing (%ldHz).\n", irqp);
4063 if(rtc_fd<0)
4064 #endif /* HAVE_RTC */
4065 mp_msg(MSGT_CPLAYER, MSGL_V, "Using %s timing\n",
4066 opts->softsleep ? "software" : timer_name);
4068 #ifdef HAVE_TERMCAP
4069 load_termcap(NULL); // load key-codes
4070 #endif
4072 // ========== Init keyboard FIFO (connection to libvo) ============
4074 // Init input system
4075 current_module = "init_input";
4076 mpctx->input = mp_input_init(&opts->input);
4077 mp_input_add_key_fd(mpctx->input, -1,0,mplayer_get_key,NULL, mpctx->key_fifo);
4078 if(slave_mode) {
4079 #if USE_FD0_CMD_SELECT
4080 int flags = fcntl(0, F_GETFL);
4081 if (flags != -1)
4082 fcntl(0, F_SETFL, flags | O_NONBLOCK);
4083 #endif
4084 mp_input_add_cmd_fd(mpctx->input, 0,USE_FD0_CMD_SELECT,MP_INPUT_SLAVE_CMD_FUNC,NULL);
4086 else if (opts->consolecontrols)
4087 mp_input_add_key_fd(mpctx->input, 0, 1, read_keys, NULL, mpctx->key_fifo);
4088 // Set the libstream interrupt callback
4089 stream_set_interrupt_callback(mp_input_check_interrupt, mpctx->input);
4091 #ifdef CONFIG_MENU
4092 if(use_menu) {
4093 if(menu_cfg && menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
4094 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
4095 else {
4096 menu_cfg = get_path("menu.conf");
4097 if(menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
4098 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
4099 else {
4100 if(menu_init(mpctx, mpctx->mconfig, mpctx->input,
4101 MPLAYER_CONFDIR "/menu.conf"))
4102 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", MPLAYER_CONFDIR"/menu.conf");
4103 else {
4104 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Menu init failed.\n");
4105 use_menu = 0;
4110 #endif
4112 current_module = NULL;
4114 /// Catch signals
4115 #ifndef __MINGW32__
4116 signal(SIGCHLD,child_sighandler);
4117 #endif
4119 #ifdef CONFIG_CRASH_DEBUG
4120 prog_path = argv[0];
4121 #endif
4122 //========= Catch terminate signals: ================
4123 // terminate requests:
4124 signal(SIGTERM,exit_sighandler); // kill
4125 signal(SIGHUP,exit_sighandler); // kill -HUP / xterm closed
4127 signal(SIGINT,exit_sighandler); // Interrupt from keyboard
4129 signal(SIGQUIT,exit_sighandler); // Quit from keyboard
4130 signal(SIGPIPE,exit_sighandler); // Some window managers cause this
4131 #ifdef CONFIG_SIGHANDLER
4132 // fatal errors:
4133 signal(SIGBUS,exit_sighandler); // bus error
4134 signal(SIGSEGV,exit_sighandler); // segfault
4135 signal(SIGILL,exit_sighandler); // illegal instruction
4136 signal(SIGFPE,exit_sighandler); // floating point exc.
4137 signal(SIGABRT,exit_sighandler); // abort()
4138 #ifdef CONFIG_CRASH_DEBUG
4139 if (crash_debug)
4140 signal(SIGTRAP,exit_sighandler);
4141 #endif
4142 #endif
4144 // ******************* Now, let's see the per-file stuff ********************
4146 play_next_file:
4148 // init global sub numbers
4149 mpctx->global_sub_size = 0;
4150 memset(mpctx->sub_counts, 0, sizeof(mpctx->sub_counts));
4152 if (mpctx->filename) {
4153 load_per_protocol_config (mpctx->mconfig, mpctx->filename);
4154 load_per_extension_config (mpctx->mconfig, mpctx->filename);
4155 load_per_file_config (mpctx->mconfig, mpctx->filename);
4158 if (opts->video_driver_list)
4159 load_per_output_config (mpctx->mconfig, PROFILE_CFG_VO, opts->video_driver_list[0]);
4160 if (opts->audio_driver_list)
4161 load_per_output_config (mpctx->mconfig, PROFILE_CFG_AO, opts->audio_driver_list[0]);
4163 // We must enable getch2 here to be able to interrupt network connection
4164 // or cache filling
4165 if (opts->consolecontrols && !slave_mode) {
4166 if(mpctx->initialized_flags&INITIALIZED_GETCH2)
4167 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"WARNING: getch2_init called twice!\n");
4168 else
4169 getch2_enable(); // prepare stdin for hotkeys...
4170 mpctx->initialized_flags|=INITIALIZED_GETCH2;
4171 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[init getch2]]]\n");
4174 // =================== GUI idle loop (STOP state) ===========================
4175 while (opts->player_idle_mode && !mpctx->filename) {
4176 play_tree_t * entry = NULL;
4177 mp_cmd_t * cmd;
4178 if (mpctx->video_out && mpctx->video_out->config_ok)
4179 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
4180 while (!(cmd = mp_input_get_cmd(mpctx->input, 0, 0))) { // wait for command
4181 if (mpctx->video_out)
4182 vo_check_events(mpctx->video_out);
4183 usec_sleep(20000);
4185 switch (cmd->id) {
4186 case MP_CMD_LOADFILE:
4187 // prepare a tree entry with the new filename
4188 entry = play_tree_new();
4189 play_tree_add_file(entry, cmd->args[0].v.s);
4190 // The entry is added to the main playtree after the switch().
4191 break;
4192 case MP_CMD_LOADLIST:
4193 entry = parse_playlist_file(mpctx->mconfig, cmd->args[0].v.s);
4194 break;
4195 case MP_CMD_QUIT:
4196 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
4197 break;
4198 case MP_CMD_VO_FULLSCREEN:
4199 case MP_CMD_GET_PROPERTY:
4200 case MP_CMD_SET_PROPERTY:
4201 case MP_CMD_STEP_PROPERTY:
4202 run_command(mpctx, cmd);
4203 break;
4206 mp_cmd_free(cmd);
4208 if (entry) { // user entered a command that gave a valid entry
4209 if (mpctx->playtree) // the playtree is always a node with one child. let's clear it
4210 play_tree_free_list(mpctx->playtree->child, 1);
4211 else mpctx->playtree=play_tree_new(); // .. or make a brand new playtree
4213 if (!mpctx->playtree) continue; // couldn't make playtree! wait for next command
4215 play_tree_set_child(mpctx->playtree, entry);
4217 /* Make iterator start at the top the of tree. */
4218 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree, mpctx->mconfig);
4219 if (!mpctx->playtree_iter) continue;
4221 // find the first real item in the tree
4222 if (play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
4223 // no items!
4224 play_tree_iter_free(mpctx->playtree_iter);
4225 mpctx->playtree_iter = NULL;
4226 continue; // wait for next command
4228 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, 1);
4231 //---------------------------------------------------------------------------
4233 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
4234 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL);
4236 if (mpctx->filename) {
4237 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nPlaying %s.\n",
4238 filename_recode(mpctx->filename));
4239 if(use_filename_title && opts->vo_wintitle == NULL)
4240 opts->vo_wintitle = strdup(mp_basename(mpctx->filename));
4243 if (edl_filename) {
4244 if (edl_records) free_edl(edl_records);
4245 next_edl_record = edl_records = edl_parse_file();
4247 if (edl_output_filename) {
4248 if (edl_fd) fclose(edl_fd);
4249 if ((edl_fd = fopen(edl_output_filename, "w")) == NULL)
4251 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Can't open EDL file [%s] for writing.\n",
4252 filename_recode(edl_output_filename));
4256 //==================== Open VOB-Sub ============================
4258 current_module="vobsub";
4259 if (opts->vobsub_name){
4260 vo_vobsub=vobsub_open(opts->vobsub_name,spudec_ifo,1,&vo_spudec);
4261 if(vo_vobsub==NULL)
4262 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load subtitles: %s\n",
4263 filename_recode(opts->vobsub_name));
4264 } else if (opts->sub_auto && mpctx->filename){
4265 char **vob = find_vob_subtitles(opts, mpctx->filename);
4266 for (int i = 0; i < MP_TALLOC_ELEMS(vob); i++) {
4267 vo_vobsub = vobsub_open(vob[i], spudec_ifo, 0, &vo_spudec);
4268 if (vo_vobsub)
4269 break;
4271 talloc_free(vob);
4273 if(vo_vobsub){
4274 mpctx->initialized_flags|=INITIALIZED_VOBSUB;
4275 vobsub_set_from_lang(vo_vobsub, opts->sub_lang);
4276 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
4278 // setup global sub numbering
4279 mpctx->sub_counts[SUB_SOURCE_VOBSUB] = vobsub_get_indexes_count(vo_vobsub);
4282 //============ Open & Sync STREAM --- fork cache2 ====================
4284 mpctx->stream=NULL;
4285 mpctx->demuxer=NULL;
4286 mpctx->d_audio=NULL;
4287 mpctx->d_video=NULL;
4288 mpctx->d_sub = NULL;
4289 mpctx->sh_audio=NULL;
4290 mpctx->sh_video=NULL;
4292 current_module="open_stream";
4293 mpctx->stream = open_stream(mpctx->filename, opts, &mpctx->file_format);
4294 if(!mpctx->stream) { // error...
4295 mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY);
4296 goto goto_next_file;
4298 mpctx->initialized_flags|=INITIALIZED_STREAM;
4300 if(mpctx->file_format == DEMUXER_TYPE_PLAYLIST) {
4301 mp_msg(MSGT_CPLAYER, MSGL_ERR, "\nThis looks like a playlist, but "
4302 "playlist support will not be used automatically.\n"
4303 "MPlayer's playlist code is unsafe and should only be used with "
4304 "trusted sources.\nPlayback will probably fail.\n\n");
4305 #if 0
4306 play_tree_t* entry;
4307 // Handle playlist
4308 current_module="handle_playlist";
4309 mp_msg(MSGT_CPLAYER,MSGL_V,"Parsing playlist %s...\n",
4310 filename_recode(mpctx->filename));
4311 entry = parse_playtree(mpctx->stream, mpctx->mconfig, 0);
4312 mpctx->eof=playtree_add_playlist(mpctx, entry);
4313 goto goto_next_file;
4314 #endif
4316 mpctx->stream->start_pos+=seek_to_byte;
4318 if(stream_dump_type==5){
4319 unsigned char buf[4096];
4320 int len;
4321 FILE *f;
4322 current_module="dumpstream";
4323 stream_reset(mpctx->stream);
4324 stream_seek(mpctx->stream,mpctx->stream->start_pos);
4325 f=fopen(opts->stream_dump_name,"wb");
4326 if(!f){
4327 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
4328 exit_player(mpctx, EXIT_ERROR);
4330 if (opts->chapterrange[0] > 1) {
4331 int chapter = opts->chapterrange[0] - 1;
4332 stream_control(mpctx->stream, STREAM_CTRL_SEEK_TO_CHAPTER, &chapter);
4334 struct stream_dump_progress info;
4335 stream_dump_progress_start(&info);
4336 while(!mpctx->stream->eof && !async_quit_request){
4337 len=stream_read(mpctx->stream,buf,4096);
4338 if(len>0) {
4339 if(fwrite(buf,len,1,f) != 1) {
4340 mp_tmsg(MSGT_GLOBAL,MSGL_FATAL,"%s: Error writing file.\n",opts->stream_dump_name);
4341 exit_player(mpctx, EXIT_ERROR);
4344 stream_dump_progress(&info, len, mpctx->stream);
4345 if (opts->chapterrange[1] > 0) {
4346 int chapter = -1;
4347 if (stream_control(mpctx->stream, STREAM_CTRL_GET_CURRENT_CHAPTER,
4348 &chapter) == STREAM_OK
4349 && chapter + 1 > opts->chapterrange[1])
4350 break;
4353 if(fclose(f)) {
4354 mp_tmsg(MSGT_GLOBAL,MSGL_FATAL,"%s: Error writing file.\n",opts->stream_dump_name);
4355 exit_player(mpctx, EXIT_ERROR);
4357 stream_dump_progress_end(&info, opts->stream_dump_name);
4358 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Stream dump complete.\n");
4359 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4362 #ifdef CONFIG_DVDREAD
4363 if(mpctx->stream->type==STREAMTYPE_DVD){
4364 current_module="dvd lang->id";
4365 if(opts->audio_lang && opts->audio_id==-1) opts->audio_id=dvd_aid_from_lang(mpctx->stream,opts->audio_lang);
4366 if(opts->sub_lang && opts->sub_id==-1) opts->sub_id=dvd_sid_from_lang(mpctx->stream,opts->sub_lang);
4367 // setup global sub numbering
4368 mpctx->sub_counts[SUB_SOURCE_DEMUX] = dvd_number_of_subs(mpctx->stream);
4369 current_module=NULL;
4371 #endif
4373 #ifdef CONFIG_DVDNAV
4374 if(mpctx->stream->type==STREAMTYPE_DVDNAV){
4375 current_module="dvdnav lang->id";
4376 if(opts->audio_lang && opts->audio_id==-1) opts->audio_id=mp_dvdnav_aid_from_lang(mpctx->stream,opts->audio_lang);
4377 dvdsub_lang_id = -3;
4378 if(opts->sub_lang && opts->sub_id==-1)
4379 dvdsub_lang_id = opts->sub_id = mp_dvdnav_sid_from_lang(mpctx->stream,opts->sub_lang);
4380 // setup global sub numbering
4381 mpctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(mpctx->stream);
4382 current_module=NULL;
4384 #endif
4386 // CACHE2: initial prefill: 20% later: 5% (should be set by -cacheopts)
4387 goto_enable_cache:
4388 if(stream_cache_size>0){
4389 int res;
4390 float stream_cache_min_percent = opts->stream_cache_min_percent;
4391 float stream_cache_seek_min_percent = opts->stream_cache_seek_min_percent;
4392 current_module="enable_cache";
4393 res = stream_enable_cache(mpctx->stream,stream_cache_size*1024,
4394 stream_cache_size*1024*(stream_cache_min_percent / 100.0),
4395 stream_cache_size*1024*(stream_cache_seek_min_percent / 100.0));
4396 if(res == 0)
4397 if((mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY))) goto goto_next_file;
4400 //============ Open DEMUXERS --- DETECT file type =======================
4401 current_module="demux_open";
4403 mpctx->demuxer=demux_open(opts, mpctx->stream,mpctx->file_format,opts->audio_id,opts->video_id,opts->sub_id,mpctx->filename);
4405 // HACK to get MOV Reference Files working
4407 if (mpctx->demuxer && mpctx->demuxer->type==DEMUXER_TYPE_PLAYLIST)
4409 unsigned char* playlist_entry;
4410 play_tree_t *list = NULL, *entry = NULL;
4412 current_module="handle_demux_playlist";
4413 while (ds_get_packet(mpctx->demuxer->video,&playlist_entry)>0)
4415 char *temp;
4416 const char *bname;
4418 mp_msg(MSGT_CPLAYER,MSGL_V,"Adding file %s to element entry.\n",
4419 filename_recode(playlist_entry));
4421 bname=mp_basename(playlist_entry);
4422 if ((strlen(bname)>10) && !strncmp(bname,"qt",2) && !strncmp(bname+3,"gateQT",6))
4423 continue;
4425 if (!strcmp(playlist_entry, mpctx->filename)) // ignoring self-reference
4426 continue;
4428 entry = play_tree_new();
4430 if (mpctx->filename && !strcmp(mp_basename(playlist_entry),playlist_entry)) // add reference path of current file
4432 temp=malloc((strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))+strlen(playlist_entry)+1));
4433 if (temp)
4435 strncpy(temp, mpctx->filename, strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename)));
4436 temp[strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))]='\0';
4437 strcat(temp, playlist_entry);
4438 if (!strcmp(temp, mpctx->filename)) {
4439 free(temp);
4440 continue;
4442 play_tree_add_file(entry,temp);
4443 mp_msg(MSGT_CPLAYER,MSGL_V,"Resolving reference to %s.\n",temp);
4444 free(temp);
4447 else
4448 play_tree_add_file(entry,playlist_entry);
4450 if(!list)
4451 list = entry;
4452 else
4453 play_tree_append_entry(list,entry);
4455 free_demuxer(mpctx->demuxer);
4456 mpctx->demuxer = NULL;
4458 if (list)
4460 entry = play_tree_new();
4461 play_tree_set_child(entry,list);
4462 mpctx->stop_play = playtree_add_playlist(mpctx, entry);
4463 goto goto_next_file;
4467 if(!mpctx->demuxer) {
4468 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Failed to recognize file format.\n");
4469 goto goto_next_file;
4472 if (mpctx->demuxer->matroska_data.ordered_chapters)
4473 build_ordered_chapter_timeline(mpctx);
4475 if (mpctx->demuxer->type == DEMUXER_TYPE_EDL)
4476 build_edl_timeline(mpctx);
4478 if (mpctx->timeline) {
4479 mpctx->timeline_part = 0;
4480 mpctx->demuxer = mpctx->timeline[0].source->demuxer;
4482 int part_count = mpctx->num_timeline_parts;
4483 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline contains %d parts from %d "
4484 "sources. Total length %.3f seconds.\n", part_count,
4485 mpctx->num_sources, mpctx->timeline[part_count].start);
4486 mp_msg(MSGT_CPLAYER, MSGL_V, "Source files:\n");
4487 for (int i = 0; i < mpctx->num_sources; i++)
4488 mp_msg(MSGT_CPLAYER, MSGL_V, "%d: %s\n", i,
4489 filename_recode(mpctx->sources[i].demuxer->filename));
4490 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline parts: (number, start, "
4491 "source_start, source):\n");
4492 for (int i = 0; i < part_count; i++) {
4493 struct timeline_part *p = mpctx->timeline + i;
4494 mp_msg(MSGT_CPLAYER, MSGL_V, "%3d %9.3f %9.3f %3td\n", i, p->start,
4495 p->source_start, p->source - mpctx->sources);
4497 mp_msg(MSGT_CPLAYER, MSGL_V, "END %9.3f\n",
4498 mpctx->timeline[part_count].start);
4501 if (!mpctx->sources) {
4502 mpctx->sources = talloc_ptrtype(NULL, mpctx->sources);
4503 *mpctx->sources = (struct content_source){.stream = mpctx->stream,
4504 .demuxer = mpctx->demuxer};
4505 mpctx->num_sources = 1;
4508 mpctx->initialized_flags|=INITIALIZED_DEMUXER;
4510 #ifdef CONFIG_ASS
4511 if (opts->ass_enabled && ass_library) {
4512 for (int j = 0; j < mpctx->num_sources; j++) {
4513 struct demuxer *d = mpctx->sources[j].demuxer;
4514 for (int i = 0; i < d->num_attachments; i++) {
4515 struct demux_attachment *att = d->attachments + i;
4516 if (use_embedded_fonts && attachment_is_font(att))
4517 ass_add_font(ass_library, att->name, att->data, att->data_size);
4521 #endif
4523 current_module="demux_open2";
4525 mpctx->d_audio=mpctx->demuxer->audio;
4526 mpctx->d_video=mpctx->demuxer->video;
4527 mpctx->d_sub=mpctx->demuxer->sub;
4529 if (ts_prog) {
4530 int tmp = ts_prog;
4531 mp_property_do("switch_program", M_PROPERTY_SET, &tmp, mpctx);
4533 // select audio stream
4534 for (int i = 0; i < mpctx->num_sources; i++)
4535 select_audio(mpctx->sources[i].demuxer->audio->demuxer, opts->audio_id,
4536 opts->audio_lang);
4538 // DUMP STREAMS:
4539 if((stream_dump_type)&&(stream_dump_type<4)){
4540 FILE *f;
4541 demux_stream_t *ds=NULL;
4542 current_module="dump";
4543 // select stream to dump
4544 switch(stream_dump_type){
4545 case 1: ds=mpctx->d_audio;break;
4546 case 2: ds=mpctx->d_video;break;
4547 case 3: ds=mpctx->d_sub;break;
4549 if(!ds){
4550 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"dump: FATAL: Selected stream missing!\n");
4551 exit_player(mpctx, EXIT_ERROR);
4553 // disable other streams:
4554 if(mpctx->d_audio && mpctx->d_audio!=ds) {ds_free_packs(mpctx->d_audio); mpctx->d_audio->id=-2; }
4555 if(mpctx->d_video && mpctx->d_video!=ds) {ds_free_packs(mpctx->d_video); mpctx->d_video->id=-2; }
4556 if(mpctx->d_sub && mpctx->d_sub!=ds) {ds_free_packs(mpctx->d_sub); mpctx->d_sub->id=-2; }
4557 // let's dump it!
4558 f=fopen(opts->stream_dump_name,"wb");
4559 if(!f){
4560 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
4561 exit_player(mpctx, EXIT_ERROR);
4563 struct stream_dump_progress info;
4564 stream_dump_progress_start(&info);
4565 while(!ds->eof){
4566 unsigned char* start;
4567 int in_size=ds_get_packet(ds,&start);
4568 if( (mpctx->demuxer->file_format==DEMUXER_TYPE_AVI || mpctx->demuxer->file_format==DEMUXER_TYPE_ASF || mpctx->demuxer->file_format==DEMUXER_TYPE_MOV)
4569 && stream_dump_type==2) fwrite(&in_size,1,4,f);
4570 if(in_size>0) {
4571 fwrite(start,in_size,1,f);
4572 stream_dump_progress(&info, in_size, mpctx->stream);
4574 if (opts->chapterrange[1] > 0) {
4575 int cur_chapter = demuxer_get_current_chapter(mpctx->demuxer, 0);
4576 if(cur_chapter!=-1 && cur_chapter+1 > opts->chapterrange[1])
4577 break;
4580 fclose(f);
4581 stream_dump_progress_end(&info, opts->stream_dump_name);
4582 mp_tmsg(MSGT_CPLAYER ,MSGL_INFO, "Stream dump complete.\n");
4583 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4586 mpctx->sh_audio=mpctx->d_audio->sh;
4587 mpctx->sh_video=mpctx->d_video->sh;
4589 if(mpctx->sh_video){
4591 current_module="video_read_properties";
4592 if(!video_read_properties(mpctx->sh_video)) {
4593 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Video: Cannot read properties.\n");
4594 mpctx->sh_video=mpctx->d_video->sh=NULL;
4595 } else {
4596 mp_tmsg(MSGT_CPLAYER,MSGL_V,"[V] filefmt:%d fourcc:0x%X size:%dx%d fps:%5.3f ftime:=%6.4f\n",
4597 mpctx->demuxer->file_format,mpctx->sh_video->format, mpctx->sh_video->disp_w,mpctx->sh_video->disp_h,
4598 mpctx->sh_video->fps,mpctx->sh_video->frametime
4601 /* need to set fps here for output encoders to pick it up in their init */
4602 if(force_fps){
4603 mpctx->sh_video->fps=force_fps;
4604 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
4606 vo_fps = mpctx->sh_video->fps;
4608 if(!mpctx->sh_video->fps && !force_fps){
4609 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"FPS not specified in the header or invalid, use the -fps option.\n");
4610 mpctx->opts.correct_pts = 1;
4616 if(!mpctx->sh_video && !mpctx->sh_audio){
4617 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL, "No stream found.\n");
4618 #ifdef CONFIG_DVBIN
4619 if(mpctx->stream->type == STREAMTYPE_DVB)
4621 int dir;
4622 int v = mpctx->last_dvb_step;
4623 if(v > 0)
4624 dir = DVB_CHANNEL_HIGHER;
4625 else
4626 dir = DVB_CHANNEL_LOWER;
4628 if(dvb_step_channel(mpctx->stream, dir)) {
4629 mpctx->stop_play = PT_NEXT_ENTRY;
4630 mpctx->dvbin_reopen = 1;
4633 #endif
4634 goto goto_next_file; // exit_player(_("Fatal error"));
4637 /* display clip info */
4638 demux_info_print(mpctx->demuxer);
4640 //================== Read SUBTITLES (DVD & TEXT) ==========================
4641 if(vo_spudec==NULL &&
4642 (mpctx->stream->type==STREAMTYPE_DVD || mpctx->stream->type == STREAMTYPE_DVDNAV)){
4643 init_vo_spudec(mpctx);
4646 // after reading video params we should load subtitles because
4647 // we know fps so now we can adjust subtitle time to ~6 seconds AST
4648 // check .sub
4649 current_module="read_subtitles_file";
4650 double sub_fps = mpctx->sh_video ? mpctx->sh_video->fps : 25;
4651 if(opts->sub_name){
4652 for (i = 0; opts->sub_name[i] != NULL; ++i)
4653 add_subtitles(mpctx, opts->sub_name[i], sub_fps, 0);
4655 if(opts->sub_auto) { // auto load sub file ...
4656 char **tmp = find_text_subtitles(opts, mpctx->filename);
4657 int nsub = MP_TALLOC_ELEMS(tmp);
4658 for (int i = 0; i < nsub; i++)
4659 add_subtitles(mpctx, tmp[i], sub_fps, 1);
4660 talloc_free(tmp);
4662 if (mpctx->set_of_sub_size > 0)
4663 mpctx->sub_counts[SUB_SOURCE_SUBS] = mpctx->set_of_sub_size;
4665 if (select_subtitle(mpctx)) {
4666 if(mpctx->subdata)
4667 switch (stream_dump_type) {
4668 case 3: list_sub_file(mpctx->subdata); break;
4669 case 4: dump_mpsub(mpctx->subdata, mpctx->sh_video->fps); break;
4670 case 6: dump_srt(mpctx->subdata, mpctx->sh_video->fps); break;
4671 case 7: dump_microdvd(mpctx->subdata, mpctx->sh_video->fps); break;
4672 case 8: dump_jacosub(mpctx->subdata, mpctx->sh_video->fps); break;
4673 case 9: dump_sami(mpctx->subdata, mpctx->sh_video->fps); break;
4677 print_file_properties(mpctx, mpctx->filename);
4679 reinit_video_chain(mpctx);
4680 if (mpctx->sh_video) {
4681 if(mpctx->sh_video->output_flags & VFCAP_SPU && vo_spudec)
4682 spudec_set_hw_spu(vo_spudec,mpctx->video_out);
4683 #ifdef CONFIG_FREETYPE
4684 force_load_font = 1;
4685 #endif
4686 } else if (!mpctx->sh_audio)
4687 goto goto_next_file;
4689 //================== MAIN: ==========================
4690 current_module="main";
4692 if (opts->playing_msg) {
4693 char* msg = property_expand_string(mpctx, opts->playing_msg);
4694 mp_msg(MSGT_CPLAYER,MSGL_INFO,"%s",msg);
4695 free(msg);
4699 // Disable the term OSD in verbose mode
4700 if (verbose)
4701 opts->term_osd = 0;
4705 // Make sure old OSD does not stay around,
4706 // e.g. with -fixed-vo and same-resolution files
4707 clear_osd_msgs();
4708 update_osd_msg(mpctx);
4710 //================ SETUP AUDIO ==========================
4712 if(mpctx->sh_audio){
4713 reinit_audio_chain(mpctx);
4714 if (mpctx->sh_audio && mpctx->sh_audio->codec)
4715 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_CODEC=%s\n", mpctx->sh_audio->codec->name);
4718 current_module="av_init";
4720 if(mpctx->sh_video){
4721 mpctx->sh_video->timer=0;
4722 if (! ignore_start)
4723 audio_delay += mpctx->sh_video->stream_delay;
4725 if(mpctx->sh_audio){
4726 if (start_volume >= 0)
4727 mixer_setvolume(&mpctx->mixer, start_volume, start_volume);
4728 if (! ignore_start)
4729 audio_delay -= mpctx->sh_audio->stream_delay;
4730 mpctx->delay=-audio_delay;
4733 if(!mpctx->sh_audio){
4734 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Audio: no sound\n");
4735 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused audio chunks.\n",mpctx->d_audio->packs);
4736 ds_free_packs(mpctx->d_audio); // free buffered chunks
4737 //mpctx->d_audio->id=-2; // do not read audio chunks
4738 //uninit_player(mpctx, INITIALIZED_AO); // close device
4740 if(!mpctx->sh_video){
4741 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Video: no video\n");
4742 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused video chunks.\n",mpctx->d_video->packs);
4743 ds_free_packs(mpctx->d_video);
4744 mpctx->d_video->id=-2;
4745 //if(!fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
4748 if (!mpctx->sh_video && !mpctx->sh_audio)
4749 goto goto_next_file;
4751 //if(demuxer->file_format!=DEMUXER_TYPE_AVI) pts_from_bps=0; // it must be 0 for mpeg/asf!
4752 if(force_fps && mpctx->sh_video){
4753 vo_fps = mpctx->sh_video->fps=force_fps;
4754 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
4755 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"FPS forced to be %5.3f (ftime: %5.3f).\n",mpctx->sh_video->fps,mpctx->sh_video->frametime);
4758 mp_input_set_section(mpctx->input, NULL);
4759 //TODO: add desired (stream-based) sections here
4760 if (mpctx->stream->type==STREAMTYPE_TV) mp_input_set_section(mpctx->input, "tv");
4761 if (mpctx->stream->type==STREAMTYPE_DVDNAV) mp_input_set_section(mpctx->input, "dvdnav");
4763 //==================== START PLAYING =======================
4765 if(opts->loop_times>1) opts->loop_times--; else
4766 if(opts->loop_times==1) opts->loop_times = -1;
4768 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Starting playback...\n");
4770 total_time_usage_start=GetTimer();
4771 audio_time_usage=0; video_time_usage=0; vout_time_usage=0;
4772 total_frame_cnt=0; drop_frame_cnt=0; // fix for multifile fps benchmark
4773 play_n_frames=play_n_frames_mf;
4775 if(play_n_frames==0){
4776 mpctx->stop_play=PT_NEXT_ENTRY; goto goto_next_file;
4779 mpctx->time_frame = 0;
4780 mpctx->drop_message_shown = 0;
4781 mpctx->restart_playback = true;
4782 mpctx->video_pts = 0;
4783 mpctx->hrseek_active = false;
4784 mpctx->hrseek_framedrop = false;
4785 mpctx->step_frames = 0;
4786 mpctx->total_avsync_change = 0;
4787 mpctx->last_chapter_seek = -1;
4789 // If there's a timeline force an absolute seek to initialize state
4790 if (seek_to_sec || mpctx->timeline) {
4791 queue_seek(mpctx, MPSEEK_ABSOLUTE, seek_to_sec, 0);
4792 seek(mpctx, mpctx->seek, false);
4793 end_at.pos += seek_to_sec;
4795 if (opts->chapterrange[0] > 0) {
4796 double pts;
4797 if (seek_chapter(mpctx, opts->chapterrange[0]-1, &pts, NULL) >= 0
4798 && pts > -1.0) {
4799 queue_seek(mpctx, MPSEEK_ABSOLUTE, pts, 0);
4800 seek(mpctx, mpctx->seek, false);
4804 if (end_at.type == END_AT_SIZE) {
4805 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Option -endpos in MPlayer does not yet support size units.\n");
4806 end_at.type = END_AT_NONE;
4809 #ifdef CONFIG_DVDNAV
4810 mp_dvdnav_context_free(mpctx);
4811 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4812 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
4813 mp_dvdnav_cell_has_changed(mpctx->stream,1);
4815 #endif
4817 mpctx->seek = (struct seek_params){0};
4818 get_relative_time(mpctx); // reset current delta
4819 // Make sure VO knows current pause state
4820 if (mpctx->sh_video)
4821 vo_control(mpctx->video_out, mpctx->paused ? VOCTRL_PAUSE : VOCTRL_RESUME,
4822 NULL);
4824 while (!mpctx->stop_play)
4825 run_playloop(mpctx);
4827 mp_msg(MSGT_GLOBAL,MSGL_V,"EOF code: %d \n",mpctx->stop_play);
4829 #ifdef CONFIG_DVBIN
4830 if(mpctx->dvbin_reopen)
4832 mpctx->stop_play = 0;
4833 uninit_player(mpctx, INITIALIZED_ALL-(INITIALIZED_STREAM|INITIALIZED_GETCH2|(opts->fixed_vo?INITIALIZED_VO:0)));
4834 cache_uninit(mpctx->stream);
4835 mpctx->dvbin_reopen = 0;
4836 goto goto_enable_cache;
4838 #endif
4841 goto_next_file: // don't jump here after ao/vo/getch initialization!
4843 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\n");
4845 if (opts->benchmark) {
4846 double tot=video_time_usage+vout_time_usage+audio_time_usage;
4847 double total_time_usage;
4848 total_time_usage_start=GetTimer()-total_time_usage_start;
4849 total_time_usage = (float)total_time_usage_start*0.000001;
4850 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\nBENCHMARKs: VC:%8.3fs VO:%8.3fs A:%8.3fs Sys:%8.3fs = %8.3fs\n",
4851 video_time_usage,vout_time_usage,audio_time_usage,
4852 total_time_usage-tot,total_time_usage);
4853 if(total_time_usage>0.0)
4854 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARK%%: VC:%8.4f%% VO:%8.4f%% A:%8.4f%% Sys:%8.4f%% = %8.4f%%\n",
4855 100.0*video_time_usage/total_time_usage,
4856 100.0*vout_time_usage/total_time_usage,
4857 100.0*audio_time_usage/total_time_usage,
4858 100.0*(total_time_usage-tot)/total_time_usage,
4859 100.0);
4860 if(total_frame_cnt && frame_dropping)
4861 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARKn: disp: %d (%3.2f fps) drop: %d (%d%%) total: %d (%3.2f fps)\n",
4862 total_frame_cnt-drop_frame_cnt,
4863 (total_time_usage>0.5)?((total_frame_cnt-drop_frame_cnt)/total_time_usage):0,
4864 drop_frame_cnt,
4865 100*drop_frame_cnt/total_frame_cnt,
4866 total_frame_cnt,
4867 (total_time_usage>0.5)?(total_frame_cnt/total_time_usage):0);
4870 // time to uninit all, except global stuff:
4871 int uninitialize_parts = INITIALIZED_ALL;
4872 if (opts->fixed_vo)
4873 uninitialize_parts -= INITIALIZED_VO;
4874 if (opts->gapless_audio && mpctx->stop_play == AT_END_OF_FILE)
4875 uninitialize_parts -= INITIALIZED_AO;
4876 uninit_player(mpctx, uninitialize_parts);
4878 if(mpctx->set_of_sub_size > 0) {
4879 current_module="sub_free";
4880 for(i = 0; i < mpctx->set_of_sub_size; ++i) {
4881 sub_free(mpctx->set_of_subtitles[i]);
4882 #ifdef CONFIG_ASS
4883 if(mpctx->set_of_ass_tracks[i])
4884 ass_free_track( mpctx->set_of_ass_tracks[i] );
4885 #endif
4887 mpctx->set_of_sub_size = 0;
4889 mpctx->vo_sub_last = vo_sub=NULL;
4890 mpctx->subdata=NULL;
4891 #ifdef CONFIG_ASS
4892 mpctx->osd->ass_track = NULL;
4893 if(ass_library)
4894 ass_clear_fonts(ass_library);
4895 #endif
4897 if (!mpctx->stop_play) // In case some goto jumped here...
4898 mpctx->stop_play = PT_NEXT_ENTRY;
4900 int playtree_direction = 1;
4902 if(mpctx->stop_play == PT_NEXT_ENTRY || mpctx->stop_play == PT_PREV_ENTRY) {
4903 if(play_tree_iter_step(mpctx->playtree_iter,mpctx->play_tree_step,0) != PLAY_TREE_ITER_ENTRY) {
4904 play_tree_iter_free(mpctx->playtree_iter);
4905 mpctx->playtree_iter = NULL;
4907 mpctx->play_tree_step = 1;
4908 } else if(mpctx->stop_play == PT_UP_NEXT || mpctx->stop_play == PT_UP_PREV) {
4909 int direction = mpctx->stop_play == PT_UP_NEXT ? 1 : -1;
4910 if(mpctx->playtree_iter) {
4911 if(play_tree_iter_up_step(mpctx->playtree_iter,direction,0) != PLAY_TREE_ITER_ENTRY) {
4912 play_tree_iter_free(mpctx->playtree_iter);
4913 mpctx->playtree_iter = NULL;
4916 } else if (mpctx->stop_play == PT_STOP) {
4917 play_tree_iter_free(mpctx->playtree_iter);
4918 mpctx->playtree_iter = NULL;
4919 } else { // NEXT PREV SRC
4920 playtree_direction = mpctx->stop_play == PT_PREV_SRC ? -1 : 1;
4923 while(mpctx->playtree_iter != NULL) {
4924 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, playtree_direction);
4925 if(mpctx->filename == NULL) {
4926 if(play_tree_iter_step(mpctx->playtree_iter, playtree_direction, 0) != PLAY_TREE_ITER_ENTRY) {
4927 play_tree_iter_free(mpctx->playtree_iter);
4928 mpctx->playtree_iter = NULL;
4930 } else
4931 break;
4934 if (mpctx->playtree_iter != NULL || opts->player_idle_mode) {
4935 if(!mpctx->playtree_iter) mpctx->filename = NULL;
4936 mpctx->stop_play = 0;
4937 goto play_next_file;
4941 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4943 return 1;
4945 #endif /* DISABLE_MAIN */