build: Revert "codec-cfg.c: avoid including aviheader.h"
[mplayer.git] / mplayer.c
blob414f3c9023f0040cf0b87748b20f42764cdbee7f
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 unsigned width, height;
1134 spudec_free(vo_spudec);
1135 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
1136 vo_spudec = NULL;
1138 // we currently can't work without video stream
1139 if (!mpctx->sh_video)
1140 return;
1142 if (spudec_ifo) {
1143 unsigned int palette[16];
1144 current_module="spudec_init_vobsub";
1145 if (vobsub_parse_ifo(NULL,spudec_ifo, palette, &width, &height, 1, -1, NULL) >= 0)
1146 vo_spudec=spudec_new_scaled(palette, width, height, NULL, 0);
1149 width = mpctx->sh_video->disp_w;
1150 height = mpctx->sh_video->disp_h;
1152 #ifdef CONFIG_DVDREAD
1153 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVD) {
1154 current_module="spudec_init_dvdread";
1155 vo_spudec=spudec_new_scaled(((dvd_priv_t *)(mpctx->stream->priv))->cur_pgc->palette,
1156 width, height,
1157 NULL, 0);
1159 #endif
1161 #ifdef CONFIG_DVDNAV
1162 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVDNAV) {
1163 unsigned int *palette = mp_dvdnav_get_spu_clut(mpctx->stream);
1164 current_module="spudec_init_dvdnav";
1165 vo_spudec=spudec_new_scaled(palette, width, height, NULL, 0);
1167 #endif
1169 if (vo_spudec==NULL) {
1170 sh_sub_t *sh = mpctx->d_sub->sh;
1171 current_module="spudec_init_normal";
1172 vo_spudec=spudec_new_scaled(NULL, width, height, sh->extradata, sh->extradata_len);
1173 spudec_set_font_factor(vo_spudec,font_factor);
1176 if (vo_spudec!=NULL) {
1177 mpctx->initialized_flags|=INITIALIZED_SPUDEC;
1178 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
1183 * In Mac OS X the SDL-lib is built upon Cocoa. The easiest way to
1184 * make it all work is to use the builtin SDL-bootstrap code, which
1185 * will be done automatically by replacing our main() if we include SDL.h.
1187 #if defined(__APPLE__) && defined(CONFIG_SDL)
1188 #ifdef CONFIG_SDL_SDL_H
1189 #include <SDL/SDL.h>
1190 #else
1191 #include <SDL.h>
1192 #endif
1193 #endif
1196 * \brief append a formatted string
1197 * \param buf buffer to print into
1198 * \param pos position of terminating 0 in buf
1199 * \param len maximum number of characters in buf, not including terminating 0
1200 * \param format printf format string
1202 static void saddf(char *buf, unsigned *pos, int len, const char *format, ...)
1204 va_list va;
1205 va_start(va, format);
1206 *pos += vsnprintf(&buf[*pos], len - *pos, format, va);
1207 va_end(va);
1208 if (*pos >= len ) {
1209 buf[len] = 0;
1210 *pos = len;
1215 * \brief append time in the hh:mm:ss.f format
1216 * \param buf buffer to print into
1217 * \param pos position of terminating 0 in buf
1218 * \param len maximum number of characters in buf, not including terminating 0
1219 * \param time time value to convert/append
1221 static void sadd_hhmmssf(char *buf, unsigned *pos, int len, float time) {
1222 int64_t tenths = 10 * time;
1223 int f1 = tenths % 10;
1224 int ss = (tenths / 10) % 60;
1225 int mm = (tenths / 600) % 60;
1226 int hh = tenths / 36000;
1227 if (time <= 0) {
1228 saddf(buf, pos, len, "unknown");
1229 return;
1231 if (hh > 0)
1232 saddf(buf, pos, len, "%2d:", hh);
1233 if (hh > 0 || mm > 0)
1234 saddf(buf, pos, len, "%02d:", mm);
1235 saddf(buf, pos, len, "%02d.%1d", ss, f1);
1238 static void print_status(struct MPContext *mpctx, double a_pos, bool at_frame)
1240 struct MPOpts *opts = &mpctx->opts;
1241 sh_video_t * const sh_video = mpctx->sh_video;
1243 if (mpctx->sh_audio && a_pos == MP_NOPTS_VALUE)
1244 a_pos = playing_audio_pts(mpctx);
1245 if (mpctx->sh_audio && sh_video && at_frame) {
1246 mpctx->last_av_difference = a_pos - mpctx->video_pts - audio_delay;
1247 if (mpctx->time_frame > 0)
1248 mpctx->last_av_difference += mpctx->time_frame * opts->playback_speed;
1249 if (mpctx->last_av_difference > 0.5 && drop_frame_cnt > 50
1250 && !mpctx->drop_message_shown) {
1251 mp_tmsg(MSGT_AVSYNC,MSGL_WARN,SystemTooSlow);
1252 mpctx->drop_message_shown = true;
1255 if (opts->quiet)
1256 return;
1259 int width;
1260 char *line;
1261 unsigned pos = 0;
1262 get_screen_size();
1263 if (screen_width > 0)
1264 width = screen_width;
1265 else
1266 width = 80;
1267 #if defined(__MINGW32__) || defined(__CYGWIN__) || defined(__OS2__)
1268 /* Windows command line is broken (MinGW's rxvt works, but we
1269 * should not depend on that). */
1270 width--;
1271 #endif
1272 line = malloc(width + 1); // one additional char for the terminating null
1274 // Audio time
1275 if (mpctx->sh_audio) {
1276 saddf(line, &pos, width, "A:%6.1f ", a_pos);
1277 if (!sh_video) {
1278 float len = get_time_length(mpctx);
1279 saddf(line, &pos, width, "(");
1280 sadd_hhmmssf(line, &pos, width, a_pos);
1281 saddf(line, &pos, width, ") of %.1f (", len);
1282 sadd_hhmmssf(line, &pos, width, len);
1283 saddf(line, &pos, width, ") ");
1287 // Video time
1288 if (sh_video)
1289 saddf(line, &pos, width, "V:%6.1f ", mpctx->video_pts);
1291 // A-V sync
1292 if (mpctx->sh_audio && sh_video)
1293 saddf(line, &pos, width, "A-V:%7.3f ct:%7.3f ",
1294 mpctx->last_av_difference, mpctx->total_avsync_change);
1296 // Video stats
1297 if (sh_video)
1298 saddf(line, &pos, width, "%3d/%3d ",
1299 (int)sh_video->num_frames,
1300 (int)sh_video->num_frames_decoded);
1302 // CPU usage
1303 if (sh_video) {
1304 if (sh_video->timer > 0.5)
1305 saddf(line, &pos, width, "%2d%% %2d%% %4.1f%% ",
1306 (int)(100.0*video_time_usage*opts->playback_speed/(double)sh_video->timer),
1307 (int)(100.0*vout_time_usage*opts->playback_speed/(double)sh_video->timer),
1308 (100.0*audio_time_usage*opts->playback_speed/(double)sh_video->timer));
1309 else
1310 saddf(line, &pos, width, "??%% ??%% ??,?%% ");
1311 } else if (mpctx->sh_audio) {
1312 if (mpctx->delay > 0.5)
1313 saddf(line, &pos, width, "%4.1f%% ",
1314 100.0*audio_time_usage/(double)mpctx->delay);
1315 else
1316 saddf(line, &pos, width, "??,?%% ");
1319 // VO stats
1320 if (sh_video)
1321 saddf(line, &pos, width, "%d %d ", drop_frame_cnt, output_quality);
1323 #ifdef CONFIG_STREAM_CACHE
1324 // cache stats
1325 if (stream_cache_size > 0)
1326 saddf(line, &pos, width, "%d%% ", cache_fill_status(mpctx->stream));
1327 #endif
1329 // other
1330 if (opts->playback_speed != 1)
1331 saddf(line, &pos, width, "%4.2fx ", opts->playback_speed);
1333 // end
1334 if (erase_to_end_of_line) {
1335 line[pos] = 0;
1336 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s%s\r", line, erase_to_end_of_line);
1337 } else {
1338 memset(&line[pos], ' ', width - pos);
1339 line[width] = 0;
1340 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s\r", line);
1342 free(line);
1345 struct stream_dump_progress {
1346 uint64_t count;
1347 unsigned start_time;
1348 unsigned last_print_time;
1351 static void stream_dump_progress_start(struct stream_dump_progress *p)
1353 p->start_time = p->last_print_time = GetTimerMS();
1354 p->count = 0;
1357 static void stream_dump_progress(struct stream_dump_progress *p,
1358 uint64_t len, stream_t *stream)
1360 p->count += len;
1361 unsigned t = GetTimerMS();
1362 if (t - p->last_print_time < 1000)
1363 return;
1365 uint64_t start = stream->start_pos;
1366 uint64_t end = stream->end_pos;
1367 uint64_t pos = stream->pos;
1369 p->last_print_time = t;
1370 /* TODO: pretty print sizes; ETA */
1371 if (end > start && pos >= start && pos <= end) {
1372 mp_tmsg(MSGT_STATUSLINE, MSGL_STATUS,
1373 "dump: %"PRIu64" bytes written (~%.1f%%)",
1374 p->count, 100.0 * (pos - start) / (end - start));
1375 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "\r");
1376 } else {
1377 mp_tmsg(MSGT_STATUSLINE, MSGL_STATUS,
1378 "dump: %"PRIu64" bytes written", p->count);
1379 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "\r");
1383 static void stream_dump_progress_end(struct stream_dump_progress *p, char *name)
1385 mp_msg(MSGT_CPLAYER, MSGL_INFO, "dump: %"PRIu64" bytes written to '%s'.\n",
1386 p->count, name);
1390 * \brief build a chain of audio filters that converts the input format
1391 * to the ao's format, taking into account the current playback_speed.
1392 * sh_audio describes the requested input format of the chain.
1393 * ao describes the requested output format of the chain.
1395 static int build_afilter_chain(struct MPContext *mpctx)
1397 struct sh_audio *sh_audio = mpctx->sh_audio;
1398 struct ao *ao = mpctx->ao;
1399 struct MPOpts *opts = &mpctx->opts;
1400 int new_srate;
1401 int result;
1402 if (!sh_audio)
1404 mpctx->mixer.afilter = NULL;
1405 return 0;
1407 if(af_control_any_rev(sh_audio->afilter,
1408 AF_CONTROL_PLAYBACK_SPEED | AF_CONTROL_SET,
1409 &opts->playback_speed)) {
1410 new_srate = sh_audio->samplerate;
1411 } else {
1412 new_srate = sh_audio->samplerate * opts->playback_speed;
1413 if (new_srate != ao->samplerate) {
1414 // limits are taken from libaf/af_resample.c
1415 if (new_srate < 8000)
1416 new_srate = 8000;
1417 if (new_srate > 192000)
1418 new_srate = 192000;
1419 opts->playback_speed = (float)new_srate / (float)sh_audio->samplerate;
1422 result = init_audio_filters(sh_audio, new_srate,
1423 &ao->samplerate, &ao->channels, &ao->format);
1424 mpctx->mixer.afilter = sh_audio->afilter;
1425 return result;
1429 typedef struct mp_osd_msg mp_osd_msg_t;
1430 struct mp_osd_msg {
1431 /// Previous message on the stack.
1432 mp_osd_msg_t* prev;
1433 /// Message text.
1434 char msg[128];
1435 int id,level,started;
1436 /// Display duration in ms.
1437 unsigned time;
1440 /// OSD message stack.
1441 static mp_osd_msg_t* osd_msg_stack = NULL;
1444 * \brief Add a message on the OSD message stack
1446 * If a message with the same id is already present in the stack
1447 * it is pulled on top of the stack, otherwise a new message is created.
1450 static void set_osd_msg_va(int id, int level, int time, const char *fmt,
1451 va_list ap)
1453 mp_osd_msg_t *msg,*last=NULL;
1454 int r;
1456 // look if the id is already in the stack
1457 for(msg = osd_msg_stack ; msg && msg->id != id ;
1458 last = msg, msg = msg->prev);
1459 // not found: alloc it
1460 if(!msg) {
1461 msg = calloc(1,sizeof(mp_osd_msg_t));
1462 msg->prev = osd_msg_stack;
1463 osd_msg_stack = msg;
1464 } else if(last) { // found, but it's not on top of the stack
1465 last->prev = msg->prev;
1466 msg->prev = osd_msg_stack;
1467 osd_msg_stack = msg;
1469 // write the msg
1470 r = vsnprintf(msg->msg, 128, fmt, ap);
1471 if(r >= 128) msg->msg[127] = 0;
1472 // set id and time
1473 msg->id = id;
1474 msg->level = level;
1475 msg->time = time;
1479 void set_osd_msg(int id, int level, int time, const char *fmt, ...)
1481 va_list ap;
1482 va_start(ap, fmt);
1483 set_osd_msg_va(id, level, time, fmt, ap);
1484 va_end(ap);
1487 void set_osd_tmsg(int id, int level, int time, const char *fmt, ...)
1489 va_list ap;
1490 va_start(ap, fmt);
1491 set_osd_msg_va(id, level, time, mp_gtext(fmt), ap);
1492 va_end(ap);
1497 * \brief Remove a message from the OSD stack
1499 * This function can be used to get rid of a message right away.
1503 void rm_osd_msg(int id) {
1504 mp_osd_msg_t *msg,*last=NULL;
1506 // Search for the msg
1507 for(msg = osd_msg_stack ; msg && msg->id != id ;
1508 last = msg, msg = msg->prev);
1509 if(!msg) return;
1511 // Detach it from the stack and free it
1512 if(last)
1513 last->prev = msg->prev;
1514 else
1515 osd_msg_stack = msg->prev;
1516 free(msg);
1520 * \brief Remove all messages from the OSD stack
1524 static void clear_osd_msgs(void) {
1525 mp_osd_msg_t* msg = osd_msg_stack, *prev = NULL;
1526 while(msg) {
1527 prev = msg->prev;
1528 free(msg);
1529 msg = prev;
1531 osd_msg_stack = NULL;
1535 * \brief Get the current message from the OSD stack.
1537 * This function decrements the message timer and destroys the old ones.
1538 * The message that should be displayed is returned (if any).
1542 static mp_osd_msg_t* get_osd_msg(struct MPContext *mpctx)
1544 struct MPOpts *opts = &mpctx->opts;
1545 mp_osd_msg_t *msg,*prev,*last = NULL;
1546 static unsigned last_update = 0;
1547 unsigned now = GetTimerMS();
1548 unsigned diff;
1549 char hidden_dec_done = 0;
1551 if (mpctx->osd_visible) {
1552 // 36000000 means max timed visibility is 1 hour into the future, if
1553 // the difference is greater assume it's wrapped around from below 0
1554 if (mpctx->osd_visible - now > 36000000) {
1555 mpctx->osd_visible = 0;
1556 vo_osd_progbar_type = -1; // disable
1557 vo_osd_changed(OSDTYPE_PROGBAR);
1558 mpctx->osd_function = mpctx->paused ? OSD_PAUSE : OSD_PLAY;
1561 if (mpctx->osd_show_percentage_until - now > 36000000)
1562 mpctx->osd_show_percentage_until = 0;
1564 if(!last_update) last_update = now;
1565 diff = now >= last_update ? now - last_update : 0;
1567 last_update = now;
1569 // Look for the first message in the stack with high enough level.
1570 for(msg = osd_msg_stack ; msg ; last = msg, msg = prev) {
1571 prev = msg->prev;
1572 if (msg->level > opts->osd_level && hidden_dec_done)
1573 continue;
1574 // The message has a high enough level or it is the first hidden one
1575 // in both cases we decrement the timer or kill it.
1576 if(!msg->started || msg->time > diff) {
1577 if(msg->started) msg->time -= diff;
1578 else msg->started = 1;
1579 // display it
1580 if (msg->level <= opts->osd_level)
1581 return msg;
1582 hidden_dec_done = 1;
1583 continue;
1585 // kill the message
1586 free(msg);
1587 if(last) {
1588 last->prev = prev;
1589 msg = last;
1590 } else {
1591 osd_msg_stack = prev;
1592 msg = NULL;
1595 // Nothing found
1596 return NULL;
1600 * \brief Display the OSD bar.
1602 * Display the OSD bar or fall back on a simple message.
1606 void set_osd_bar(struct MPContext *mpctx, int type,const char* name,double min,double max,double val) {
1607 struct MPOpts *opts = &mpctx->opts;
1608 if (opts->osd_level < 1)
1609 return;
1611 if(mpctx->sh_video) {
1612 mpctx->osd_visible = (GetTimerMS() + 1000) | 1;
1613 vo_osd_progbar_type = type;
1614 vo_osd_progbar_value = 256*(val-min)/(max-min);
1615 vo_osd_changed(OSDTYPE_PROGBAR);
1616 return;
1619 set_osd_msg(OSD_MSG_BAR, 1, opts->osd_duration, "%s: %d %%",
1620 name, ROUND(100*(val-min)/(max-min)));
1624 * \brief Display text subtitles on the OSD
1626 void set_osd_subtitle(struct MPContext *mpctx, subtitle *subs)
1628 int i;
1629 vo_sub = subs;
1630 vo_osd_changed(OSDTYPE_SUBTITLE);
1631 if (!mpctx->sh_video) {
1632 // reverse order, since newest set_osd_msg is displayed first
1633 for (i = SUB_MAX_TEXT - 1; i >= 0; i--) {
1634 if (!subs || i >= subs->lines || !subs->text[i])
1635 rm_osd_msg(OSD_MSG_SUB_BASE + i);
1636 else {
1637 // HACK: currently display time for each sub line except the last is set to 2 seconds.
1638 int display_time = i == subs->lines - 1 ? 180000 : 2000;
1639 set_osd_msg(OSD_MSG_SUB_BASE + i, 1, display_time, "%s", subs->text[i]);
1646 * \brief Update the OSD message line.
1648 * This function displays the current message on the vo OSD or on the term.
1649 * If the stack is empty and the OSD level is high enough the timer
1650 * is displayed (only on the vo OSD).
1654 static void update_osd_msg(struct MPContext *mpctx)
1656 struct MPOpts *opts = &mpctx->opts;
1657 mp_osd_msg_t *msg;
1658 struct osd_state *osd = mpctx->osd;
1659 char osd_text_timer[128];
1661 if (mpctx->add_osd_seek_info) {
1662 double percentage = get_percent_pos(mpctx);
1663 set_osd_bar(mpctx, 0, "Position", 0, 100, percentage);
1664 if (mpctx->sh_video)
1665 mpctx->osd_show_percentage_until = (GetTimerMS() + 1000) | 1;
1666 mpctx->add_osd_seek_info = false;
1669 // Look if we have a msg
1670 if((msg = get_osd_msg(mpctx))) {
1671 if (strcmp(osd->osd_text, msg->msg)) {
1672 strncpy(osd->osd_text, msg->msg, 127);
1673 if(mpctx->sh_video) vo_osd_changed(OSDTYPE_OSD); else
1674 if(opts->term_osd)
1675 mp_msg(MSGT_CPLAYER,MSGL_STATUS, "%s%s\n", opts->term_osd_esc,
1676 msg->msg);
1678 return;
1681 if(mpctx->sh_video) {
1682 // fallback on the timer
1683 if (opts->osd_level >= 2) {
1684 int len = get_time_length(mpctx);
1685 int percentage = -1;
1686 char percentage_text[10];
1687 char fractions_text[4];
1688 double fpts = get_current_time(mpctx);
1689 int pts = fpts;
1691 if (mpctx->osd_show_percentage_until)
1692 percentage = get_percent_pos(mpctx);
1694 if (percentage >= 0)
1695 snprintf(percentage_text, 9, " (%d%%)", percentage);
1696 else
1697 percentage_text[0] = 0;
1699 if (opts->osd_fractions == 1) {
1700 //print fractions as sub-second timestamp
1701 snprintf(fractions_text, sizeof(fractions_text), ".%02d",
1702 (int)((fpts - pts) * 100));
1703 } else if (opts->osd_fractions == 2) {
1704 /* Print fractions by estimating the frame count within the
1705 * second.
1707 * Rounding or cutting off numbers after the decimal point
1708 * causes problems because of float's precision and movies
1709 * whose first frame is not exactly at timestamp 0. Therefore,
1710 * we add 0.2 and cut off at the decimal point, which proved
1711 * to be good heuristic.
1713 double fps = mpctx->sh_video->fps;
1714 if (fps <= 1 || fps > 99)
1715 strcpy(fractions_text, ".??");
1716 else
1717 snprintf(fractions_text, sizeof(fractions_text), ".%02d",
1718 (int) ( (fpts - pts) * fps + 0.2 ) );
1719 } else {
1720 //do not print fractions
1721 fractions_text[0] = 0;
1724 if (opts->osd_level == 3)
1725 snprintf(osd_text_timer, 63,
1726 "%c %02d:%02d:%02d%s / %02d:%02d:%02d%s",
1727 mpctx->osd_function,pts/3600,(pts/60)%60,pts%60,
1728 fractions_text, len/3600, (len/60)%60, len%60,
1729 percentage_text);
1730 else
1731 snprintf(osd_text_timer, 63, "%c %02d:%02d:%02d%s%s",
1732 mpctx->osd_function,pts/3600,(pts/60)%60,
1733 pts%60, fractions_text, percentage_text);
1734 } else
1735 osd_text_timer[0]=0;
1737 if (strcmp(osd->osd_text, osd_text_timer)) {
1738 strncpy(osd->osd_text, osd_text_timer, 63);
1739 vo_osd_changed(OSDTYPE_OSD);
1741 return;
1744 // Clear the term osd line
1745 if (opts->term_osd && osd->osd_text[0]) {
1746 osd->osd_text[0] = 0;
1747 printf("%s\n", opts->term_osd_esc);
1751 ///@}
1752 // OSDMsgStack
1755 void reinit_audio_chain(struct MPContext *mpctx)
1757 struct MPOpts *opts = &mpctx->opts;
1758 struct ao *ao;
1759 if (!mpctx->sh_audio)
1760 return;
1761 if (!(mpctx->initialized_flags & INITIALIZED_ACODEC)) {
1762 current_module="init_audio_codec";
1763 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1764 if(!init_best_audio_codec(mpctx->sh_audio,audio_codec_list,audio_fm_list)){
1765 goto init_error;
1767 mpctx->initialized_flags|=INITIALIZED_ACODEC;
1768 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1772 current_module="af_preinit";
1773 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1774 mpctx->initialized_flags |= INITIALIZED_AO;
1775 mpctx->ao = ao_create();
1776 mpctx->ao->samplerate = force_srate;
1777 mpctx->ao->format = opts->audio_output_format;
1779 ao = mpctx->ao;
1781 // first init to detect best values
1782 if(!init_audio_filters(mpctx->sh_audio, // preliminary init
1783 // input:
1784 mpctx->sh_audio->samplerate,
1785 // output:
1786 &ao->samplerate, &ao->channels, &ao->format)) {
1787 mp_tmsg(MSGT_CPLAYER,MSGL_ERR, "Error at audio filter chain "
1788 "pre-init!\n");
1789 exit_player(mpctx, EXIT_ERROR);
1791 if (!ao->initialized) {
1792 current_module="ao2_init";
1793 ao->buffersize = opts->ao_buffersize;
1794 ao_init(ao, opts->audio_driver_list);
1795 if (!ao->initialized) {
1796 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Could not open/initialize audio device -> no sound.\n");
1797 goto init_error;
1799 ao->buffer.start = talloc_new(ao);
1800 mp_msg(MSGT_CPLAYER,MSGL_INFO,"AO: [%s] %dHz %dch %s (%d bytes per sample)\n",
1801 ao->driver->info->short_name,
1802 ao->samplerate, ao->channels,
1803 af_fmt2str_short(ao->format),
1804 af_fmt2bits(ao->format)/8 );
1805 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Description: %s\nAO: Author: %s\n",
1806 ao->driver->info->name, ao->driver->info->author);
1807 if (strlen(ao->driver->info->comment) > 0)
1808 mp_msg(MSGT_CPLAYER, MSGL_V, "AO: Comment: %s\n",
1809 ao->driver->info->comment);
1812 // init audio filters:
1813 current_module="af_init";
1814 if (!build_afilter_chain(mpctx)) {
1815 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Couldn't find matching filter/ao format!\n");
1816 goto init_error;
1818 mpctx->mixer.ao = ao;
1819 mpctx->mixer.volstep = volstep;
1820 mpctx->syncing_audio = true;
1821 return;
1823 init_error:
1824 uninit_player(mpctx, INITIALIZED_ACODEC|INITIALIZED_AO); // close codec and possibly AO
1825 mpctx->sh_audio=mpctx->d_audio->sh=NULL; // -> nosound
1826 mpctx->d_audio->id = -2;
1830 ///@}
1831 // Command2Property
1834 // Return pts value corresponding to the end point of audio written to the
1835 // ao so far.
1836 static double written_audio_pts(struct MPContext *mpctx)
1838 sh_audio_t *sh_audio = mpctx->sh_audio;
1839 demux_stream_t *d_audio = mpctx->d_audio;
1840 // first calculate the end pts of audio that has been output by decoder
1841 double a_pts = sh_audio->pts;
1842 if (a_pts != MP_NOPTS_VALUE)
1843 // Good, decoder supports new way of calculating audio pts.
1844 // sh_audio->pts is the timestamp of the latest input packet with
1845 // known pts that the decoder has decoded. sh_audio->pts_bytes is
1846 // the amount of bytes the decoder has written after that timestamp.
1847 a_pts += sh_audio->pts_bytes / (double) sh_audio->o_bps;
1848 else {
1849 // Decoder doesn't support new way of calculating pts (or we're
1850 // being called before it has decoded anything with known timestamp).
1851 // Use the old method of audio pts calculation: take the timestamp
1852 // of last packet with known pts the decoder has read data from,
1853 // and add amount of bytes read after the beginning of that packet
1854 // divided by input bps. This will be inaccurate if the input/output
1855 // ratio is not constant for every audio packet or if it is constant
1856 // but not accurately known in sh_audio->i_bps.
1858 a_pts = d_audio->pts;
1859 // ds_tell_pts returns bytes read after last timestamp from
1860 // demuxing layer, decoder might use sh_audio->a_in_buffer for bytes
1861 // it has read but not decoded
1862 if (sh_audio->i_bps)
1863 a_pts += (ds_tell_pts(d_audio) - sh_audio->a_in_buffer_len) /
1864 (double)sh_audio->i_bps;
1866 // Now a_pts hopefully holds the pts for end of audio from decoder.
1867 // Substract data in buffers between decoder and audio out.
1869 // Decoded but not filtered
1870 a_pts -= sh_audio->a_buffer_len / (double)sh_audio->o_bps;
1872 // Data buffered in audio filters, measured in bytes of "missing" output
1873 double buffered_output = af_calc_delay(sh_audio->afilter);
1875 // Data that was ready for ao but was buffered because ao didn't fully
1876 // accept everything to internal buffers yet
1877 buffered_output += mpctx->ao->buffer.len;
1879 // Filters divide audio length by playback_speed, so multiply by it
1880 // to get the length in original units without speedup or slowdown
1881 a_pts -= buffered_output * mpctx->opts.playback_speed / mpctx->ao->bps;
1883 return a_pts + mpctx->video_offset;
1886 // Return pts value corresponding to currently playing audio.
1887 double playing_audio_pts(struct MPContext *mpctx)
1889 return written_audio_pts(mpctx) - mpctx->opts.playback_speed *
1890 ao_get_delay(mpctx->ao);
1893 static bool is_av_sub(int type)
1895 return type == 'b' || type == 'p' || type == 'x';
1898 void update_subtitles(struct MPContext *mpctx, double refpts,
1899 double sub_offset, bool reset)
1901 struct MPOpts *opts = &mpctx->opts;
1902 struct sh_video *sh_video = mpctx->sh_video;
1903 struct demux_stream *d_sub = mpctx->d_sub;
1904 double curpts = refpts + sub_delay;
1905 unsigned char *packet=NULL;
1906 int len;
1907 struct sh_sub *sh_sub = d_sub->sh;
1908 int type = sh_sub ? sh_sub->type : 'v';
1909 static subtitle subs;
1910 if (reset) {
1911 if (sh_sub)
1912 sub_reset(sh_sub, mpctx->osd);
1913 sub_clear_text(&subs, MP_NOPTS_VALUE);
1914 if (vo_sub)
1915 set_osd_subtitle(mpctx, NULL);
1916 if (vo_spudec) {
1917 spudec_reset(vo_spudec);
1918 vo_osd_changed(OSDTYPE_SPU);
1920 #ifdef CONFIG_FFMPEG
1921 if (is_av_sub(type))
1922 reset_avsub(sh_sub);
1923 #endif
1924 return;
1926 // find sub
1927 if (mpctx->subdata) {
1928 if (sub_fps==0) sub_fps = sh_video ? sh_video->fps : 25;
1929 current_module = "find_sub";
1930 find_sub(mpctx, mpctx->subdata, curpts *
1931 (mpctx->subdata->sub_uses_time ? 100. : sub_fps));
1932 if (vo_sub)
1933 mpctx->vo_sub_last = vo_sub;
1936 // DVD sub:
1937 if (vobsub_id >= 0 || type == 'v') {
1938 int timestamp;
1939 current_module = "spudec";
1940 /* Get a sub packet from the DVD or a vobsub */
1941 while(1) {
1942 // Vobsub
1943 len = 0;
1944 if (vo_vobsub) {
1945 if (curpts >= 0) {
1946 len = vobsub_get_packet(vo_vobsub, curpts,
1947 (void**)&packet, &timestamp);
1948 if (len > 0) {
1949 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);
1952 } else {
1953 // DVD sub
1954 len = ds_get_packet_sub(d_sub, (unsigned char**)&packet);
1955 if (len > 0) {
1956 // XXX This is wrong, sh_video->pts can be arbitrarily
1957 // much behind demuxing position. Unfortunately using
1958 // d_video->pts which would have been the simplest
1959 // improvement doesn't work because mpeg specific hacks
1960 // in video.c set d_video->pts to 0.
1961 float x = d_sub->pts - refpts;
1962 if (x > -20 && x < 20) // prevent missing subs on pts reset
1963 timestamp = 90000*d_sub->pts;
1964 else timestamp = 90000*curpts;
1965 mp_dbg(MSGT_CPLAYER, MSGL_V, "\rDVD sub: len=%d "
1966 "v_pts=%5.3f s_pts=%5.3f ts=%d \n", len,
1967 refpts, d_sub->pts, timestamp);
1970 if (len<=0 || !packet) break;
1971 // create it only here, since with some broken demuxers we might
1972 // type = v but no DVD sub and we currently do not change the
1973 // "original frame size" ever after init, leading to wrong-sized
1974 // PGS subtitles.
1975 if (!vo_spudec)
1976 vo_spudec = spudec_new(NULL);
1977 if (vo_vobsub || timestamp >= 0)
1978 spudec_assemble(vo_spudec, packet, len, timestamp);
1980 } else if (is_text_sub(type) || is_av_sub(type) || type == 'd') {
1981 if (type == 'd' && !d_sub->demuxer->teletext) {
1982 tt_stream_props tsp = {0};
1983 void *ptr = &tsp;
1984 if (teletext_control(NULL, TV_VBI_CONTROL_START, &ptr) == VBI_CONTROL_TRUE)
1985 d_sub->demuxer->teletext = ptr;
1987 if (d_sub->non_interleaved)
1988 ds_get_next_pts(d_sub);
1990 while (d_sub->first) {
1991 double subpts = ds_get_next_pts(d_sub) + sub_offset;
1992 if (subpts > curpts) {
1993 // Libass handled subs can be fed to it in advance
1994 if (!opts->ass_enabled || !is_text_sub(type))
1995 break;
1996 // Try to avoid demuxing whole file at once
1997 if (d_sub->non_interleaved && subpts > curpts + 1)
1998 break;
2000 double duration = d_sub->first->duration;
2001 len = ds_get_packet_sub(d_sub, &packet);
2002 if (is_av_sub(type)) {
2003 #ifdef CONFIG_FFMPEG
2004 int ret = decode_avsub(sh_sub, packet, len, subpts, duration);
2005 if (ret < 0)
2006 mp_msg(MSGT_SPUDEC, MSGL_WARN, "lavc failed decoding "
2007 "subtitle\n");
2008 #endif
2009 continue;
2011 if (type == 'm') {
2012 if (len < 2) continue;
2013 len = FFMIN(len - 2, AV_RB16(packet));
2014 packet += 2;
2016 if (type == 'd') {
2017 if (d_sub->demuxer->teletext) {
2018 uint8_t *p = packet;
2019 p++;
2020 len--;
2021 while (len >= 46) {
2022 int sublen = p[1];
2023 if (p[0] == 2 || p[0] == 3)
2024 teletext_control(d_sub->demuxer->teletext,
2025 TV_VBI_CONTROL_DECODE_DVB, p + 2);
2026 p += sublen + 2;
2027 len -= sublen + 2;
2030 continue;
2032 if (sh_sub && sh_sub->active) {
2033 sub_decode(sh_sub, mpctx->osd, packet, len, subpts, duration);
2034 continue;
2036 if (subpts != MP_NOPTS_VALUE) {
2037 if (duration < 0)
2038 sub_clear_text(&subs, MP_NOPTS_VALUE);
2039 if (type == 'a') { // ssa/ass subs without libass => convert to plaintext
2040 int i;
2041 unsigned char* p = packet;
2042 for (i=0; i < 8 && *p != '\0'; p++)
2043 if (*p == ',')
2044 i++;
2045 if (*p == '\0') /* Broken line? */
2046 continue;
2047 len -= p - packet;
2048 packet = p;
2050 double endpts = MP_NOPTS_VALUE;
2051 if (subpts != MP_NOPTS_VALUE && duration >= 0)
2052 endpts = subpts + duration;
2053 sub_add_text(&subs, packet, len, endpts);
2054 set_osd_subtitle(mpctx, &subs);
2056 if (d_sub->non_interleaved)
2057 ds_get_next_pts(d_sub);
2059 if (!opts->ass_enabled)
2060 if (sub_clear_text(&subs, curpts))
2061 set_osd_subtitle(mpctx, &subs);
2063 if (vo_spudec) {
2064 spudec_heartbeat(vo_spudec, 90000*curpts);
2065 if (spudec_changed(vo_spudec))
2066 vo_osd_changed(OSDTYPE_SPU);
2069 current_module=NULL;
2072 static void update_teletext(sh_video_t *sh_video, demuxer_t *demuxer, int reset)
2074 int page_changed;
2076 if (!demuxer->teletext)
2077 return;
2079 //Also forcing page update when such ioctl is not supported or call error occured
2080 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_IS_CHANGED,&page_changed)!=VBI_CONTROL_TRUE)
2081 page_changed=1;
2083 if(!page_changed)
2084 return;
2086 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_GET_VBIPAGE,&vo_osd_teletext_page)!=VBI_CONTROL_TRUE)
2087 vo_osd_teletext_page=NULL;
2088 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_GET_HALF_PAGE,&vo_osd_teletext_half)!=VBI_CONTROL_TRUE)
2089 vo_osd_teletext_half=0;
2090 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_GET_MODE,&vo_osd_teletext_mode)!=VBI_CONTROL_TRUE)
2091 vo_osd_teletext_mode=0;
2092 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_GET_FORMAT,&vo_osd_teletext_format)!=VBI_CONTROL_TRUE)
2093 vo_osd_teletext_format=0;
2094 vo_osd_changed(OSDTYPE_TELETEXT);
2096 teletext_control(demuxer->teletext,TV_VBI_CONTROL_MARK_UNCHANGED,NULL);
2099 static int check_framedrop(struct MPContext *mpctx, double frame_time) {
2100 struct MPOpts *opts = &mpctx->opts;
2101 // check for frame-drop:
2102 current_module = "check_framedrop";
2103 if (mpctx->sh_audio && !mpctx->ao->untimed && !mpctx->d_audio->eof) {
2104 static int dropped_frames;
2105 float delay = opts->playback_speed * ao_get_delay(mpctx->ao);
2106 float d = delay-mpctx->delay;
2107 ++total_frame_cnt;
2108 // we should avoid dropping too many frames in sequence unless we
2109 // are too late. and we allow 100ms A-V delay here:
2110 if (d < -dropped_frames*frame_time-0.100 && !mpctx->paused
2111 && !mpctx->restart_playback) {
2112 ++drop_frame_cnt;
2113 ++dropped_frames;
2114 return frame_dropping;
2115 } else
2116 dropped_frames = 0;
2118 return 0;
2122 #ifdef HAVE_RTC
2123 int rtc_fd = -1;
2124 #endif
2126 static float timing_sleep(struct MPContext *mpctx, float time_frame)
2128 #ifdef HAVE_RTC
2129 if (rtc_fd >= 0){
2130 // -------- RTC -----------
2131 current_module="sleep_rtc";
2132 while (time_frame > 0.000) {
2133 unsigned long rtc_ts;
2134 if (read(rtc_fd, &rtc_ts, sizeof(rtc_ts)) <= 0)
2135 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC read error: %s\n", strerror(errno));
2136 time_frame -= get_relative_time(mpctx);
2138 } else
2139 #endif
2141 // assume kernel HZ=100 for softsleep, works with larger HZ but with
2142 // unnecessarily high CPU usage
2143 struct MPOpts *opts = &mpctx->opts;
2144 float margin = opts->softsleep ? 0.011 : 0;
2145 current_module = "sleep_timer";
2146 while (time_frame > margin) {
2147 usec_sleep(1000000 * (time_frame - margin));
2148 time_frame -= get_relative_time(mpctx);
2150 if (opts->softsleep){
2151 current_module = "sleep_soft";
2152 if (time_frame < 0)
2153 mp_tmsg(MSGT_AVSYNC, MSGL_WARN, "Warning! Softsleep underflow!\n");
2154 while (time_frame > 0)
2155 time_frame -= get_relative_time(mpctx); // burn the CPU
2158 return time_frame;
2161 static int select_subtitle(MPContext *mpctx)
2163 struct MPOpts *opts = &mpctx->opts;
2164 // find the best sub to use
2165 int id;
2166 int found = 0;
2167 mpctx->global_sub_pos = -1; // no subs by default
2168 if (vobsub_id >= 0) {
2169 // if user asks for a vobsub id, use that first.
2170 id = vobsub_id;
2171 found = mp_property_do("sub_vob", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
2174 if (!found && opts->sub_id >= 0) {
2175 // if user asks for a dvd sub id, use that next.
2176 id = opts->sub_id;
2177 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
2180 if (!found) {
2181 // if there are text subs to use, use those. (autosubs come last here)
2182 id = 0;
2183 found = mp_property_do("sub_file", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
2186 if (!found && opts->sub_id == -1) {
2187 // finally select subs by language and container hints
2188 if (opts->sub_id == -1)
2189 opts->sub_id =
2190 demuxer_sub_track_by_lang_and_default(mpctx->d_sub->demuxer,
2191 opts->sub_lang);
2192 if (opts->sub_id >= 0) {
2193 id = opts->sub_id;
2194 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
2197 return found;
2200 #ifdef CONFIG_DVDNAV
2201 #ifndef FF_B_TYPE
2202 #define FF_B_TYPE 3
2203 #endif
2204 /// store decoded video image
2205 static mp_image_t * mp_dvdnav_copy_mpi(mp_image_t *to_mpi,
2206 mp_image_t *from_mpi) {
2207 mp_image_t *mpi;
2209 /// Do not store B-frames
2210 if (from_mpi->pict_type == FF_B_TYPE)
2211 return to_mpi;
2213 if (to_mpi &&
2214 to_mpi->w == from_mpi->w &&
2215 to_mpi->h == from_mpi->h &&
2216 to_mpi->imgfmt == from_mpi->imgfmt)
2217 mpi = to_mpi;
2218 else {
2219 if (to_mpi)
2220 free_mp_image(to_mpi);
2221 if (from_mpi->w == 0 || from_mpi->h == 0)
2222 return NULL;
2223 mpi = alloc_mpi(from_mpi->w,from_mpi->h,from_mpi->imgfmt);
2226 copy_mpi(mpi,from_mpi);
2227 return mpi;
2230 static void mp_dvdnav_reset_stream (MPContext *ctx) {
2231 struct MPOpts *opts = &ctx->opts;
2232 if (ctx->sh_video) {
2233 /// clear video pts
2234 ctx->d_video->pts = 0.0f;
2235 ctx->sh_video->pts = 0.0f;
2236 ctx->sh_video->i_pts = 0.0f;
2237 ctx->sh_video->last_pts = 0.0f;
2238 ctx->sh_video->num_buffered_pts = 0;
2239 ctx->sh_video->num_frames = 0;
2240 ctx->sh_video->num_frames_decoded = 0;
2241 ctx->sh_video->timer = 0.0f;
2242 ctx->sh_video->stream_delay = 0.0f;
2243 ctx->sh_video->timer = 0;
2244 ctx->demuxer->stream_pts = MP_NOPTS_VALUE;
2247 if (ctx->sh_audio) {
2248 /// free audio packets and reset
2249 ds_free_packs(ctx->d_audio);
2250 audio_delay -= ctx->sh_audio->stream_delay;
2251 ctx->delay =- audio_delay;
2252 ao_reset(ctx->ao);
2253 resync_audio_stream(ctx->sh_audio);
2256 audio_delay = 0.0f;
2257 ctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(ctx->stream);
2258 if (opts->sub_lang && opts->sub_id == dvdsub_lang_id) {
2259 dvdsub_lang_id = mp_dvdnav_sid_from_lang(ctx->stream, opts->sub_lang);
2260 if (dvdsub_lang_id != opts->sub_id) {
2261 opts->sub_id = dvdsub_lang_id;
2262 select_subtitle(ctx);
2266 /// clear all EOF related flags
2267 ctx->d_video->eof = ctx->d_audio->eof = ctx->stream->eof = 0;
2270 /// Restore last decoded DVDNAV (still frame)
2271 static mp_image_t *mp_dvdnav_restore_smpi(struct MPContext *mpctx,
2272 int *in_size,
2273 unsigned char **start,
2274 mp_image_t *decoded_frame)
2276 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2277 return decoded_frame;
2279 /// a change occurred in dvdnav stream
2280 if (mp_dvdnav_cell_has_changed(mpctx->stream,0)) {
2281 mp_dvdnav_read_wait(mpctx->stream, 1, 1);
2282 mp_dvdnav_context_free(mpctx);
2283 mp_dvdnav_reset_stream(mpctx);
2284 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
2285 mp_dvdnav_cell_has_changed(mpctx->stream,1);
2288 if (*in_size < 0) {
2289 float len;
2291 /// Display still frame, if any
2292 if (mpctx->nav_smpi && !mpctx->nav_buffer)
2293 decoded_frame = mpctx->nav_smpi;
2295 /// increment video frame : continue playing after still frame
2296 len = get_time_length(mpctx);
2297 if (mpctx->sh_video->pts >= len &&
2298 mpctx->sh_video->pts > 0.0 && len > 0.0) {
2299 mp_dvdnav_skip_still(mpctx->stream);
2300 mp_dvdnav_skip_wait(mpctx->stream);
2302 mpctx->sh_video->pts += 1 / mpctx->sh_video->fps;
2304 if (mpctx->nav_buffer) {
2305 *start = mpctx->nav_start;
2306 *in_size = mpctx->nav_in_size;
2307 if (mpctx->nav_start)
2308 memcpy(*start,mpctx->nav_buffer,mpctx->nav_in_size);
2312 return decoded_frame;
2315 /// Save last decoded DVDNAV (still frame)
2316 static void mp_dvdnav_save_smpi(struct MPContext *mpctx, int in_size,
2317 unsigned char *start,
2318 mp_image_t *decoded_frame)
2320 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2321 return;
2323 free(mpctx->nav_buffer);
2324 mpctx->nav_buffer = NULL;
2325 mpctx->nav_start = NULL;
2326 mpctx->nav_in_size = -1;
2328 if (in_size > 0)
2329 mpctx->nav_buffer = malloc(in_size);
2330 if (mpctx->nav_buffer) {
2331 mpctx->nav_start = start;
2332 memcpy(mpctx->nav_buffer,start,in_size);
2335 if (decoded_frame && mpctx->nav_smpi != decoded_frame)
2336 mpctx->nav_smpi = mp_dvdnav_copy_mpi(mpctx->nav_smpi,decoded_frame);
2338 #endif /* CONFIG_DVDNAV */
2340 /* Modify video timing to match the audio timeline. There are two main
2341 * reasons this is needed. First, video and audio can start from different
2342 * positions at beginning of file or after a seek (MPlayer starts both
2343 * immediately even if they have different pts). Second, the file can have
2344 * audio timestamps that are inconsistent with the duration of the audio
2345 * packets, for example two consecutive timestamp values differing by
2346 * one second but only a packet with enough samples for half a second
2347 * of playback between them.
2349 static void adjust_sync(struct MPContext *mpctx, double frame_time)
2351 current_module = "av_sync";
2353 if (!mpctx->sh_audio || mpctx->syncing_audio)
2354 return;
2356 double a_pts = written_audio_pts(mpctx) - mpctx->delay;
2357 double v_pts = mpctx->sh_video->pts;
2358 double av_delay = a_pts - v_pts;
2359 // Try to sync vo_flip() so it will *finish* at given time
2360 av_delay += mpctx->last_vo_flip_duration;
2361 av_delay -= audio_delay; // This much pts difference is desired
2363 double change = av_delay * 0.1;
2364 double max_change = default_max_pts_correction >= 0 ?
2365 default_max_pts_correction : frame_time * 0.1;
2366 if (change < -max_change)
2367 change = -max_change;
2368 else if (change > max_change)
2369 change = max_change;
2370 mpctx->delay += change;
2371 mpctx->total_avsync_change += change;
2374 #define ASYNC_PLAY_DONE -3
2375 static int audio_start_sync(struct MPContext *mpctx, int playsize)
2377 struct ao *ao = mpctx->ao;
2378 struct MPOpts *opts = &mpctx->opts;
2379 sh_audio_t * const sh_audio = mpctx->sh_audio;
2380 int res;
2382 // Timing info may not be set without
2383 res = decode_audio(sh_audio, &ao->buffer, 1);
2384 if (res < 0)
2385 return res;
2387 int bytes;
2388 bool did_retry = false;
2389 while (1) {
2390 double written_pts = written_audio_pts(mpctx);
2391 double ptsdiff = written_pts - mpctx->video_pts - mpctx->delay
2392 - audio_delay;
2393 bytes = ptsdiff * ao->bps / mpctx->opts.playback_speed;
2394 bytes -= bytes % (ao->channels * af_fmt2bits(ao->format) / 8);
2396 // ogg demuxers give packets without timing
2397 if (written_pts <= 1 && sh_audio->pts == MP_NOPTS_VALUE) {
2398 if (!did_retry) {
2399 // Try to read more data to see packets that have pts
2400 int res = decode_audio(sh_audio, &ao->buffer, ao->bps);
2401 if (res < 0)
2402 return res;
2403 did_retry = true;
2404 continue;
2406 bytes = 0;
2409 if (fabs(ptsdiff) > 300) // pts reset or just broken?
2410 bytes = 0;
2412 if (bytes > 0)
2413 break;
2415 mpctx->syncing_audio = false;
2416 int a = FFMIN(-bytes, FFMAX(playsize, 20000));
2417 int res = decode_audio(sh_audio, &ao->buffer, a);
2418 bytes += ao->buffer.len;
2419 if (bytes >= 0) {
2420 memmove(ao->buffer.start,
2421 ao->buffer.start + ao->buffer.len - bytes, bytes);
2422 ao->buffer.len = bytes;
2423 if (res < 0)
2424 return res;
2425 return decode_audio(sh_audio, &ao->buffer, playsize);
2427 ao->buffer.len = 0;
2428 if (res < 0)
2429 return res;
2431 int fillbyte = 0;
2432 if ((ao->format & AF_FORMAT_SIGN_MASK) == AF_FORMAT_US)
2433 fillbyte = 0x80;
2434 if (bytes >= playsize) {
2435 /* This case could fall back to the one below with
2436 * bytes = playsize, but then silence would keep accumulating
2437 * in a_out_buffer if the AO accepts less data than it asks for
2438 * in playsize. */
2439 char *p = malloc(playsize);
2440 memset(p, fillbyte, playsize);
2441 playsize = ao_play(ao, p, playsize, 0);
2442 free(p);
2443 mpctx->delay += opts->playback_speed*playsize/(double)ao->bps;
2444 return ASYNC_PLAY_DONE;
2446 mpctx->syncing_audio = false;
2447 decode_audio_prepend_bytes(&ao->buffer, bytes, fillbyte);
2448 return decode_audio(sh_audio, &ao->buffer, playsize);
2451 static int fill_audio_out_buffers(struct MPContext *mpctx)
2453 struct MPOpts *opts = &mpctx->opts;
2454 struct ao *ao = mpctx->ao;
2455 unsigned int t;
2456 double tt;
2457 int playsize;
2458 int playflags=0;
2459 bool audio_eof = false;
2460 bool partial_fill = false;
2461 sh_audio_t * const sh_audio = mpctx->sh_audio;
2462 bool modifiable_audio_format = !(ao->format & AF_FORMAT_SPECIAL_MASK);
2463 int unitsize = ao->channels * af_fmt2bits(ao->format) / 8;
2465 current_module="play_audio";
2467 if (ao->untimed && mpctx->sh_video && mpctx->delay > 0)
2468 return 0;
2470 // all the current uses of ao->pts seem to be in aos that handle
2471 // sync completely wrong; there should be no need to use ao->pts
2472 // in get_space()
2473 ao->pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2474 playsize = ao_get_space(ao);
2476 // Fill buffer if needed:
2477 current_module="decode_audio";
2478 t = GetTimer();
2480 if (!opts->initial_audio_sync || !modifiable_audio_format)
2481 mpctx->syncing_audio = false;
2483 int res;
2484 if (mpctx->syncing_audio && mpctx->sh_video)
2485 res = audio_start_sync(mpctx, playsize);
2486 else
2487 res = decode_audio(sh_audio, &ao->buffer, playsize);
2488 if (res < 0) { // EOF, error or format change
2489 if (res == -2) {
2490 /* The format change isn't handled too gracefully. A more precise
2491 * implementation would require draining buffered old-format audio
2492 * while displaying video, then doing the output format switch.
2494 uninit_player(mpctx, INITIALIZED_AO);
2495 reinit_audio_chain(mpctx);
2496 return -1;
2497 } else if (res == ASYNC_PLAY_DONE)
2498 return 0;
2499 else if (mpctx->d_audio->eof)
2500 audio_eof = true;
2502 t = GetTimer() - t;
2503 tt = t*0.000001f; audio_time_usage+=tt;
2504 if (mpctx->timeline && modifiable_audio_format) {
2505 double endpts = mpctx->timeline[mpctx->timeline_part + 1].start;
2506 double bytes = (endpts - written_audio_pts(mpctx) + audio_delay)
2507 * ao->bps / opts->playback_speed;
2508 if (playsize > bytes) {
2509 playsize = FFMAX(bytes, 0);
2510 playflags |= AOPLAY_FINAL_CHUNK;
2511 audio_eof = true;
2512 partial_fill = true;
2516 assert(ao->buffer.len % unitsize == 0);
2517 if (playsize > ao->buffer.len) {
2518 partial_fill = true;
2519 playsize = ao->buffer.len;
2520 if (audio_eof)
2521 playflags |= AOPLAY_FINAL_CHUNK;
2523 playsize -= playsize % unitsize;
2524 if (!playsize)
2525 return partial_fill && audio_eof ? -2 : -partial_fill;
2527 // play audio:
2528 current_module="play_audio";
2530 // Is this pts value actually useful for the aos that access it?
2531 // They're obviously badly broken in the way they handle av sync;
2532 // would not having access to this make them more broken?
2533 ao->pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2534 int played = ao_play(ao, ao->buffer.start, playsize, playflags);
2535 assert(played % unitsize == 0);
2536 ao->buffer_playable_size = playsize - played;
2538 if (played > 0) {
2539 ao->buffer.len -= played;
2540 memmove(ao->buffer.start, ao->buffer.start + played, ao->buffer.len);
2541 mpctx->delay += opts->playback_speed * played / ao->bps;
2542 } else if (audio_eof && ao_get_delay(ao) < .04) {
2543 // Sanity check to avoid hanging in case current ao doesn't output
2544 // partial chunks and doesn't check for AOPLAY_FINAL_CHUNK
2545 return -2;
2548 return -partial_fill;
2551 static int sleep_until_near_frame(struct MPContext *mpctx, float *time_frame,
2552 bool sync_to_audio, float *aq_sleep_time)
2554 struct MPOpts *opts = &mpctx->opts;
2555 double audio_limit = 2;
2556 current_module="calc_sleep_time";
2558 if (mpctx->restart_playback)
2559 return 0;
2561 *time_frame -= get_relative_time(mpctx); // reset timer
2563 if (sync_to_audio) {
2564 float delay = ao_get_delay(mpctx->ao);
2565 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "delay=%f\n", delay);
2567 if (opts->autosync) {
2569 * Adjust this raw delay value by calculating the expected
2570 * delay for this frame and generating a new value which is
2571 * weighted between the two. The higher autosync is, the
2572 * closer to the delay value gets to that which "-nosound"
2573 * would have used, and the longer it will take for A/V
2574 * sync to settle at the right value (but it eventually will.)
2575 * This settling time is very short for values below 100.
2577 float predicted = mpctx->delay / opts->playback_speed + *time_frame;
2578 float difference = delay - predicted;
2579 delay = predicted + difference / (float)opts->autosync;
2582 *time_frame = delay - mpctx->delay / opts->playback_speed;
2584 // delay = amount of audio buffered in soundcard/driver
2585 delay = FFMIN(delay, 0.5);
2586 delay = FFMAX(delay, 0.1);
2587 audio_limit = delay;
2588 } else {
2589 // If we're lagging more than 200 ms behind the right playback rate,
2590 // don't try to "catch up".
2591 // If benchmark is set always output frames as fast as possible
2592 // without sleeping.
2593 if (*time_frame < -0.2 || opts->benchmark)
2594 *time_frame = 0;
2597 double t = *time_frame - mpctx->video_out->flip_queue_offset;
2599 if (t <= 0.05)
2600 return 0;
2602 t -= 0.05;
2603 if (t > audio_limit * 0.6)
2604 t = audio_limit * 0.5;
2605 *aq_sleep_time += t;
2606 mp_input_get_cmd(mpctx->input, t * 1000 + 1, 1);
2607 return 1;
2610 int reinit_video_chain(struct MPContext *mpctx)
2612 struct MPOpts *opts = &mpctx->opts;
2613 sh_video_t * const sh_video = mpctx->sh_video;
2614 if (!sh_video)
2615 return 0;
2616 double ar=-1.0;
2617 //================== Init VIDEO (codec & libvo) ==========================
2618 if (!opts->fixed_vo || !(mpctx->initialized_flags & INITIALIZED_VO)) {
2619 current_module="preinit_libvo";
2621 //shouldn't we set dvideo->id=-2 when we fail?
2622 //if((mpctx->video_out->preinit(vo_subdevice))!=0){
2623 if(!(mpctx->video_out=init_best_video_out(opts, mpctx->x11_state, mpctx->key_fifo, mpctx->input))){
2624 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Error opening/initializing the selected video_out (-vo) device.\n");
2625 goto err_out;
2627 mpctx->initialized_flags|=INITIALIZED_VO;
2630 if(stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_ASPECT_RATIO, &ar) != STREAM_UNSUPPORTED)
2631 mpctx->sh_video->stream_aspect = ar;
2632 current_module="init_video_filters";
2634 char* vf_arg[] = { "_oldargs_", (char*)mpctx->video_out , NULL };
2635 sh_video->vfilter = vf_open_filter(opts, NULL,"vo",vf_arg);
2637 #ifdef CONFIG_MENU
2638 if(use_menu) {
2639 char* vf_arg[] = { "_oldargs_", menu_root, NULL };
2640 vf_menu = vf_open_plugin(opts,libmenu_vfs,sh_video->vfilter,"menu",vf_arg);
2641 if(!vf_menu) {
2642 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Can't open libmenu video filter with root menu %s.\n",menu_root);
2643 use_menu = 0;
2646 if(vf_menu)
2647 sh_video->vfilter = vf_menu;
2648 #endif
2650 #ifdef CONFIG_ASS
2651 if(opts->ass_enabled) {
2652 int i;
2653 int insert = 1;
2654 if (opts->vf_settings)
2655 for (i = 0; opts->vf_settings[i].name; ++i)
2656 if (strcmp(opts->vf_settings[i].name, "ass") == 0) {
2657 insert = 0;
2658 break;
2660 if (insert) {
2661 extern vf_info_t vf_info_ass;
2662 const vf_info_t* libass_vfs[] = {&vf_info_ass, NULL};
2663 char* vf_arg[] = {"auto", "1", NULL};
2664 int retcode = 0;
2665 struct vf_instance *vf_ass = vf_open_plugin_noerr(opts, libass_vfs,
2666 sh_video->vfilter,
2667 "ass", vf_arg,
2668 &retcode);
2669 if (vf_ass)
2670 sh_video->vfilter = vf_ass;
2671 else if (retcode == -1) // vf_ass open() returns -1 if there's VO EOSD
2672 mp_msg(MSGT_CPLAYER, MSGL_V, "[ass] vf_ass not needed\n");
2673 else
2674 mp_msg(MSGT_CPLAYER,MSGL_ERR, "ASS: cannot add video filter\n");
2677 #endif
2679 sh_video->vfilter = append_filters(sh_video->vfilter, opts->vf_settings);
2681 #ifdef CONFIG_ASS
2682 if (opts->ass_enabled)
2683 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_INIT_EOSD, ass_library);
2684 #endif
2686 current_module="init_video_codec";
2688 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2689 init_best_video_codec(sh_video,video_codec_list,video_fm_list);
2690 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2692 if(!sh_video->initialized){
2693 if(!opts->fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
2694 goto err_out;
2697 mpctx->initialized_flags|=INITIALIZED_VCODEC;
2699 if (sh_video->codec)
2700 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODEC=%s\n", sh_video->codec->name);
2702 sh_video->last_pts = MP_NOPTS_VALUE;
2703 sh_video->num_buffered_pts = 0;
2704 sh_video->next_frame_time = 0;
2706 if (opts->auto_quality > 0) {
2707 // Auto quality option enabled
2708 output_quality=get_video_quality_max(sh_video);
2709 if (opts->auto_quality > output_quality)
2710 opts->auto_quality = output_quality;
2711 else
2712 output_quality = opts->auto_quality;
2713 mp_msg(MSGT_CPLAYER,MSGL_V,"AutoQ: setting quality to %d.\n",output_quality);
2714 set_video_quality(sh_video,output_quality);
2717 // ========== Init display (sh_video->disp_w*sh_video->disp_h/out_fmt) ============
2719 current_module="init_vo";
2721 return 1;
2723 err_out:
2724 mpctx->sh_video = mpctx->d_video->sh = NULL;
2725 return 0;
2728 static double update_video_nocorrect_pts(struct MPContext *mpctx)
2730 struct sh_video *sh_video = mpctx->sh_video;
2731 double frame_time = 0;
2732 struct vo *video_out = mpctx->video_out;
2733 while (1) {
2734 current_module = "filter_video";
2735 // In nocorrect-pts mode there is no way to properly time these frames
2736 if (vo_get_buffered_frame(video_out, 0) >= 0)
2737 break;
2738 if (vf_output_queued_frame(sh_video->vfilter))
2739 break;
2740 unsigned char *packet = NULL;
2741 frame_time = sh_video->next_frame_time;
2742 if (mpctx->restart_playback)
2743 frame_time = 0;
2744 int in_size = video_read_frame(sh_video, &sh_video->next_frame_time,
2745 &packet, force_fps);
2746 if (in_size < 0) {
2747 #ifdef CONFIG_DVDNAV
2748 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
2749 if (mp_dvdnav_is_eof(mpctx->stream))
2750 return -1;
2751 if (mpctx->d_video)
2752 mpctx->d_video->eof = 0;
2753 if (mpctx->d_audio)
2754 mpctx->d_audio->eof = 0;
2755 mpctx->stream->eof = 0;
2756 } else
2757 #endif
2758 return -1;
2760 if (in_size > max_framesize)
2761 max_framesize = in_size;
2762 sh_video->timer += frame_time;
2763 if (mpctx->sh_audio)
2764 mpctx->delay -= frame_time;
2765 // video_read_frame can change fps (e.g. for ASF video)
2766 vo_fps = sh_video->fps;
2767 int framedrop_type = check_framedrop(mpctx, frame_time);
2768 current_module = "decode video";
2770 void *decoded_frame;
2771 #ifdef CONFIG_DVDNAV
2772 decoded_frame = mp_dvdnav_restore_smpi(mpctx, &in_size, &packet, NULL);
2773 if (in_size >= 0 && !decoded_frame)
2774 #endif
2775 decoded_frame = decode_video(sh_video, packet, in_size, framedrop_type,
2776 sh_video->pts);
2777 #ifdef CONFIG_DVDNAV
2778 // Save last still frame for future display
2779 mp_dvdnav_save_smpi(mpctx, in_size, packet, decoded_frame);
2780 #endif
2781 if (decoded_frame) {
2782 current_module = "filter video";
2783 filter_video(sh_video, decoded_frame, sh_video->pts);
2785 break;
2787 return frame_time;
2790 static void determine_frame_pts(struct MPContext *mpctx)
2792 struct sh_video *sh_video = mpctx->sh_video;
2793 struct MPOpts *opts = &mpctx->opts;
2795 if (opts->user_pts_assoc_mode) {
2796 sh_video->pts_assoc_mode = opts->user_pts_assoc_mode;
2797 } else if (sh_video->pts_assoc_mode == 0) {
2798 if (mpctx->d_video->demuxer->timestamp_type == TIMESTAMP_TYPE_PTS
2799 && sh_video->codec_reordered_pts != MP_NOPTS_VALUE)
2800 sh_video->pts_assoc_mode = 1;
2801 else
2802 sh_video->pts_assoc_mode = 2;
2803 } else {
2804 int probcount1 = sh_video->num_reordered_pts_problems;
2805 int probcount2 = sh_video->num_sorted_pts_problems;
2806 if (sh_video->pts_assoc_mode == 2) {
2807 int tmp = probcount1;
2808 probcount1 = probcount2;
2809 probcount2 = tmp;
2811 if (probcount1 >= probcount2 * 1.5 + 2) {
2812 sh_video->pts_assoc_mode = 3 - sh_video->pts_assoc_mode;
2813 mp_msg(MSGT_CPLAYER, MSGL_V, "Switching to pts association mode "
2814 "%d.\n", sh_video->pts_assoc_mode);
2817 sh_video->pts = sh_video->pts_assoc_mode == 1 ?
2818 sh_video->codec_reordered_pts : sh_video->sorted_pts;
2821 static double update_video(struct MPContext *mpctx)
2823 struct sh_video *sh_video = mpctx->sh_video;
2824 struct vo *video_out = mpctx->video_out;
2825 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_SET_OSD_OBJ,
2826 mpctx->osd); // hack for vf_expand
2827 if (!mpctx->opts.correct_pts)
2828 return update_video_nocorrect_pts(mpctx);
2830 double pts;
2832 while (1) {
2833 current_module = "filter_video";
2834 if (!mpctx->hrseek_active
2835 && vo_get_buffered_frame(video_out, false) >= 0)
2836 break;
2837 // XXX Time used in this call is not counted in any performance
2838 // timer now
2839 if (vf_output_queued_frame(sh_video->vfilter))
2840 break;
2841 unsigned char *packet = NULL;
2842 int in_size = ds_get_packet_pts(mpctx->d_video, &packet, &pts);
2843 if (pts != MP_NOPTS_VALUE)
2844 pts += mpctx->video_offset;
2845 bool hit_eof = false;
2846 if (in_size < 0) {
2847 // try to extract last frames in case of decoder lag
2848 in_size = 0;
2849 pts = MP_NOPTS_VALUE;
2850 hit_eof = true;
2852 if (in_size > max_framesize)
2853 max_framesize = in_size;
2854 current_module = "decode video";
2855 if (pts >= mpctx->hrseek_pts - .005)
2856 mpctx->hrseek_framedrop = false;
2857 int framedrop_type = mpctx->hrseek_framedrop ? 1 :
2858 check_framedrop(mpctx, sh_video->frametime);
2859 void *decoded_frame = decode_video(sh_video, packet, in_size,
2860 framedrop_type, pts);
2861 if (decoded_frame) {
2862 determine_frame_pts(mpctx);
2863 current_module = "filter video";
2864 filter_video(sh_video, decoded_frame, sh_video->pts);
2865 } else if (hit_eof) {
2866 if (vo_get_buffered_frame(video_out, true) < 0)
2867 return -1;
2869 break;
2872 if (!video_out->frame_loaded)
2873 return 0;
2875 pts = video_out->next_pts;
2876 if (pts == MP_NOPTS_VALUE) {
2877 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Video pts after filters MISSING\n");
2878 // Try to use decoder pts from before filters
2879 pts = sh_video->pts;
2880 if (pts == MP_NOPTS_VALUE)
2881 pts = sh_video->last_pts;
2883 if (mpctx->hrseek_active && pts < mpctx->hrseek_pts - .005) {
2884 vo_skip_frame(video_out);
2885 return 0;
2887 mpctx->hrseek_active = false;
2888 sh_video->pts = pts;
2889 if (sh_video->last_pts == MP_NOPTS_VALUE)
2890 sh_video->last_pts = sh_video->pts;
2891 else if (sh_video->last_pts > sh_video->pts) {
2892 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Decreasing video pts: %f < %f\n",
2893 sh_video->pts, sh_video->last_pts);
2894 /* If the difference in pts is small treat it as jitter around the
2895 * right value (possibly caused by incorrect timestamp ordering) and
2896 * just show this frame immediately after the last one.
2897 * Treat bigger differences as timestamp resets and start counting
2898 * timing of later frames from the position of this one. */
2899 if (sh_video->last_pts - sh_video->pts > 0.5)
2900 sh_video->last_pts = sh_video->pts;
2901 else
2902 sh_video->pts = sh_video->last_pts;
2904 double frame_time = sh_video->pts - sh_video->last_pts;
2905 sh_video->last_pts = sh_video->pts;
2906 sh_video->timer += frame_time;
2907 if (mpctx->sh_audio)
2908 mpctx->delay -= frame_time;
2909 return frame_time;
2912 void pause_player(struct MPContext *mpctx)
2914 if (mpctx->paused)
2915 return;
2916 mpctx->paused = 1;
2917 mpctx->step_frames = 0;
2918 mpctx->time_frame -= get_relative_time(mpctx);
2920 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2921 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2923 if (mpctx->ao && mpctx->sh_audio)
2924 ao_pause(mpctx->ao); // pause audio, keep data if possible
2927 void unpause_player(struct MPContext *mpctx)
2929 if (!mpctx->paused)
2930 return;
2931 mpctx->paused = 0;
2933 if (mpctx->ao && mpctx->sh_audio)
2934 ao_resume(mpctx->ao);
2935 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok
2936 && !mpctx->step_frames)
2937 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL); // resume video
2938 (void)get_relative_time(mpctx); // ignore time that passed during pause
2941 void add_step_frame(struct MPContext *mpctx)
2943 mpctx->step_frames++;
2944 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2945 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2946 unpause_player(mpctx);
2949 static void pause_loop(struct MPContext *mpctx)
2951 struct MPOpts *opts = &mpctx->opts;
2952 mp_cmd_t* cmd;
2953 #ifdef CONFIG_STREAM_CACHE
2954 int old_cache_fill = stream_cache_size > 0 ?
2955 cache_fill_status(mpctx->stream) : 0;
2956 #endif
2957 if (!opts->quiet) {
2958 if (opts->term_osd && !mpctx->sh_video) {
2959 set_osd_tmsg(OSD_MSG_PAUSE, 1, 0, " ===== PAUSE =====");
2960 update_osd_msg(mpctx);
2961 } else
2962 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "\n%s\r",
2963 mp_gtext(" ===== PAUSE ====="));
2964 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_PAUSED\n");
2967 while ( (cmd = mp_input_get_cmd(mpctx->input, 20, 1)) == NULL
2968 || cmd->id == MP_CMD_SET_MOUSE_POS || cmd->pausing == 4) {
2969 if (cmd) {
2970 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
2971 run_command(mpctx, cmd);
2972 mp_cmd_free(cmd);
2973 continue;
2975 if (mpctx->sh_video && mpctx->video_out)
2976 vo_check_events(mpctx->video_out);
2977 #ifdef CONFIG_MENU
2978 if (vf_menu)
2979 vf_menu_pause_update(vf_menu);
2980 #endif
2981 usec_sleep(20000);
2982 update_osd_msg(mpctx);
2983 int hack = vo_osd_changed(0);
2984 vo_osd_changed(hack);
2985 if (hack)
2986 break;
2987 #ifdef CONFIG_STREAM_CACHE
2988 if (!opts->quiet && stream_cache_size > 0) {
2989 int new_cache_fill = cache_fill_status(mpctx->stream);
2990 if (new_cache_fill != old_cache_fill) {
2991 if (opts->term_osd && !mpctx->sh_video) {
2992 set_osd_tmsg(OSD_MSG_PAUSE, 1, 0, "%s %d%%",
2993 mp_gtext(" ===== PAUSE ====="),
2994 new_cache_fill);
2995 update_osd_msg(mpctx);
2996 } else
2997 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "%s %d%%\r",
2998 mp_gtext(" ===== PAUSE ====="),
2999 new_cache_fill);
3000 old_cache_fill = new_cache_fill;
3003 #endif
3008 // Find the right mute status and record position for new file position
3009 static void edl_seek_reset(MPContext *mpctx)
3011 mpctx->edl_muted = 0;
3012 next_edl_record = edl_records;
3014 while (next_edl_record) {
3015 if (next_edl_record->start_sec >= get_current_time(mpctx))
3016 break;
3018 if (next_edl_record->action == EDL_MUTE)
3019 mpctx->edl_muted = !mpctx->edl_muted;
3020 next_edl_record = next_edl_record->next;
3022 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
3023 mixer_mute(&mpctx->mixer);
3027 // Execute EDL command for the current position if one exists
3028 static void edl_update(MPContext *mpctx)
3030 if (!next_edl_record)
3031 return;
3033 if (!mpctx->sh_video) {
3034 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot use EDL without video, disabling.\n");
3035 free_edl(edl_records);
3036 next_edl_record = NULL;
3037 edl_records = NULL;
3038 return;
3041 if (get_current_time(mpctx) >= next_edl_record->start_sec) {
3042 if (next_edl_record->action == EDL_SKIP) {
3043 mpctx->osd_function = OSD_FFW;
3044 queue_seek(mpctx, MPSEEK_RELATIVE, next_edl_record->length_sec, 0);
3045 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_SKIP: start [%f], stop "
3046 "[%f], length [%f]\n", next_edl_record->start_sec,
3047 next_edl_record->stop_sec, next_edl_record->length_sec);
3049 else if (next_edl_record->action == EDL_MUTE) {
3050 mpctx->edl_muted = !mpctx->edl_muted;
3051 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
3052 mixer_mute(&mpctx->mixer);
3053 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_MUTE: [%f]\n",
3054 next_edl_record->start_sec );
3056 next_edl_record = next_edl_record->next;
3060 static void reinit_decoders(struct MPContext *mpctx)
3062 reinit_video_chain(mpctx);
3063 reinit_audio_chain(mpctx);
3064 mp_property_do("sub", M_PROPERTY_SET, &(int){mpctx->global_sub_pos}, mpctx);
3067 static void seek_reset(struct MPContext *mpctx, bool reset_ao)
3069 if (mpctx->sh_video) {
3070 current_module = "seek_video_reset";
3071 resync_video_stream(mpctx->sh_video);
3072 mpctx->sh_video->timer = 0;
3073 vo_seek_reset(mpctx->video_out);
3074 mpctx->sh_video->timer = 0;
3075 mpctx->sh_video->num_buffered_pts = 0;
3076 mpctx->sh_video->last_pts = MP_NOPTS_VALUE;
3077 mpctx->delay = 0;
3078 mpctx->time_frame = 0;
3079 mpctx->restart_playback = true;
3080 // Not all demuxers set d_video->pts during seek, so this value
3081 // (which is used by at least vobsub and edl code below) may
3082 // be completely wrong (probably 0).
3083 mpctx->sh_video->pts = mpctx->d_video->pts + mpctx->video_offset;
3084 mpctx->video_pts = mpctx->sh_video->pts;
3085 update_subtitles(mpctx, mpctx->sh_video->pts, mpctx->video_offset,
3086 true);
3087 update_teletext(mpctx->sh_video, mpctx->demuxer, 1);
3090 if (mpctx->sh_audio) {
3091 current_module = "seek_audio_reset";
3092 resync_audio_stream(mpctx->sh_audio);
3093 if (reset_ao)
3094 ao_reset(mpctx->ao);
3095 mpctx->ao->buffer.len = mpctx->ao->buffer_playable_size;
3096 mpctx->sh_audio->a_buffer_len = 0;
3097 if (!mpctx->sh_video)
3098 update_subtitles(mpctx, mpctx->sh_audio->pts,
3099 mpctx->video_offset, true);
3102 if (vo_vobsub && mpctx->sh_video) {
3103 current_module = "seek_vobsub_reset";
3104 vobsub_seek(vo_vobsub, mpctx->sh_video->pts);
3107 edl_seek_reset(mpctx);
3109 mpctx->hrseek_active = false;
3110 mpctx->hrseek_framedrop = false;
3111 mpctx->total_avsync_change = 0;
3112 audio_time_usage = 0; video_time_usage = 0; vout_time_usage = 0;
3113 drop_frame_cnt = 0;
3115 current_module = NULL;
3118 static bool timeline_set_part(struct MPContext *mpctx, int i)
3120 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
3121 struct timeline_part *n = mpctx->timeline + i;
3122 mpctx->timeline_part = i;
3123 mpctx->video_offset = n->start - n->source_start;
3124 if (n->source == p->source)
3125 return false;
3126 enum stop_play_reason orig_stop_play = mpctx->stop_play;
3127 if (!mpctx->sh_video && mpctx->stop_play == KEEP_PLAYING)
3128 mpctx->stop_play = AT_END_OF_FILE; // let audio uninit drain data
3129 uninit_player(mpctx, INITIALIZED_VCODEC | (mpctx->opts.fixed_vo ? 0 : INITIALIZED_VO) | (mpctx->opts.gapless_audio ? 0 : INITIALIZED_AO) | INITIALIZED_ACODEC | INITIALIZED_SUB);
3130 mpctx->stop_play = orig_stop_play;
3131 mpctx->demuxer = n->source->demuxer;
3132 mpctx->d_video = mpctx->demuxer->video;
3133 mpctx->d_audio = mpctx->demuxer->audio;
3134 mpctx->d_sub = mpctx->demuxer->sub;
3135 mpctx->sh_video = mpctx->d_video->sh;
3136 mpctx->sh_audio = mpctx->d_audio->sh;
3137 return true;
3140 // Given pts, switch playback to the corresponding part.
3141 // Return offset within that part.
3142 static double timeline_set_from_time(struct MPContext *mpctx, double pts,
3143 bool *need_reset)
3145 if (pts < 0)
3146 pts = 0;
3147 for (int i = 0; i < mpctx->num_timeline_parts; i++) {
3148 struct timeline_part *p = mpctx->timeline + i;
3149 if (pts < (p+1)->start) {
3150 *need_reset = timeline_set_part(mpctx, i);
3151 return pts - p->start + p->source_start;
3154 return -1;
3158 // return -1 if seek failed (non-seekable stream?), 0 otherwise
3159 static int seek(MPContext *mpctx, struct seek_params seek,
3160 bool timeline_fallthrough)
3162 struct MPOpts *opts = &mpctx->opts;
3164 current_module = "seek";
3165 if (mpctx->stop_play == AT_END_OF_FILE)
3166 mpctx->stop_play = KEEP_PLAYING;
3167 bool hr_seek = mpctx->demuxer->accurate_seek && opts->correct_pts;
3168 hr_seek &= seek.exact >= 0 && seek.type != MPSEEK_FACTOR;
3169 hr_seek &= opts->hr_seek == 0 && seek.type == MPSEEK_ABSOLUTE
3170 || opts->hr_seek > 0 || seek.exact > 0;
3171 if (seek.type == MPSEEK_FACTOR
3172 || seek.type == MPSEEK_ABSOLUTE
3173 && seek.amount < mpctx->last_chapter_pts
3174 || seek.amount < 0)
3175 mpctx->last_chapter_seek = -1;
3176 if (mpctx->timeline && seek.type == MPSEEK_FACTOR) {
3177 seek.amount *= mpctx->timeline[mpctx->num_timeline_parts].start;
3178 seek.type = MPSEEK_ABSOLUTE;
3180 if ((mpctx->demuxer->accurate_seek || mpctx->timeline)
3181 && seek.type == MPSEEK_RELATIVE) {
3182 seek.type = MPSEEK_ABSOLUTE;
3183 seek.direction = seek.amount > 0 ? 1 : -1;
3184 seek.amount += get_current_time(mpctx);
3187 /* At least the liba52 decoder wants to read from the input stream
3188 * during initialization, so reinit must be done after the demux_seek()
3189 * call that clears possible stream EOF. */
3190 bool need_reset = false;
3191 double demuxer_amount = seek.amount;
3192 if (mpctx->timeline) {
3193 demuxer_amount = timeline_set_from_time(mpctx, seek.amount,
3194 &need_reset);
3195 if (demuxer_amount == -1) {
3196 mpctx->stop_play = AT_END_OF_FILE;
3197 // Clear audio from current position
3198 if (mpctx->sh_audio) {
3199 ao_reset(mpctx->ao);
3200 mpctx->sh_audio->a_buffer_len = 0;
3202 return -1;
3205 int demuxer_style = 0;
3206 switch (seek.type) {
3207 case MPSEEK_FACTOR:
3208 demuxer_style |= SEEK_FACTOR; // fallthrough
3209 case MPSEEK_ABSOLUTE:
3210 demuxer_style |= SEEK_ABSOLUTE;
3212 if (hr_seek || seek.direction < 0)
3213 demuxer_style |= SEEK_BACKWARD;
3214 else if (seek.direction > 0)
3215 demuxer_style |= SEEK_FORWARD;
3217 int seekresult = demux_seek(mpctx->demuxer, demuxer_amount, audio_delay,
3218 demuxer_style);
3219 if (need_reset)
3220 reinit_decoders(mpctx);
3221 if (seekresult == 0)
3222 return -1;
3224 seek_reset(mpctx, !timeline_fallthrough);
3226 /* Use the target time as "current position" for further relative
3227 * seeks etc until a new video frame has been decoded */
3228 if (seek.type == MPSEEK_ABSOLUTE)
3229 mpctx->video_pts = seek.amount;
3231 if (hr_seek) {
3232 mpctx->hrseek_active = true;
3233 mpctx->hrseek_framedrop = true;
3234 mpctx->hrseek_pts = seek.amount;
3237 mpctx->start_timestamp = GetTimerMS();
3239 return 0;
3242 void queue_seek(struct MPContext *mpctx, enum seek_type type, double amount,
3243 int exact)
3245 struct seek_params *seek = &mpctx->seek;
3246 switch (type) {
3247 case MPSEEK_RELATIVE:
3248 if (seek->type == MPSEEK_FACTOR)
3249 return; // Well... not common enough to bother doing better
3250 seek->amount += amount;
3251 seek->exact = FFMAX(seek->exact, exact);
3252 if (seek->type == MPSEEK_NONE)
3253 seek->exact = exact;
3254 if (seek->type == MPSEEK_ABSOLUTE)
3255 return;
3256 if (seek->amount == 0) {
3257 *seek = (struct seek_params){0};
3258 return;
3260 seek->type = MPSEEK_RELATIVE;
3261 return;
3262 case MPSEEK_ABSOLUTE:
3263 case MPSEEK_FACTOR:
3264 *seek = (struct seek_params) {
3265 .type = type,
3266 .amount = amount,
3267 .exact = exact,
3269 return;
3270 case MPSEEK_NONE:
3271 *seek = (struct seek_params){0};
3272 return;
3274 abort();
3278 double get_time_length(struct MPContext *mpctx)
3280 if (mpctx->timeline)
3281 return mpctx->timeline[mpctx->num_timeline_parts].start;
3283 struct demuxer *demuxer = mpctx->demuxer;
3284 double get_time_ans;
3285 // <= 0 means DEMUXER_CTRL_NOTIMPL or DEMUXER_CTRL_DONTKNOW
3286 if (demux_control(demuxer, DEMUXER_CTRL_GET_TIME_LENGTH,
3287 (void *) &get_time_ans) > 0)
3288 return get_time_ans;
3290 struct sh_video *sh_video = mpctx->d_video->sh;
3291 struct sh_audio *sh_audio = mpctx->d_audio->sh;
3292 if (sh_video && sh_video->i_bps && sh_audio && sh_audio->i_bps)
3293 return (double) (demuxer->movi_end - demuxer->movi_start) /
3294 (sh_video->i_bps + sh_audio->i_bps);
3295 if (sh_video && sh_video->i_bps)
3296 return (double) (demuxer->movi_end - demuxer->movi_start) /
3297 sh_video->i_bps;
3298 if (sh_audio && sh_audio->i_bps)
3299 return (double) (demuxer->movi_end - demuxer->movi_start) /
3300 sh_audio->i_bps;
3301 return 0;
3304 /* If there are timestamps from stream level then use those (for example
3305 * DVDs can have consistent times there while the MPEG-level timestamps
3306 * reset). */
3307 double get_current_time(struct MPContext *mpctx)
3309 struct demuxer *demuxer = mpctx->demuxer;
3310 if (demuxer->stream_pts != MP_NOPTS_VALUE)
3311 return demuxer->stream_pts;
3312 struct sh_video *sh_video = demuxer->video->sh;
3313 if (sh_video)
3314 return mpctx->video_pts;
3315 return playing_audio_pts(mpctx);
3318 int get_percent_pos(struct MPContext *mpctx)
3320 struct demuxer *demuxer = mpctx->demuxer;
3321 int ans = 0;
3322 if (mpctx->timeline)
3323 ans = get_current_time(mpctx) * 100 /
3324 mpctx->timeline[mpctx->num_timeline_parts].start;
3325 else if (demux_control(demuxer, DEMUXER_CTRL_GET_PERCENT_POS, &ans) > 0)
3327 else {
3328 int len = (demuxer->movi_end - demuxer->movi_start) / 100;
3329 off_t pos = demuxer->filepos > 0 ?
3330 demuxer->filepos : stream_tell(demuxer->stream);
3331 if (len > 0)
3332 ans = (pos - demuxer->movi_start) / len;
3333 else
3334 ans = 0;
3336 if (ans < 0)
3337 ans = 0;
3338 if (ans > 100)
3339 ans = 100;
3340 return ans;
3343 // -2 is no chapters, -1 is before first chapter
3344 int get_current_chapter(struct MPContext *mpctx)
3346 double current_pts = get_current_time(mpctx);
3347 if (!mpctx->chapters)
3348 return FFMAX(mpctx->last_chapter_seek,
3349 demuxer_get_current_chapter(mpctx->demuxer, current_pts));
3351 int i;
3352 for (i = 1; i < mpctx->num_chapters; i++)
3353 if (current_pts < mpctx->chapters[i].start)
3354 break;
3355 return FFMAX(mpctx->last_chapter_seek, i - 1);
3358 // currently returns a string allocated with malloc, not talloc
3359 char *chapter_display_name(struct MPContext *mpctx, int chapter)
3361 if (!mpctx->chapters || !mpctx->sh_video)
3362 return demuxer_chapter_display_name(mpctx->demuxer, chapter);
3363 return talloc_strdup(NULL, mpctx->chapters[chapter].name);
3366 int seek_chapter(struct MPContext *mpctx, int chapter, double *seek_pts,
3367 char **chapter_name)
3369 mpctx->last_chapter_seek = -1;
3370 if (!mpctx->chapters || !mpctx->sh_video) {
3371 int res = demuxer_seek_chapter(mpctx->demuxer, chapter, seek_pts,
3372 chapter_name);
3373 if (res >= 0) {
3374 if (*seek_pts == -1)
3375 seek_reset(mpctx, true);
3376 else {
3377 mpctx->last_chapter_seek = res;
3378 mpctx->last_chapter_pts = *seek_pts;
3381 return res;
3384 if (chapter >= mpctx->num_chapters)
3385 return -1;
3386 if (chapter < 0)
3387 chapter = 0;
3388 *seek_pts = mpctx->chapters[chapter].start;
3389 mpctx->last_chapter_seek = chapter;
3390 mpctx->last_chapter_pts = *seek_pts;
3391 if (chapter_name)
3392 *chapter_name = talloc_strdup(NULL, mpctx->chapters[chapter].name);
3393 return chapter;
3397 static void run_playloop(struct MPContext *mpctx)
3399 struct MPOpts *opts = &mpctx->opts;
3400 float aq_sleep_time = 0;
3401 bool full_audio_buffers = false;
3403 if (opts->chapterrange[1] > 0) {
3404 int cur_chapter = get_current_chapter(mpctx);
3405 if (cur_chapter!=-1 && cur_chapter + 1 > opts->chapterrange[1])
3406 mpctx->stop_play = PT_NEXT_ENTRY;
3409 if (!mpctx->sh_audio && mpctx->d_audio->sh) {
3410 mpctx->sh_audio = mpctx->d_audio->sh;
3411 mpctx->sh_audio->ds = mpctx->d_audio;
3412 reinit_audio_chain(mpctx);
3415 /*========================== PLAY AUDIO ============================*/
3417 if (mpctx->sh_audio && !mpctx->paused
3418 && (!mpctx->restart_playback || !mpctx->sh_video)) {
3419 int status = fill_audio_out_buffers(mpctx);
3420 full_audio_buffers = status >= 0 && !mpctx->ao->untimed;
3421 if (status == -2)
3422 // at eof, all audio at least written to ao
3423 if (!mpctx->sh_video)
3424 mpctx->stop_play = AT_END_OF_FILE;
3428 if (!mpctx->sh_video) {
3429 mpctx->restart_playback = false;
3430 if (mpctx->step_frames) {
3431 mpctx->step_frames = 0;
3432 pause_player(mpctx);
3434 // handle audio-only case:
3435 double a_pos = 0, a_buf = 0;
3436 // sh_audio can be NULL due to video stream switching
3437 // TODO: handle this better
3438 if (mpctx->sh_audio) {
3439 a_buf = ao_get_delay(mpctx->ao);
3440 a_pos = written_audio_pts(mpctx) - mpctx->opts.playback_speed *
3441 a_buf;
3444 print_status(mpctx, a_pos, false);
3446 update_subtitles(mpctx, a_pos, mpctx->video_offset, false);
3447 update_osd_msg(mpctx);
3448 if (end_at.type == END_AT_TIME && end_at.pos < a_pos) {
3449 mpctx->stop_play = AT_END_OF_FILE;
3450 } else if (mpctx->timeline && mpctx->stop_play == AT_END_OF_FILE
3451 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts
3452 && mpctx->sh_audio) {
3453 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
3454 if (!opts->gapless_audio && p->source != (p+1)->source
3455 && a_buf > 0.05) {
3456 mpctx->stop_play = KEEP_PLAYING;
3457 mp_input_get_cmd(mpctx->input, (a_buf-.05) * 1000, true);
3458 } else {
3459 seek(mpctx, (struct seek_params){ .type = MPSEEK_ABSOLUTE,
3460 .amount = (p+1)->start },
3461 true);
3463 } else if (!mpctx->stop_play) {
3464 int sleep_time = 100;
3465 if (mpctx->sh_audio) {
3466 if (mpctx->ao->untimed)
3467 sleep_time = 0;
3468 else if (full_audio_buffers)
3469 sleep_time = FFMAX(20, a_buf * 1000 - 50);
3470 else
3471 sleep_time = 20;
3472 sleep_time = FFMIN(sleep_time, 100);
3474 mp_input_get_cmd(mpctx->input, sleep_time, true);
3476 } else {
3478 /*========================== PLAY VIDEO ============================*/
3480 vo_pts = mpctx->sh_video->timer * 90000.0;
3481 vo_fps = mpctx->sh_video->fps;
3483 bool blit_frame = mpctx->video_out->frame_loaded;
3484 if (!blit_frame || mpctx->hrseek_active) {
3485 double frame_time = update_video(mpctx);
3486 blit_frame = mpctx->video_out->frame_loaded;
3487 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "*** ftime=%5.3f ***\n", frame_time);
3488 if (mpctx->sh_video->vf_initialized < 0) {
3489 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
3490 "\nFATAL: Could not initialize video filters (-vf) "
3491 "or video output (-vo).\n");
3492 mpctx->stop_play = PT_NEXT_ENTRY;
3493 return;
3495 if (frame_time < 0)
3496 mpctx->stop_play = AT_END_OF_FILE;
3497 else if (!mpctx->restart_playback) {
3498 mpctx->time_frame += frame_time / opts->playback_speed;
3499 adjust_sync(mpctx, frame_time);
3502 if (mpctx->timeline) {
3503 struct timeline_part *next =
3504 mpctx->timeline + mpctx->timeline_part + 1;
3505 if (mpctx->sh_video->pts >= next->start
3506 || mpctx->stop_play == AT_END_OF_FILE
3507 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts) {
3508 seek(mpctx, (struct seek_params){ .type = MPSEEK_ABSOLUTE,
3509 .amount = next->start },
3510 true);
3511 return;
3515 // ==========================================================================
3517 current_module = "vo_check_events";
3518 vo_check_events(mpctx->video_out);
3520 #ifdef CONFIG_X11
3521 if (stop_xscreensaver) {
3522 current_module = "stop_xscreensaver";
3523 xscreensaver_heartbeat(mpctx->x11_state);
3525 #endif
3526 if (heartbeat_cmd) {
3527 static unsigned last_heartbeat;
3528 unsigned now = GetTimerMS();
3529 if (now - last_heartbeat > 30000) {
3530 last_heartbeat = now;
3531 system(heartbeat_cmd);
3535 bool frame_time_remaining = sleep_until_near_frame(mpctx,
3536 &mpctx->time_frame,
3537 full_audio_buffers,
3538 &aq_sleep_time);
3540 //====================== FLIP PAGE (VIDEO BLT): =========================
3542 current_module = "flip_page";
3543 if (!frame_time_remaining && blit_frame) {
3544 struct sh_video *sh_video = mpctx->sh_video;
3545 mpctx->video_pts = sh_video->pts;
3546 update_subtitles(mpctx, sh_video->pts, mpctx->video_offset, false);
3547 update_teletext(sh_video, mpctx->demuxer, 0);
3548 update_osd_msg(mpctx);
3549 struct vf_instance *vf = sh_video->vfilter;
3550 vf->control(vf, VFCTRL_DRAW_EOSD, mpctx->osd);
3551 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
3552 vo_osd_changed(0);
3554 mpctx->time_frame -= mpctx->video_out->flip_queue_offset;
3555 aq_sleep_time += mpctx->time_frame;
3556 // flag 256 means: libvo driver does its timing (dvb card)
3557 if (mpctx->time_frame > 0.001
3558 && !(mpctx->sh_video->output_flags & VFCAP_TIMER))
3559 mpctx->time_frame = timing_sleep(mpctx, mpctx->time_frame);
3560 mpctx->time_frame += mpctx->video_out->flip_queue_offset;
3562 unsigned int t2 = GetTimer();
3563 /* Playing with playback speed it's possible to get pathological
3564 * cases with mpctx->time_frame negative enough to cause an
3565 * overflow in pts_us calculation, thus the FFMAX. */
3566 double time_frame = FFMAX(mpctx->time_frame, -1);
3567 unsigned int pts_us = mpctx->last_time + time_frame * 1e6;
3568 int duration = -1;
3569 double pts2 = mpctx->video_out->next_pts2;
3570 if (pts2 != MP_NOPTS_VALUE && opts->correct_pts
3571 && !mpctx->restart_playback) {
3572 // expected A/V sync correction is ignored
3573 double diff = (pts2 - mpctx->video_pts);
3574 diff /= opts->playback_speed;
3575 if (mpctx->time_frame < 0)
3576 diff += mpctx->time_frame;
3577 if (diff < 0)
3578 diff = 0;
3579 if (diff > 10)
3580 diff = 10;
3581 duration = diff * 1e6;
3583 vo_flip_page(mpctx->video_out, pts_us | 1, duration);
3585 mpctx->last_vo_flip_duration = (GetTimer() - t2) * 0.000001;
3586 vout_time_usage += mpctx->last_vo_flip_duration;
3587 if (mpctx->video_out->driver->flip_page_timed) {
3588 // No need to adjust sync based on flip speed
3589 mpctx->last_vo_flip_duration = 0;
3590 // For print_status - VO call finishing early is OK for sync
3591 mpctx->time_frame -= get_relative_time(mpctx);
3593 if (mpctx->restart_playback) {
3594 mpctx->syncing_audio = true;
3595 if (mpctx->sh_audio && !mpctx->paused)
3596 fill_audio_out_buffers(mpctx);
3597 mpctx->restart_playback = false;
3598 mpctx->time_frame = 0;
3599 get_relative_time(mpctx);
3601 print_status(mpctx, MP_NOPTS_VALUE, true);
3602 } else
3603 print_status(mpctx, MP_NOPTS_VALUE, false);
3605 //============================ Auto QUALITY ============================
3607 /*Output quality adjustments:*/
3608 if (opts->auto_quality > 0) {
3609 current_module = "autoq";
3610 if (output_quality < opts->auto_quality && aq_sleep_time > 0)
3611 ++output_quality;
3612 else
3613 if (output_quality>1 && aq_sleep_time<0)
3614 --output_quality;
3615 else if (output_quality>0 && aq_sleep_time<-0.050f) // 50ms
3616 output_quality = 0;
3617 set_video_quality(mpctx->sh_video, output_quality);
3620 if (!frame_time_remaining && blit_frame) {
3621 if (play_n_frames >= 0) {
3622 --play_n_frames;
3623 if (play_n_frames <= 0)
3624 mpctx->stop_play = PT_NEXT_ENTRY;
3626 if (mpctx->step_frames > 0) {
3627 mpctx->step_frames--;
3628 if (mpctx->step_frames == 0)
3629 pause_player(mpctx);
3633 // FIXME: add size based support for -endpos
3634 if (end_at.type == END_AT_TIME &&
3635 !frame_time_remaining && end_at.pos <= mpctx->sh_video->pts)
3636 mpctx->stop_play = PT_NEXT_ENTRY;
3638 } // end if(mpctx->sh_video)
3640 #ifdef CONFIG_DVDNAV
3641 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
3642 nav_highlight_t hl;
3643 mp_dvdnav_get_highlight(mpctx->stream, &hl);
3644 if (!vo_spudec || !spudec_apply_palette_crop(vo_spudec, hl.palette, hl.sx, hl.sy, hl.ex, hl.ey)) {
3645 osd_set_nav_box(hl.sx, hl.sy, hl.ex, hl.ey);
3646 vo_osd_changed(OSDTYPE_DVDNAV);
3647 } else {
3648 osd_set_nav_box(0, 0, 0, 0);
3649 vo_osd_changed(OSDTYPE_DVDNAV);
3650 vo_osd_changed(OSDTYPE_SPU);
3653 if (mp_dvdnav_stream_has_changed(mpctx->stream)) {
3654 double ar = -1.0;
3655 if (mpctx->sh_video &&
3656 stream_control(mpctx->demuxer->stream,
3657 STREAM_CTRL_GET_ASPECT_RATIO, &ar)
3658 != STREAM_UNSUPPORTED)
3659 mpctx->sh_video->stream_aspect = ar;
3662 #endif
3664 //================= Keyboard events, SEEKing ====================
3666 current_module = "key_events";
3668 while (1) {
3669 mp_cmd_t *cmd;
3670 while ((cmd = mp_input_get_cmd(mpctx->input, 0, 1)) != NULL) {
3671 /* Allow running consecutive seek commands to combine them,
3672 * but execute the seek before running other commands.
3673 * If the user seeks continuously (keeps arrow key down)
3674 * try to finish showing a frame from one location before doing
3675 * another seek (which could lead to unchanging display). */
3676 if (mpctx->seek.type && cmd->id != MP_CMD_SEEK
3677 || mpctx->restart_playback && cmd->id == MP_CMD_SEEK
3678 && GetTimerMS() - mpctx->start_timestamp < 300)
3679 break;
3680 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
3681 run_command(mpctx, cmd);
3682 mp_cmd_free(cmd);
3683 if (mpctx->stop_play)
3684 break;
3686 if (!mpctx->paused || mpctx->stop_play || mpctx->seek.type
3687 || mpctx->restart_playback)
3688 break;
3689 if (mpctx->sh_video) {
3690 update_osd_msg(mpctx);
3691 int hack = vo_osd_changed(0);
3692 vo_osd_changed(hack);
3693 if (hack) {
3694 if (redraw_osd(mpctx->sh_video, mpctx->osd) < 0) {
3695 add_step_frame(mpctx);
3696 break;
3697 } else
3698 vo_osd_changed(0);
3701 pause_loop(mpctx);
3704 // handle -sstep
3705 if (step_sec > 0 && !mpctx->paused) {
3706 mpctx->osd_function = OSD_FFW;
3707 queue_seek(mpctx, MPSEEK_RELATIVE, step_sec, 0);
3710 edl_update(mpctx);
3712 /* Looping. */
3713 if (mpctx->stop_play==AT_END_OF_FILE && opts->loop_times>=0) {
3714 mp_msg(MSGT_CPLAYER, MSGL_V, "loop_times = %d\n", opts->loop_times);
3716 if (opts->loop_times>1)
3717 opts->loop_times--;
3718 else if (opts->loop_times==1)
3719 opts->loop_times = -1;
3720 play_n_frames = play_n_frames_mf;
3721 mpctx->stop_play = 0;
3722 queue_seek(mpctx, MPSEEK_ABSOLUTE, 0, 0);
3725 if (mpctx->seek.type) {
3726 seek(mpctx, mpctx->seek, false);
3727 mpctx->seek = (struct seek_params){0};
3732 static int read_keys(void *ctx, int fd)
3734 getch2(ctx);
3735 return mplayer_get_key(ctx, 0);
3738 static bool attachment_is_font(struct demux_attachment *att)
3740 if (!att->name || !att->type || !att->data || !att->data_size)
3741 return false;
3742 // match against MIME types
3743 if (strcmp(att->type, "application/x-truetype-font") == 0
3744 || strcmp(att->type, "application/x-font") == 0)
3745 return true;
3746 // fallback: match against file extension
3747 if (strlen(att->name) > 4) {
3748 char *ext = att->name + strlen(att->name) - 4;
3749 if (strcasecmp(ext, ".ttf") == 0 || strcasecmp(ext, ".ttc") == 0
3750 || strcasecmp(ext, ".otf") == 0)
3751 return true;
3753 return false;
3756 static int select_audio(demuxer_t *demuxer, int audio_id, char **audio_lang)
3758 if (audio_id == -1)
3759 audio_id = demuxer_audio_track_by_lang_and_default(demuxer, audio_lang);
3760 if (audio_id != -1) // -1 (automatic) is the default behaviour of demuxers
3761 demuxer_switch_audio(demuxer, audio_id);
3762 if (audio_id == -2) { // some demuxers don't yet know how to switch to no sound
3763 demuxer->audio->id = -2;
3764 demuxer->audio->sh = NULL;
3766 return demuxer->audio->id;
3769 static void print_version(const char* name)
3771 mp_msg(MSGT_CPLAYER, MSGL_INFO, MP_TITLE, name);
3773 /* Test for CPU capabilities (and corresponding OS support) for optimizing */
3774 GetCpuCaps(&gCpuCaps);
3775 #if ARCH_X86
3776 mp_msg(MSGT_CPLAYER, MSGL_V,
3777 "CPUflags: MMX: %d MMX2: %d 3DNow: %d 3DNowExt: %d SSE: %d SSE2: %d SSSE3: %d\n",
3778 gCpuCaps.hasMMX, gCpuCaps.hasMMX2,
3779 gCpuCaps.has3DNow, gCpuCaps.has3DNowExt,
3780 gCpuCaps.hasSSE, gCpuCaps.hasSSE2, gCpuCaps.hasSSSE3);
3781 #if CONFIG_RUNTIME_CPUDETECT
3782 mp_tmsg(MSGT_CPLAYER,MSGL_V, "Compiled with runtime CPU detection.\n");
3783 #else
3784 mp_tmsg(MSGT_CPLAYER,MSGL_V, "Compiled for x86 CPU with extensions:");
3785 if (HAVE_MMX)
3786 mp_msg(MSGT_CPLAYER,MSGL_V," MMX");
3787 if (HAVE_MMX2)
3788 mp_msg(MSGT_CPLAYER,MSGL_V," MMX2");
3789 if (HAVE_AMD3DNOW)
3790 mp_msg(MSGT_CPLAYER,MSGL_V," 3DNow");
3791 if (HAVE_AMD3DNOWEXT)
3792 mp_msg(MSGT_CPLAYER,MSGL_V," 3DNowExt");
3793 if (HAVE_SSE)
3794 mp_msg(MSGT_CPLAYER,MSGL_V," SSE");
3795 if (HAVE_SSE2)
3796 mp_msg(MSGT_CPLAYER,MSGL_V," SSE2");
3797 if (HAVE_SSSE3)
3798 mp_msg(MSGT_CPLAYER,MSGL_V," SSSE3");
3799 if (HAVE_CMOV)
3800 mp_msg(MSGT_CPLAYER,MSGL_V," CMOV");
3801 mp_msg(MSGT_CPLAYER,MSGL_V,"\n");
3802 #endif /* CONFIG_RUNTIME_CPUDETECT */
3803 #endif /* ARCH_X86 */
3806 #ifdef PTW32_STATIC_LIB
3807 static void detach_ptw32(void)
3809 pthread_win32_thread_detach_np();
3810 pthread_win32_process_detach_np();
3812 #endif
3814 /* This preprocessor directive is a hack to generate a mplayer-nomain.o object
3815 * file for some tools to link against. */
3816 #ifndef DISABLE_MAIN
3817 int main(int argc,char* argv[]){
3818 #ifdef PTW32_STATIC_LIB
3819 pthread_win32_process_attach_np();
3820 pthread_win32_thread_attach_np();
3821 atexit(detach_ptw32);
3822 #endif
3823 if (argc > 1 && !strcmp(argv[1], "-leak-report"))
3824 talloc_enable_leak_report();
3826 char * mem_ptr;
3828 // movie info:
3830 /* Flag indicating whether MPlayer should exit without playing anything. */
3831 int opt_exit = 0;
3832 int i;
3834 struct MPContext *mpctx = &(struct MPContext){
3835 .osd_function = OSD_PLAY,
3836 .begin_skip = MP_NOPTS_VALUE,
3837 .play_tree_step = 1,
3838 .global_sub_pos = -1,
3839 .set_of_sub_pos = -1,
3840 .file_format = DEMUXER_TYPE_UNKNOWN,
3841 .last_dvb_step = 1,
3844 InitTimer();
3845 srand(GetTimerMS());
3847 mp_msg_init();
3848 set_av_log_callback();
3850 #ifdef CONFIG_X11
3851 mpctx->x11_state = vo_x11_init_state();
3852 #endif
3853 struct MPOpts *opts = &mpctx->opts;
3854 set_default_mplayer_options(opts);
3855 // Create the config context and register the options
3856 mpctx->mconfig = m_config_new(opts, cfg_include);
3857 m_config_register_options(mpctx->mconfig,mplayer_opts);
3858 m_config_register_options(mpctx->mconfig, common_opts);
3859 mp_input_register_options(mpctx->mconfig);
3861 // Preparse the command line
3862 m_config_preparse_command_line(mpctx->mconfig,argc,argv);
3864 #if (defined(__MINGW32__) || defined(__CYGWIN__)) && defined(CONFIG_WIN32DLL)
3865 set_path_env();
3866 #endif
3868 #ifdef CONFIG_TV
3869 stream_tv_defaults.immediate = 1;
3870 #endif
3872 parse_cfgfiles(mpctx, mpctx->mconfig);
3874 mpctx->playtree = m_config_parse_mp_command_line(mpctx->mconfig, argc, argv);
3875 if(mpctx->playtree == NULL)
3876 opt_exit = 1;
3877 else {
3878 mpctx->playtree = play_tree_cleanup(mpctx->playtree);
3879 if(mpctx->playtree) {
3880 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,mpctx->mconfig);
3881 if(mpctx->playtree_iter) {
3882 if(play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
3883 play_tree_iter_free(mpctx->playtree_iter);
3884 mpctx->playtree_iter = NULL;
3886 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,1);
3890 mpctx->key_fifo = mp_fifo_create(opts);
3892 print_version("MPlayer2");
3894 #if defined(__MINGW32__) || defined(__CYGWIN__)
3896 HMODULE kernel32 = GetModuleHandle("Kernel32.dll");
3897 BOOL WINAPI (*setDEP)(DWORD) = NULL;
3898 BOOL WINAPI (*setDllDir)(LPCTSTR) = NULL;
3899 if (kernel32) {
3900 setDEP = GetProcAddress(kernel32, "SetProcessDEPPolicy");
3901 setDllDir = GetProcAddress(kernel32, "SetDllDirectoryA");
3903 if (setDEP) setDEP(3);
3904 if (setDllDir) setDllDir("");
3906 // stop Windows from showing all kinds of annoying error dialogs
3907 SetErrorMode(0x8003);
3908 // request 1ms timer resolution
3909 timeBeginPeriod(1);
3910 #endif
3912 #ifdef CONFIG_PRIORITY
3913 set_priority();
3914 #endif
3916 if(opts->video_driver_list && strcmp(opts->video_driver_list[0],"help")==0){
3917 list_video_out();
3918 opt_exit = 1;
3921 if(opts->audio_driver_list && strcmp(opts->audio_driver_list[0],"help")==0){
3922 list_audio_out();
3923 opt_exit = 1;
3926 /* Check codecs.conf. */
3927 if(!codecs_file || !parse_codec_cfg(codecs_file)){
3928 if(!parse_codec_cfg(mem_ptr=get_path("codecs.conf"))){
3929 if(!parse_codec_cfg(MPLAYER_CONFDIR "/codecs.conf")){
3930 if(!parse_codec_cfg(NULL)){
3931 exit_player_with_rc(mpctx, EXIT_NONE, 0);
3933 mp_tmsg(MSGT_CPLAYER,MSGL_V,"Using built-in default codecs.conf.\n");
3936 free( mem_ptr ); // release the buffer created by get_path()
3939 if(audio_codec_list && strcmp(audio_codec_list[0],"help")==0){
3940 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available audio codecs:\n");
3941 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AUDIO_CODECS\n");
3942 list_codecs(1);
3943 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3944 opt_exit = 1;
3946 if(video_codec_list && strcmp(video_codec_list[0],"help")==0){
3947 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available video codecs:\n");
3948 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODECS\n");
3949 list_codecs(0);
3950 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3951 opt_exit = 1;
3953 if(video_fm_list && strcmp(video_fm_list[0],"help")==0){
3954 vfm_help();
3955 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3956 opt_exit = 1;
3958 if(audio_fm_list && strcmp(audio_fm_list[0],"help")==0){
3959 afm_help();
3960 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3961 opt_exit = 1;
3963 if(af_cfg.list && strcmp(af_cfg.list[0],"help")==0){
3964 af_help();
3965 printf("\n");
3966 opt_exit = 1;
3968 #ifdef CONFIG_X11
3969 if(vo_fstype_list && strcmp(vo_fstype_list[0],"help")==0){
3970 fstype_help();
3971 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3972 opt_exit = 1;
3974 #endif
3975 if((opts->demuxer_name && strcmp(opts->demuxer_name,"help")==0) ||
3976 (opts->audio_demuxer_name && strcmp(opts->audio_demuxer_name,"help")==0) ||
3977 (opts->sub_demuxer_name && strcmp(opts->sub_demuxer_name,"help")==0)){
3978 demuxer_help();
3979 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
3980 opt_exit = 1;
3982 if (opts->list_properties) {
3983 property_print_help();
3984 opt_exit = 1;
3987 if(opt_exit)
3988 exit_player(mpctx, EXIT_NONE);
3990 if (!mpctx->filename && !opts->player_idle_mode) {
3991 // no file/vcd/dvd -> show HELP:
3992 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", mp_gtext(help_text));
3993 exit_player_with_rc(mpctx, EXIT_NONE, 0);
3996 /* Display what configure line was used */
3997 mp_msg(MSGT_CPLAYER, MSGL_V, "Configuration: " CONFIGURATION "\n");
3999 // Many users forget to include command line in bugreports...
4000 if( mp_msg_test(MSGT_CPLAYER,MSGL_V) ){
4001 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "CommandLine:");
4002 for(i=1;i<argc;i++)mp_msg(MSGT_CPLAYER, MSGL_INFO," '%s'",argv[i]);
4003 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
4006 //------ load global data first ------
4008 mpctx->osd = osd_create();
4010 // check font
4011 #ifdef CONFIG_FREETYPE
4012 init_freetype();
4013 #endif
4014 #ifdef CONFIG_FONTCONFIG
4015 if(font_fontconfig <= 0)
4017 #endif
4018 #ifdef CONFIG_BITMAP_FONT
4019 if(font_name){
4020 vo_font=read_font_desc(font_name,font_factor,verbose>1);
4021 if(!vo_font) mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load bitmap font: %s\n",
4022 filename_recode(font_name));
4023 } else {
4024 // try default:
4025 vo_font=read_font_desc( mem_ptr=get_path("font/font.desc"),font_factor,verbose>1);
4026 free(mem_ptr); // release the buffer created by get_path()
4027 if(!vo_font)
4028 vo_font=read_font_desc(MPLAYER_DATADIR "/font/font.desc",font_factor,verbose>1);
4030 if (sub_font_name)
4031 mpctx->osd->sub_font = read_font_desc(sub_font_name, font_factor, verbose>1);
4032 else
4033 mpctx->osd->sub_font = vo_font;
4034 #endif
4035 #ifdef CONFIG_FONTCONFIG
4037 #endif
4039 #ifdef CONFIG_ASS
4040 ass_library = mp_ass_init();
4041 #endif
4043 #ifdef HAVE_RTC
4044 if(opts->rtc)
4046 char *rtc_device = opts->rtc_device;
4047 // seteuid(0); /* Can't hurt to try to get root here */
4048 if ((rtc_fd = open(rtc_device ? rtc_device : "/dev/rtc", O_RDONLY)) < 0)
4049 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Failed to open %s: %s (it should be readable by the user.)\n",
4050 rtc_device ? rtc_device : "/dev/rtc", strerror(errno));
4051 else {
4052 unsigned long irqp = 1024; /* 512 seemed OK. 128 is jerky. */
4054 if (ioctl(rtc_fd, RTC_IRQP_SET, irqp) < 0) {
4055 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Linux RTC init error in ioctl (rtc_irqp_set %lu): %s\n", irqp, strerror(errno));
4056 mp_tmsg(MSGT_CPLAYER, MSGL_HINT, "Try adding \"echo %lu > /proc/sys/dev/rtc/max-user-freq\" to your system startup scripts.\n", irqp);
4057 close (rtc_fd);
4058 rtc_fd = -1;
4059 } else if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
4060 /* variable only by the root */
4061 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC init error in ioctl (rtc_pie_on): %s\n", strerror(errno));
4062 close (rtc_fd);
4063 rtc_fd = -1;
4064 } else
4065 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Using Linux hardware RTC timing (%ldHz).\n", irqp);
4068 if(rtc_fd<0)
4069 #endif /* HAVE_RTC */
4070 mp_msg(MSGT_CPLAYER, MSGL_V, "Using %s timing\n",
4071 opts->softsleep ? "software" : timer_name);
4073 #ifdef HAVE_TERMCAP
4074 load_termcap(NULL); // load key-codes
4075 #endif
4077 // ========== Init keyboard FIFO (connection to libvo) ============
4079 // Init input system
4080 current_module = "init_input";
4081 mpctx->input = mp_input_init(&opts->input);
4082 mp_input_add_key_fd(mpctx->input, -1,0,mplayer_get_key,NULL, mpctx->key_fifo);
4083 if(slave_mode) {
4084 #if USE_FD0_CMD_SELECT
4085 int flags = fcntl(0, F_GETFL);
4086 if (flags != -1)
4087 fcntl(0, F_SETFL, flags | O_NONBLOCK);
4088 #endif
4089 mp_input_add_cmd_fd(mpctx->input, 0,USE_FD0_CMD_SELECT,MP_INPUT_SLAVE_CMD_FUNC,NULL);
4091 else if (opts->consolecontrols)
4092 mp_input_add_key_fd(mpctx->input, 0, 1, read_keys, NULL, mpctx->key_fifo);
4093 // Set the libstream interrupt callback
4094 stream_set_interrupt_callback(mp_input_check_interrupt, mpctx->input);
4096 #ifdef CONFIG_MENU
4097 if(use_menu) {
4098 if(menu_cfg && menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
4099 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
4100 else {
4101 menu_cfg = get_path("menu.conf");
4102 if(menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
4103 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
4104 else {
4105 if(menu_init(mpctx, mpctx->mconfig, mpctx->input,
4106 MPLAYER_CONFDIR "/menu.conf"))
4107 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", MPLAYER_CONFDIR"/menu.conf");
4108 else {
4109 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Menu init failed.\n");
4110 use_menu = 0;
4115 #endif
4117 current_module = NULL;
4119 /// Catch signals
4120 #ifndef __MINGW32__
4121 signal(SIGCHLD,child_sighandler);
4122 #endif
4124 #ifdef CONFIG_CRASH_DEBUG
4125 prog_path = argv[0];
4126 #endif
4127 //========= Catch terminate signals: ================
4128 // terminate requests:
4129 signal(SIGTERM,exit_sighandler); // kill
4130 signal(SIGHUP,exit_sighandler); // kill -HUP / xterm closed
4132 signal(SIGINT,exit_sighandler); // Interrupt from keyboard
4134 signal(SIGQUIT,exit_sighandler); // Quit from keyboard
4135 signal(SIGPIPE,exit_sighandler); // Some window managers cause this
4136 #ifdef CONFIG_SIGHANDLER
4137 // fatal errors:
4138 signal(SIGBUS,exit_sighandler); // bus error
4139 signal(SIGSEGV,exit_sighandler); // segfault
4140 signal(SIGILL,exit_sighandler); // illegal instruction
4141 signal(SIGFPE,exit_sighandler); // floating point exc.
4142 signal(SIGABRT,exit_sighandler); // abort()
4143 #ifdef CONFIG_CRASH_DEBUG
4144 if (crash_debug)
4145 signal(SIGTRAP,exit_sighandler);
4146 #endif
4147 #endif
4149 // ******************* Now, let's see the per-file stuff ********************
4151 play_next_file:
4153 // init global sub numbers
4154 mpctx->global_sub_size = 0;
4155 memset(mpctx->sub_counts, 0, sizeof(mpctx->sub_counts));
4157 if (mpctx->filename) {
4158 load_per_protocol_config (mpctx->mconfig, mpctx->filename);
4159 load_per_extension_config (mpctx->mconfig, mpctx->filename);
4160 load_per_file_config (mpctx->mconfig, mpctx->filename);
4163 if (opts->video_driver_list)
4164 load_per_output_config (mpctx->mconfig, PROFILE_CFG_VO, opts->video_driver_list[0]);
4165 if (opts->audio_driver_list)
4166 load_per_output_config (mpctx->mconfig, PROFILE_CFG_AO, opts->audio_driver_list[0]);
4168 // We must enable getch2 here to be able to interrupt network connection
4169 // or cache filling
4170 if (opts->consolecontrols && !slave_mode) {
4171 if(mpctx->initialized_flags&INITIALIZED_GETCH2)
4172 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"WARNING: getch2_init called twice!\n");
4173 else
4174 getch2_enable(); // prepare stdin for hotkeys...
4175 mpctx->initialized_flags|=INITIALIZED_GETCH2;
4176 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[init getch2]]]\n");
4179 // =================== GUI idle loop (STOP state) ===========================
4180 while (opts->player_idle_mode && !mpctx->filename) {
4181 play_tree_t * entry = NULL;
4182 mp_cmd_t * cmd;
4183 if (mpctx->video_out && mpctx->video_out->config_ok)
4184 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
4185 while (!(cmd = mp_input_get_cmd(mpctx->input, 0, 0))) { // wait for command
4186 if (mpctx->video_out)
4187 vo_check_events(mpctx->video_out);
4188 usec_sleep(20000);
4190 switch (cmd->id) {
4191 case MP_CMD_LOADFILE:
4192 // prepare a tree entry with the new filename
4193 entry = play_tree_new();
4194 play_tree_add_file(entry, cmd->args[0].v.s);
4195 // The entry is added to the main playtree after the switch().
4196 break;
4197 case MP_CMD_LOADLIST:
4198 entry = parse_playlist_file(mpctx->mconfig, cmd->args[0].v.s);
4199 break;
4200 case MP_CMD_QUIT:
4201 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
4202 break;
4203 case MP_CMD_VO_FULLSCREEN:
4204 case MP_CMD_GET_PROPERTY:
4205 case MP_CMD_SET_PROPERTY:
4206 case MP_CMD_STEP_PROPERTY:
4207 run_command(mpctx, cmd);
4208 break;
4211 mp_cmd_free(cmd);
4213 if (entry) { // user entered a command that gave a valid entry
4214 if (mpctx->playtree) // the playtree is always a node with one child. let's clear it
4215 play_tree_free_list(mpctx->playtree->child, 1);
4216 else mpctx->playtree=play_tree_new(); // .. or make a brand new playtree
4218 if (!mpctx->playtree) continue; // couldn't make playtree! wait for next command
4220 play_tree_set_child(mpctx->playtree, entry);
4222 /* Make iterator start at the top the of tree. */
4223 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree, mpctx->mconfig);
4224 if (!mpctx->playtree_iter) continue;
4226 // find the first real item in the tree
4227 if (play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
4228 // no items!
4229 play_tree_iter_free(mpctx->playtree_iter);
4230 mpctx->playtree_iter = NULL;
4231 continue; // wait for next command
4233 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, 1);
4236 //---------------------------------------------------------------------------
4238 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
4239 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL);
4241 if (mpctx->filename) {
4242 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nPlaying %s.\n",
4243 filename_recode(mpctx->filename));
4244 if(use_filename_title && opts->vo_wintitle == NULL)
4245 opts->vo_wintitle = strdup(mp_basename(mpctx->filename));
4248 if (edl_filename) {
4249 if (edl_records) free_edl(edl_records);
4250 next_edl_record = edl_records = edl_parse_file();
4252 if (edl_output_filename) {
4253 if (edl_fd) fclose(edl_fd);
4254 if ((edl_fd = fopen(edl_output_filename, "w")) == NULL)
4256 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Can't open EDL file [%s] for writing.\n",
4257 filename_recode(edl_output_filename));
4261 //==================== Open VOB-Sub ============================
4263 current_module="vobsub";
4264 if (opts->vobsub_name){
4265 vo_vobsub=vobsub_open(opts->vobsub_name,spudec_ifo,1,&vo_spudec);
4266 if(vo_vobsub==NULL)
4267 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load subtitles: %s\n",
4268 filename_recode(opts->vobsub_name));
4269 } else if (opts->sub_auto && mpctx->filename){
4270 char **vob = find_vob_subtitles(opts, mpctx->filename);
4271 for (int i = 0; i < MP_TALLOC_ELEMS(vob); i++) {
4272 vo_vobsub = vobsub_open(vob[i], spudec_ifo, 0, &vo_spudec);
4273 if (vo_vobsub)
4274 break;
4276 talloc_free(vob);
4278 if(vo_vobsub){
4279 mpctx->initialized_flags|=INITIALIZED_VOBSUB;
4280 vobsub_set_from_lang(vo_vobsub, opts->sub_lang);
4281 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
4283 // setup global sub numbering
4284 mpctx->sub_counts[SUB_SOURCE_VOBSUB] = vobsub_get_indexes_count(vo_vobsub);
4287 //============ Open & Sync STREAM --- fork cache2 ====================
4289 mpctx->stream=NULL;
4290 mpctx->demuxer=NULL;
4291 mpctx->d_audio=NULL;
4292 mpctx->d_video=NULL;
4293 mpctx->d_sub = NULL;
4294 mpctx->sh_audio=NULL;
4295 mpctx->sh_video=NULL;
4297 current_module="open_stream";
4298 mpctx->stream = open_stream(mpctx->filename, opts, &mpctx->file_format);
4299 if(!mpctx->stream) { // error...
4300 mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY);
4301 goto goto_next_file;
4303 mpctx->initialized_flags|=INITIALIZED_STREAM;
4305 if(mpctx->file_format == DEMUXER_TYPE_PLAYLIST) {
4306 mp_msg(MSGT_CPLAYER, MSGL_ERR, "\nThis looks like a playlist, but "
4307 "playlist support will not be used automatically.\n"
4308 "MPlayer's playlist code is unsafe and should only be used with "
4309 "trusted sources.\nPlayback will probably fail.\n\n");
4310 #if 0
4311 play_tree_t* entry;
4312 // Handle playlist
4313 current_module="handle_playlist";
4314 mp_msg(MSGT_CPLAYER,MSGL_V,"Parsing playlist %s...\n",
4315 filename_recode(mpctx->filename));
4316 entry = parse_playtree(mpctx->stream, mpctx->mconfig, 0);
4317 mpctx->eof=playtree_add_playlist(mpctx, entry);
4318 goto goto_next_file;
4319 #endif
4321 mpctx->stream->start_pos+=seek_to_byte;
4323 if(stream_dump_type==5){
4324 unsigned char buf[4096];
4325 int len;
4326 FILE *f;
4327 current_module="dumpstream";
4328 stream_reset(mpctx->stream);
4329 stream_seek(mpctx->stream,mpctx->stream->start_pos);
4330 f=fopen(opts->stream_dump_name,"wb");
4331 if(!f){
4332 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
4333 exit_player(mpctx, EXIT_ERROR);
4335 if (opts->chapterrange[0] > 1) {
4336 int chapter = opts->chapterrange[0] - 1;
4337 stream_control(mpctx->stream, STREAM_CTRL_SEEK_TO_CHAPTER, &chapter);
4339 struct stream_dump_progress info;
4340 stream_dump_progress_start(&info);
4341 while(!mpctx->stream->eof && !async_quit_request){
4342 len=stream_read(mpctx->stream,buf,4096);
4343 if(len>0) {
4344 if(fwrite(buf,len,1,f) != 1) {
4345 mp_tmsg(MSGT_GLOBAL,MSGL_FATAL,"%s: Error writing file.\n",opts->stream_dump_name);
4346 exit_player(mpctx, EXIT_ERROR);
4349 stream_dump_progress(&info, len, mpctx->stream);
4350 if (opts->chapterrange[1] > 0) {
4351 int chapter = -1;
4352 if (stream_control(mpctx->stream, STREAM_CTRL_GET_CURRENT_CHAPTER,
4353 &chapter) == STREAM_OK
4354 && chapter + 1 > opts->chapterrange[1])
4355 break;
4358 if(fclose(f)) {
4359 mp_tmsg(MSGT_GLOBAL,MSGL_FATAL,"%s: Error writing file.\n",opts->stream_dump_name);
4360 exit_player(mpctx, EXIT_ERROR);
4362 stream_dump_progress_end(&info, opts->stream_dump_name);
4363 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Stream dump complete.\n");
4364 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4367 #ifdef CONFIG_DVDREAD
4368 if(mpctx->stream->type==STREAMTYPE_DVD){
4369 current_module="dvd lang->id";
4370 if(opts->audio_lang && opts->audio_id==-1) opts->audio_id=dvd_aid_from_lang(mpctx->stream,opts->audio_lang);
4371 if(opts->sub_lang && opts->sub_id==-1) opts->sub_id=dvd_sid_from_lang(mpctx->stream,opts->sub_lang);
4372 // setup global sub numbering
4373 mpctx->sub_counts[SUB_SOURCE_DEMUX] = dvd_number_of_subs(mpctx->stream);
4374 current_module=NULL;
4376 #endif
4378 #ifdef CONFIG_DVDNAV
4379 if(mpctx->stream->type==STREAMTYPE_DVDNAV){
4380 current_module="dvdnav lang->id";
4381 if(opts->audio_lang && opts->audio_id==-1) opts->audio_id=mp_dvdnav_aid_from_lang(mpctx->stream,opts->audio_lang);
4382 dvdsub_lang_id = -3;
4383 if(opts->sub_lang && opts->sub_id==-1)
4384 dvdsub_lang_id = opts->sub_id = mp_dvdnav_sid_from_lang(mpctx->stream,opts->sub_lang);
4385 // setup global sub numbering
4386 mpctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(mpctx->stream);
4387 current_module=NULL;
4389 #endif
4391 // CACHE2: initial prefill: 20% later: 5% (should be set by -cacheopts)
4392 goto_enable_cache:
4393 if(stream_cache_size>0){
4394 int res;
4395 float stream_cache_min_percent = opts->stream_cache_min_percent;
4396 float stream_cache_seek_min_percent = opts->stream_cache_seek_min_percent;
4397 current_module="enable_cache";
4398 res = stream_enable_cache(mpctx->stream,stream_cache_size*1024,
4399 stream_cache_size*1024*(stream_cache_min_percent / 100.0),
4400 stream_cache_size*1024*(stream_cache_seek_min_percent / 100.0));
4401 if(res == 0)
4402 if((mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY))) goto goto_next_file;
4405 //============ Open DEMUXERS --- DETECT file type =======================
4406 current_module="demux_open";
4408 mpctx->demuxer=demux_open(opts, mpctx->stream,mpctx->file_format,opts->audio_id,opts->video_id,opts->sub_id,mpctx->filename);
4410 // HACK to get MOV Reference Files working
4412 if (mpctx->demuxer && mpctx->demuxer->type==DEMUXER_TYPE_PLAYLIST)
4414 unsigned char* playlist_entry;
4415 play_tree_t *list = NULL, *entry = NULL;
4417 current_module="handle_demux_playlist";
4418 while (ds_get_packet(mpctx->demuxer->video,&playlist_entry)>0)
4420 char *temp;
4421 const char *bname;
4423 mp_msg(MSGT_CPLAYER,MSGL_V,"Adding file %s to element entry.\n",
4424 filename_recode(playlist_entry));
4426 bname=mp_basename(playlist_entry);
4427 if ((strlen(bname)>10) && !strncmp(bname,"qt",2) && !strncmp(bname+3,"gateQT",6))
4428 continue;
4430 if (!strcmp(playlist_entry, mpctx->filename)) // ignoring self-reference
4431 continue;
4433 entry = play_tree_new();
4435 if (mpctx->filename && !strcmp(mp_basename(playlist_entry),playlist_entry)) // add reference path of current file
4437 temp=malloc((strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))+strlen(playlist_entry)+1));
4438 if (temp)
4440 strncpy(temp, mpctx->filename, strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename)));
4441 temp[strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))]='\0';
4442 strcat(temp, playlist_entry);
4443 if (!strcmp(temp, mpctx->filename)) {
4444 free(temp);
4445 continue;
4447 play_tree_add_file(entry,temp);
4448 mp_msg(MSGT_CPLAYER,MSGL_V,"Resolving reference to %s.\n",temp);
4449 free(temp);
4452 else
4453 play_tree_add_file(entry,playlist_entry);
4455 if(!list)
4456 list = entry;
4457 else
4458 play_tree_append_entry(list,entry);
4460 free_demuxer(mpctx->demuxer);
4461 mpctx->demuxer = NULL;
4463 if (list)
4465 entry = play_tree_new();
4466 play_tree_set_child(entry,list);
4467 mpctx->stop_play = playtree_add_playlist(mpctx, entry);
4468 goto goto_next_file;
4472 if(!mpctx->demuxer) {
4473 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Failed to recognize file format.\n");
4474 goto goto_next_file;
4477 if (mpctx->demuxer->matroska_data.ordered_chapters)
4478 build_ordered_chapter_timeline(mpctx);
4480 if (mpctx->demuxer->type == DEMUXER_TYPE_EDL)
4481 build_edl_timeline(mpctx);
4483 if (mpctx->timeline) {
4484 mpctx->timeline_part = 0;
4485 mpctx->demuxer = mpctx->timeline[0].source->demuxer;
4487 int part_count = mpctx->num_timeline_parts;
4488 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline contains %d parts from %d "
4489 "sources. Total length %.3f seconds.\n", part_count,
4490 mpctx->num_sources, mpctx->timeline[part_count].start);
4491 mp_msg(MSGT_CPLAYER, MSGL_V, "Source files:\n");
4492 for (int i = 0; i < mpctx->num_sources; i++)
4493 mp_msg(MSGT_CPLAYER, MSGL_V, "%d: %s\n", i,
4494 filename_recode(mpctx->sources[i].demuxer->filename));
4495 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline parts: (number, start, "
4496 "source_start, source):\n");
4497 for (int i = 0; i < part_count; i++) {
4498 struct timeline_part *p = mpctx->timeline + i;
4499 mp_msg(MSGT_CPLAYER, MSGL_V, "%3d %9.3f %9.3f %3td\n", i, p->start,
4500 p->source_start, p->source - mpctx->sources);
4502 mp_msg(MSGT_CPLAYER, MSGL_V, "END %9.3f\n",
4503 mpctx->timeline[part_count].start);
4506 if (!mpctx->sources) {
4507 mpctx->sources = talloc_ptrtype(NULL, mpctx->sources);
4508 *mpctx->sources = (struct content_source){.stream = mpctx->stream,
4509 .demuxer = mpctx->demuxer};
4510 mpctx->num_sources = 1;
4513 mpctx->initialized_flags|=INITIALIZED_DEMUXER;
4515 #ifdef CONFIG_ASS
4516 if (opts->ass_enabled && ass_library) {
4517 for (int j = 0; j < mpctx->num_sources; j++) {
4518 struct demuxer *d = mpctx->sources[j].demuxer;
4519 for (int i = 0; i < d->num_attachments; i++) {
4520 struct demux_attachment *att = d->attachments + i;
4521 if (use_embedded_fonts && attachment_is_font(att))
4522 ass_add_font(ass_library, att->name, att->data, att->data_size);
4526 #endif
4528 current_module="demux_open2";
4530 mpctx->d_audio=mpctx->demuxer->audio;
4531 mpctx->d_video=mpctx->demuxer->video;
4532 mpctx->d_sub=mpctx->demuxer->sub;
4534 if (ts_prog) {
4535 int tmp = ts_prog;
4536 mp_property_do("switch_program", M_PROPERTY_SET, &tmp, mpctx);
4538 // select audio stream
4539 for (int i = 0; i < mpctx->num_sources; i++)
4540 select_audio(mpctx->sources[i].demuxer->audio->demuxer, opts->audio_id,
4541 opts->audio_lang);
4543 // DUMP STREAMS:
4544 if((stream_dump_type)&&(stream_dump_type<4)){
4545 FILE *f;
4546 demux_stream_t *ds=NULL;
4547 current_module="dump";
4548 // select stream to dump
4549 switch(stream_dump_type){
4550 case 1: ds=mpctx->d_audio;break;
4551 case 2: ds=mpctx->d_video;break;
4552 case 3: ds=mpctx->d_sub;break;
4554 if(!ds){
4555 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"dump: FATAL: Selected stream missing!\n");
4556 exit_player(mpctx, EXIT_ERROR);
4558 // disable other streams:
4559 if(mpctx->d_audio && mpctx->d_audio!=ds) {ds_free_packs(mpctx->d_audio); mpctx->d_audio->id=-2; }
4560 if(mpctx->d_video && mpctx->d_video!=ds) {ds_free_packs(mpctx->d_video); mpctx->d_video->id=-2; }
4561 if(mpctx->d_sub && mpctx->d_sub!=ds) {ds_free_packs(mpctx->d_sub); mpctx->d_sub->id=-2; }
4562 // let's dump it!
4563 f=fopen(opts->stream_dump_name,"wb");
4564 if(!f){
4565 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
4566 exit_player(mpctx, EXIT_ERROR);
4568 struct stream_dump_progress info;
4569 stream_dump_progress_start(&info);
4570 while(!ds->eof){
4571 unsigned char* start;
4572 int in_size=ds_get_packet(ds,&start);
4573 if( (mpctx->demuxer->file_format==DEMUXER_TYPE_AVI || mpctx->demuxer->file_format==DEMUXER_TYPE_ASF || mpctx->demuxer->file_format==DEMUXER_TYPE_MOV)
4574 && stream_dump_type==2) fwrite(&in_size,1,4,f);
4575 if(in_size>0) {
4576 fwrite(start,in_size,1,f);
4577 stream_dump_progress(&info, in_size, mpctx->stream);
4579 if (opts->chapterrange[1] > 0) {
4580 int cur_chapter = demuxer_get_current_chapter(mpctx->demuxer, 0);
4581 if(cur_chapter!=-1 && cur_chapter+1 > opts->chapterrange[1])
4582 break;
4585 fclose(f);
4586 stream_dump_progress_end(&info, opts->stream_dump_name);
4587 mp_tmsg(MSGT_CPLAYER ,MSGL_INFO, "Stream dump complete.\n");
4588 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4591 mpctx->sh_audio=mpctx->d_audio->sh;
4592 mpctx->sh_video=mpctx->d_video->sh;
4594 if(mpctx->sh_video){
4596 current_module="video_read_properties";
4597 if(!video_read_properties(mpctx->sh_video)) {
4598 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Video: Cannot read properties.\n");
4599 mpctx->sh_video=mpctx->d_video->sh=NULL;
4600 } else {
4601 mp_tmsg(MSGT_CPLAYER,MSGL_V,"[V] filefmt:%d fourcc:0x%X size:%dx%d fps:%5.3f ftime:=%6.4f\n",
4602 mpctx->demuxer->file_format,mpctx->sh_video->format, mpctx->sh_video->disp_w,mpctx->sh_video->disp_h,
4603 mpctx->sh_video->fps,mpctx->sh_video->frametime
4606 /* need to set fps here for output encoders to pick it up in their init */
4607 if(force_fps){
4608 mpctx->sh_video->fps=force_fps;
4609 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
4611 vo_fps = mpctx->sh_video->fps;
4613 if(!mpctx->sh_video->fps && !force_fps){
4614 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"FPS not specified in the header or invalid, use the -fps option.\n");
4615 mpctx->opts.correct_pts = 1;
4621 if(!mpctx->sh_video && !mpctx->sh_audio){
4622 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL, "No stream found.\n");
4623 #ifdef CONFIG_DVBIN
4624 if(mpctx->stream->type == STREAMTYPE_DVB)
4626 int dir;
4627 int v = mpctx->last_dvb_step;
4628 if(v > 0)
4629 dir = DVB_CHANNEL_HIGHER;
4630 else
4631 dir = DVB_CHANNEL_LOWER;
4633 if(dvb_step_channel(mpctx->stream, dir)) {
4634 mpctx->stop_play = PT_NEXT_ENTRY;
4635 mpctx->dvbin_reopen = 1;
4638 #endif
4639 goto goto_next_file; // exit_player(_("Fatal error"));
4642 /* display clip info */
4643 demux_info_print(mpctx->demuxer);
4645 //================== Read SUBTITLES (DVD & TEXT) ==========================
4646 if(vo_spudec==NULL &&
4647 (mpctx->stream->type==STREAMTYPE_DVD || mpctx->stream->type == STREAMTYPE_DVDNAV)){
4648 init_vo_spudec(mpctx);
4651 // after reading video params we should load subtitles because
4652 // we know fps so now we can adjust subtitle time to ~6 seconds AST
4653 // check .sub
4654 current_module="read_subtitles_file";
4655 double sub_fps = mpctx->sh_video ? mpctx->sh_video->fps : 25;
4656 if(opts->sub_name){
4657 for (i = 0; opts->sub_name[i] != NULL; ++i)
4658 add_subtitles(mpctx, opts->sub_name[i], sub_fps, 0);
4660 if(opts->sub_auto) { // auto load sub file ...
4661 char **tmp = find_text_subtitles(opts, mpctx->filename);
4662 int nsub = MP_TALLOC_ELEMS(tmp);
4663 for (int i = 0; i < nsub; i++)
4664 add_subtitles(mpctx, tmp[i], sub_fps, 1);
4665 talloc_free(tmp);
4667 if (mpctx->set_of_sub_size > 0)
4668 mpctx->sub_counts[SUB_SOURCE_SUBS] = mpctx->set_of_sub_size;
4670 if (select_subtitle(mpctx)) {
4671 if(mpctx->subdata)
4672 switch (stream_dump_type) {
4673 case 3: list_sub_file(mpctx->subdata); break;
4674 case 4: dump_mpsub(mpctx->subdata, mpctx->sh_video->fps); break;
4675 case 6: dump_srt(mpctx->subdata, mpctx->sh_video->fps); break;
4676 case 7: dump_microdvd(mpctx->subdata, mpctx->sh_video->fps); break;
4677 case 8: dump_jacosub(mpctx->subdata, mpctx->sh_video->fps); break;
4678 case 9: dump_sami(mpctx->subdata, mpctx->sh_video->fps); break;
4682 print_file_properties(mpctx, mpctx->filename);
4684 reinit_video_chain(mpctx);
4685 if (mpctx->sh_video) {
4686 if(mpctx->sh_video->output_flags & VFCAP_SPU && vo_spudec)
4687 spudec_set_hw_spu(vo_spudec,mpctx->video_out);
4688 #ifdef CONFIG_FREETYPE
4689 force_load_font = 1;
4690 #endif
4691 } else if (!mpctx->sh_audio)
4692 goto goto_next_file;
4694 //================== MAIN: ==========================
4695 current_module="main";
4697 if (opts->playing_msg) {
4698 char* msg = property_expand_string(mpctx, opts->playing_msg);
4699 mp_msg(MSGT_CPLAYER,MSGL_INFO,"%s",msg);
4700 free(msg);
4704 // Disable the term OSD in verbose mode
4705 if (verbose)
4706 opts->term_osd = 0;
4710 // Make sure old OSD does not stay around,
4711 // e.g. with -fixed-vo and same-resolution files
4712 clear_osd_msgs();
4713 update_osd_msg(mpctx);
4715 //================ SETUP AUDIO ==========================
4717 if(mpctx->sh_audio){
4718 reinit_audio_chain(mpctx);
4719 if (mpctx->sh_audio && mpctx->sh_audio->codec)
4720 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_CODEC=%s\n", mpctx->sh_audio->codec->name);
4723 current_module="av_init";
4725 if(mpctx->sh_video){
4726 mpctx->sh_video->timer=0;
4727 if (! ignore_start)
4728 audio_delay += mpctx->sh_video->stream_delay;
4730 if(mpctx->sh_audio){
4731 if (start_volume >= 0)
4732 mixer_setvolume(&mpctx->mixer, start_volume, start_volume);
4733 if (! ignore_start)
4734 audio_delay -= mpctx->sh_audio->stream_delay;
4735 mpctx->delay=-audio_delay;
4738 if(!mpctx->sh_audio){
4739 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Audio: no sound\n");
4740 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused audio chunks.\n",mpctx->d_audio->packs);
4741 ds_free_packs(mpctx->d_audio); // free buffered chunks
4742 //mpctx->d_audio->id=-2; // do not read audio chunks
4743 //uninit_player(mpctx, INITIALIZED_AO); // close device
4745 if(!mpctx->sh_video){
4746 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Video: no video\n");
4747 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused video chunks.\n",mpctx->d_video->packs);
4748 ds_free_packs(mpctx->d_video);
4749 mpctx->d_video->id=-2;
4750 //if(!fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
4753 if (!mpctx->sh_video && !mpctx->sh_audio)
4754 goto goto_next_file;
4756 //if(demuxer->file_format!=DEMUXER_TYPE_AVI) pts_from_bps=0; // it must be 0 for mpeg/asf!
4757 if(force_fps && mpctx->sh_video){
4758 vo_fps = mpctx->sh_video->fps=force_fps;
4759 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
4760 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"FPS forced to be %5.3f (ftime: %5.3f).\n",mpctx->sh_video->fps,mpctx->sh_video->frametime);
4763 mp_input_set_section(mpctx->input, NULL);
4764 //TODO: add desired (stream-based) sections here
4765 if (mpctx->stream->type==STREAMTYPE_TV) mp_input_set_section(mpctx->input, "tv");
4766 if (mpctx->stream->type==STREAMTYPE_DVDNAV) mp_input_set_section(mpctx->input, "dvdnav");
4768 //==================== START PLAYING =======================
4770 if(opts->loop_times>1) opts->loop_times--; else
4771 if(opts->loop_times==1) opts->loop_times = -1;
4773 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Starting playback...\n");
4775 total_time_usage_start=GetTimer();
4776 audio_time_usage=0; video_time_usage=0; vout_time_usage=0;
4777 total_frame_cnt=0; drop_frame_cnt=0; // fix for multifile fps benchmark
4778 play_n_frames=play_n_frames_mf;
4780 if(play_n_frames==0){
4781 mpctx->stop_play=PT_NEXT_ENTRY; goto goto_next_file;
4784 mpctx->time_frame = 0;
4785 mpctx->drop_message_shown = 0;
4786 mpctx->restart_playback = true;
4787 mpctx->video_pts = 0;
4788 mpctx->hrseek_active = false;
4789 mpctx->hrseek_framedrop = false;
4790 mpctx->step_frames = 0;
4791 mpctx->total_avsync_change = 0;
4792 mpctx->last_chapter_seek = -1;
4794 // If there's a timeline force an absolute seek to initialize state
4795 if (seek_to_sec || mpctx->timeline) {
4796 queue_seek(mpctx, MPSEEK_ABSOLUTE, seek_to_sec, 0);
4797 seek(mpctx, mpctx->seek, false);
4798 end_at.pos += seek_to_sec;
4800 if (opts->chapterrange[0] > 0) {
4801 double pts;
4802 if (seek_chapter(mpctx, opts->chapterrange[0]-1, &pts, NULL) >= 0
4803 && pts > -1.0) {
4804 queue_seek(mpctx, MPSEEK_ABSOLUTE, pts, 0);
4805 seek(mpctx, mpctx->seek, false);
4809 if (end_at.type == END_AT_SIZE) {
4810 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Option -endpos in MPlayer does not yet support size units.\n");
4811 end_at.type = END_AT_NONE;
4814 #ifdef CONFIG_DVDNAV
4815 mp_dvdnav_context_free(mpctx);
4816 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4817 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
4818 mp_dvdnav_cell_has_changed(mpctx->stream,1);
4820 #endif
4822 mpctx->seek = (struct seek_params){0};
4823 get_relative_time(mpctx); // reset current delta
4824 // Make sure VO knows current pause state
4825 if (mpctx->sh_video)
4826 vo_control(mpctx->video_out, mpctx->paused ? VOCTRL_PAUSE : VOCTRL_RESUME,
4827 NULL);
4829 while (!mpctx->stop_play)
4830 run_playloop(mpctx);
4832 mp_msg(MSGT_GLOBAL,MSGL_V,"EOF code: %d \n",mpctx->stop_play);
4834 #ifdef CONFIG_DVBIN
4835 if(mpctx->dvbin_reopen)
4837 mpctx->stop_play = 0;
4838 uninit_player(mpctx, INITIALIZED_ALL-(INITIALIZED_STREAM|INITIALIZED_GETCH2|(opts->fixed_vo?INITIALIZED_VO:0)));
4839 cache_uninit(mpctx->stream);
4840 mpctx->dvbin_reopen = 0;
4841 goto goto_enable_cache;
4843 #endif
4846 goto_next_file: // don't jump here after ao/vo/getch initialization!
4848 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\n");
4850 if (opts->benchmark) {
4851 double tot=video_time_usage+vout_time_usage+audio_time_usage;
4852 double total_time_usage;
4853 total_time_usage_start=GetTimer()-total_time_usage_start;
4854 total_time_usage = (float)total_time_usage_start*0.000001;
4855 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\nBENCHMARKs: VC:%8.3fs VO:%8.3fs A:%8.3fs Sys:%8.3fs = %8.3fs\n",
4856 video_time_usage,vout_time_usage,audio_time_usage,
4857 total_time_usage-tot,total_time_usage);
4858 if(total_time_usage>0.0)
4859 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARK%%: VC:%8.4f%% VO:%8.4f%% A:%8.4f%% Sys:%8.4f%% = %8.4f%%\n",
4860 100.0*video_time_usage/total_time_usage,
4861 100.0*vout_time_usage/total_time_usage,
4862 100.0*audio_time_usage/total_time_usage,
4863 100.0*(total_time_usage-tot)/total_time_usage,
4864 100.0);
4865 if(total_frame_cnt && frame_dropping)
4866 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARKn: disp: %d (%3.2f fps) drop: %d (%d%%) total: %d (%3.2f fps)\n",
4867 total_frame_cnt-drop_frame_cnt,
4868 (total_time_usage>0.5)?((total_frame_cnt-drop_frame_cnt)/total_time_usage):0,
4869 drop_frame_cnt,
4870 100*drop_frame_cnt/total_frame_cnt,
4871 total_frame_cnt,
4872 (total_time_usage>0.5)?(total_frame_cnt/total_time_usage):0);
4875 // time to uninit all, except global stuff:
4876 int uninitialize_parts = INITIALIZED_ALL;
4877 if (opts->fixed_vo)
4878 uninitialize_parts -= INITIALIZED_VO;
4879 if (opts->gapless_audio && mpctx->stop_play == AT_END_OF_FILE)
4880 uninitialize_parts -= INITIALIZED_AO;
4881 uninit_player(mpctx, uninitialize_parts);
4883 if(mpctx->set_of_sub_size > 0) {
4884 current_module="sub_free";
4885 for(i = 0; i < mpctx->set_of_sub_size; ++i) {
4886 sub_free(mpctx->set_of_subtitles[i]);
4887 #ifdef CONFIG_ASS
4888 if(mpctx->set_of_ass_tracks[i])
4889 ass_free_track( mpctx->set_of_ass_tracks[i] );
4890 #endif
4892 mpctx->set_of_sub_size = 0;
4894 mpctx->vo_sub_last = vo_sub=NULL;
4895 mpctx->subdata=NULL;
4896 #ifdef CONFIG_ASS
4897 mpctx->osd->ass_track = NULL;
4898 if(ass_library)
4899 ass_clear_fonts(ass_library);
4900 #endif
4902 if (!mpctx->stop_play) // In case some goto jumped here...
4903 mpctx->stop_play = PT_NEXT_ENTRY;
4905 int playtree_direction = 1;
4907 if(mpctx->stop_play == PT_NEXT_ENTRY || mpctx->stop_play == PT_PREV_ENTRY) {
4908 if(play_tree_iter_step(mpctx->playtree_iter,mpctx->play_tree_step,0) != PLAY_TREE_ITER_ENTRY) {
4909 play_tree_iter_free(mpctx->playtree_iter);
4910 mpctx->playtree_iter = NULL;
4912 mpctx->play_tree_step = 1;
4913 } else if(mpctx->stop_play == PT_UP_NEXT || mpctx->stop_play == PT_UP_PREV) {
4914 int direction = mpctx->stop_play == PT_UP_NEXT ? 1 : -1;
4915 if(mpctx->playtree_iter) {
4916 if(play_tree_iter_up_step(mpctx->playtree_iter,direction,0) != PLAY_TREE_ITER_ENTRY) {
4917 play_tree_iter_free(mpctx->playtree_iter);
4918 mpctx->playtree_iter = NULL;
4921 } else if (mpctx->stop_play == PT_STOP) {
4922 play_tree_iter_free(mpctx->playtree_iter);
4923 mpctx->playtree_iter = NULL;
4924 } else { // NEXT PREV SRC
4925 playtree_direction = mpctx->stop_play == PT_PREV_SRC ? -1 : 1;
4928 while(mpctx->playtree_iter != NULL) {
4929 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, playtree_direction);
4930 if(mpctx->filename == NULL) {
4931 if(play_tree_iter_step(mpctx->playtree_iter, playtree_direction, 0) != PLAY_TREE_ITER_ENTRY) {
4932 play_tree_iter_free(mpctx->playtree_iter);
4933 mpctx->playtree_iter = NULL;
4935 } else
4936 break;
4939 if (mpctx->playtree_iter != NULL || opts->player_idle_mode) {
4940 if(!mpctx->playtree_iter) mpctx->filename = NULL;
4941 mpctx->stop_play = 0;
4942 goto play_next_file;
4946 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4948 return 1;
4950 #endif /* DISABLE_MAIN */