ao: fix crash after ao init failure (from recent 3a5fd15fa2)
[mplayer/greg.git] / mplayer.c
blob0e519d20a62f6f103ed3a071b255e4ae35c11acf
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 "\n"
216 " * * * SEE THE MAN PAGE FOR DETAILS, FURTHER (ADVANCED) OPTIONS AND KEYS * * *\n"
217 "\n");
220 #define Exit_SIGILL_RTCpuSel _(\
221 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
222 " It may be a bug in our new runtime CPU-detection code...\n"\
223 " Please read DOCS/HTML/en/bugreports.html.\n")
225 #define Exit_SIGILL _(\
226 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
227 " It usually happens when you run it on a CPU different than the one it was\n"\
228 " compiled/optimized for.\n"\
229 " Verify this!\n")
231 #define Exit_SIGSEGV_SIGFPE _(\
232 "- MPlayer crashed by bad usage of CPU/FPU/RAM.\n"\
233 " Recompile MPlayer with --enable-debug and make a 'gdb' backtrace and\n"\
234 " disassembly. Details in DOCS/HTML/en/bugreports_what.html#bugreports_crash.\n")
236 #define Exit_SIGCRASH _(\
237 "- MPlayer crashed. This shouldn't happen.\n"\
238 " It can be a bug in the MPlayer code _or_ in your drivers _or_ in your\n"\
239 " gcc version. If you think it's MPlayer's fault, please read\n"\
240 " DOCS/HTML/en/bugreports.html and follow the instructions there. We can't and\n"\
241 " won't help unless you provide this information when reporting a possible bug.\n")
243 #define SystemTooSlow _("\n\n"\
244 " ************************************************\n"\
245 " **** Your system is too SLOW to play this! ****\n"\
246 " ************************************************\n\n"\
247 "Possible reasons, problems, workarounds:\n"\
248 "- Most common: broken/buggy _audio_ driver\n"\
249 " - Try -ao sdl or use the OSS emulation of ALSA.\n"\
250 " - Experiment with different values for -autosync, 30 is a good start.\n"\
251 "- Slow video output\n"\
252 " - Try a different -vo driver (-vo help for a list) or try -framedrop!\n"\
253 "- Slow CPU\n"\
254 " - Don't try to play a big DVD/DivX on a slow CPU! Try some of the lavdopts,\n"\
255 " e.g. -vfm ffmpeg -lavdopts lowres=1:fast:skiploopfilter=all.\n"\
256 "- Broken file\n"\
257 " - Try various combinations of -nobps -ni -forceidx -mc 0.\n"\
258 "- Slow media (NFS/SMB mounts, DVD, VCD etc)\n"\
259 " - Try -cache 8192.\n"\
260 "- Are you using -cache to play a non-interleaved AVI file?\n"\
261 " - Try -nocache.\n"\
262 "Read DOCS/HTML/en/video.html for tuning/speedup tips.\n"\
263 "If none of this helps you, read DOCS/HTML/en/bugreports.html.\n\n")
266 //**************************************************************************//
267 //**************************************************************************//
269 #include "mp_fifo.h"
271 // benchmark:
272 double video_time_usage=0;
273 double vout_time_usage=0;
274 static double audio_time_usage=0;
275 static int total_time_usage_start=0;
276 static int total_frame_cnt=0;
277 static int drop_frame_cnt=0; // total number of dropped frames
279 // options:
280 static int output_quality=0;
282 // seek:
283 static double seek_to_sec;
284 static off_t seek_to_byte=0;
285 static off_t step_sec=0;
287 static m_time_size_t end_at = { .type = END_AT_NONE, .pos = 0 };
289 // codecs:
290 char **audio_codec_list=NULL; // override audio codec
291 char **video_codec_list=NULL; // override video codec
292 char **audio_fm_list=NULL; // override audio codec family
293 char **video_fm_list=NULL; // override video codec family
295 // this dvdsub_id was selected via slang
296 // use this to allow dvdnav to follow -slang across stream resets,
297 // in particular the subtitle ID for a language changes
298 int dvdsub_lang_id;
299 int vobsub_id=-1;
300 static char* spudec_ifo=NULL;
301 int forced_subs_only=0;
302 int file_filter=1;
304 // cache2:
305 int stream_cache_size=-1;
307 // dump:
308 int stream_dump_type=0;
310 // A-V sync:
311 static float default_max_pts_correction=-1;//0.01f;
312 float audio_delay=0;
313 static int ignore_start=0;
315 double force_fps=0;
316 static int force_srate=0;
317 int frame_dropping=0; // option 0=no drop 1= drop vo 2= drop decode
318 static int play_n_frames=-1;
319 static int play_n_frames_mf=-1;
321 // sub:
322 char *font_name=NULL;
323 char *sub_font_name=NULL;
324 extern int font_fontconfig;
325 float font_factor=0.75;
326 float sub_delay=0;
327 float sub_fps=0;
328 int subcc_enabled=0;
329 int suboverlap_enabled = 1;
331 #include "sub/ass_mp.h"
333 char* current_module=NULL; // for debugging
336 // ---
338 #ifdef CONFIG_MENU
339 #include "m_struct.h"
340 #include "libmenu/menu.h"
341 static const vf_info_t* const libmenu_vfs[] = {
342 &vf_info_menu,
343 NULL
345 static vf_instance_t* vf_menu = NULL;
346 int use_menu = 0;
347 static char* menu_cfg = NULL;
348 static char* menu_root = "main";
349 #endif
352 edl_record_ptr edl_records = NULL; ///< EDL entries memory area
353 edl_record_ptr next_edl_record = NULL; ///< only for traversing edl_records
354 FILE* edl_fd = NULL; ///< fd to write to when in -edlout mode.
355 int use_filedir_conf;
356 int use_filename_title;
358 #include "mpcommon.h"
359 #include "command.h"
361 #include "metadata.h"
363 const void *mpctx_get_video_out(MPContext *mpctx)
365 return mpctx->video_out;
368 void *mpctx_get_demuxer(MPContext *mpctx)
370 return mpctx->demuxer;
373 void *mpctx_get_playtree_iter(MPContext *mpctx)
375 return mpctx->playtree_iter;
378 void *mpctx_get_mixer(MPContext *mpctx)
380 return &mpctx->mixer;
383 int mpctx_get_global_sub_size(MPContext *mpctx)
385 return mpctx->global_sub_size;
388 int mpctx_get_osd_function(MPContext *mpctx)
390 return mpctx->osd_function;
393 static float get_relative_time(struct MPContext *mpctx)
395 unsigned int new_time = GetTimer();
396 unsigned int delta = new_time - mpctx->last_time;
397 mpctx->last_time = new_time;
398 return delta * 0.000001;
401 static int is_valid_metadata_type(struct MPContext *mpctx, metadata_t type) {
402 switch (type)
404 /* check for valid video stream */
405 case META_VIDEO_CODEC:
406 case META_VIDEO_BITRATE:
407 case META_VIDEO_RESOLUTION:
409 if (!mpctx->sh_video)
410 return 0;
411 break;
414 /* check for valid audio stream */
415 case META_AUDIO_CODEC:
416 case META_AUDIO_BITRATE:
417 case META_AUDIO_SAMPLES:
419 if (!mpctx->sh_audio)
420 return 0;
421 break;
424 /* check for valid demuxer */
425 case META_INFO_TITLE:
426 case META_INFO_ARTIST:
427 case META_INFO_ALBUM:
428 case META_INFO_YEAR:
429 case META_INFO_COMMENT:
430 case META_INFO_TRACK:
431 case META_INFO_GENRE:
433 if (!mpctx->demuxer)
434 return 0;
435 break;
438 default:
439 break;
442 return 1;
445 static char *get_demuxer_info(struct MPContext *mpctx, char *tag) {
446 char **info = mpctx->demuxer->info;
447 int n;
449 if (!info || !tag)
450 return talloc_strdup(NULL, "");
452 for (n = 0; info[2*n] != NULL ; n++)
453 if (!strcasecmp (info[2*n], tag))
454 break;
456 return talloc_strdup(NULL, info[2*n+1] ? info[2*n+1] : "");
459 char *get_metadata(struct MPContext *mpctx, metadata_t type)
461 sh_audio_t * const sh_audio = mpctx->sh_audio;
462 sh_video_t * const sh_video = mpctx->sh_video;
464 if (!is_valid_metadata_type(mpctx, type))
465 return NULL;
467 switch (type) {
468 case META_NAME:
469 return talloc_strdup(NULL, mp_basename(mpctx->filename));
470 case META_VIDEO_CODEC:
471 if (sh_video->format == 0x10000001)
472 return talloc_strdup(NULL, "mpeg1");
473 else if (sh_video->format == 0x10000002)
474 return talloc_strdup(NULL, "mpeg2");
475 else if (sh_video->format == 0x10000004)
476 return talloc_strdup(NULL, "mpeg4");
477 else if (sh_video->format == 0x10000005)
478 return talloc_strdup(NULL, "h264");
479 else if (sh_video->format >= 0x20202020)
480 return talloc_asprintf(NULL, "%.4s", (char *) &sh_video->format);
481 else
482 return talloc_asprintf(NULL, "0x%08X", sh_video->format);
483 case META_VIDEO_BITRATE:
484 return talloc_asprintf(NULL, "%d kbps",
485 (int) (sh_video->i_bps * 8 / 1024));
486 case META_VIDEO_RESOLUTION:
487 return talloc_asprintf(NULL, "%d x %d", sh_video->disp_w,
488 sh_video->disp_h);
489 case META_AUDIO_CODEC:
490 if (sh_audio->codec && sh_audio->codec->name)
491 return talloc_strdup(NULL, sh_audio->codec->name);
492 return talloc_strdup(NULL, "");
493 case META_AUDIO_BITRATE:
494 return talloc_asprintf(NULL, "%d kbps",
495 (int) (sh_audio->i_bps * 8/1000));
496 case META_AUDIO_SAMPLES:
497 return talloc_asprintf(NULL, "%d Hz, %d ch.", sh_audio->samplerate,
498 sh_audio->channels);
500 /* check for valid demuxer */
501 case META_INFO_TITLE:
502 return get_demuxer_info(mpctx, "Title");
504 case META_INFO_ARTIST:
505 return get_demuxer_info(mpctx, "Artist");
507 case META_INFO_ALBUM:
508 return get_demuxer_info(mpctx, "Album");
510 case META_INFO_YEAR:
511 return get_demuxer_info(mpctx, "Year");
513 case META_INFO_COMMENT:
514 return get_demuxer_info(mpctx, "Comment");
516 case META_INFO_TRACK:
517 return get_demuxer_info(mpctx, "Track");
519 case META_INFO_GENRE:
520 return get_demuxer_info(mpctx, "Genre");
522 default:
523 break;
526 return talloc_strdup(NULL, "");
529 static void print_file_properties(struct MPContext *mpctx, const char *filename)
531 double start_pts = MP_NOPTS_VALUE;
532 double video_start_pts = MP_NOPTS_VALUE;
533 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_FILENAME=%s\n",
534 filename_recode(filename));
535 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_DEMUXER=%s\n", mpctx->demuxer->desc->name);
536 if (mpctx->sh_video) {
537 /* Assume FOURCC if all bytes >= 0x20 (' ') */
538 if (mpctx->sh_video->format >= 0x20202020)
539 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=%.4s\n", (char *)&mpctx->sh_video->format);
540 else
541 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=0x%08X\n", mpctx->sh_video->format);
542 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_BITRATE=%d\n", mpctx->sh_video->i_bps*8);
543 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_WIDTH=%d\n", mpctx->sh_video->disp_w);
544 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_HEIGHT=%d\n", mpctx->sh_video->disp_h);
545 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FPS=%5.3f\n", mpctx->sh_video->fps);
546 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_ASPECT=%1.4f\n", mpctx->sh_video->aspect);
547 video_start_pts = ds_get_next_pts(mpctx->d_video);
549 if (mpctx->sh_audio) {
550 /* Assume FOURCC if all bytes >= 0x20 (' ') */
551 if (mpctx->sh_audio->format >= 0x20202020)
552 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_FORMAT=%.4s\n", (char *)&mpctx->sh_audio->format);
553 else
554 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_FORMAT=%d\n", mpctx->sh_audio->format);
555 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_BITRATE=%d\n", mpctx->sh_audio->i_bps*8);
556 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_RATE=%d\n", mpctx->sh_audio->samplerate);
557 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_NCH=%d\n", mpctx->sh_audio->channels);
558 start_pts = ds_get_next_pts(mpctx->d_audio);
560 if (video_start_pts != MP_NOPTS_VALUE) {
561 if (start_pts == MP_NOPTS_VALUE || !mpctx->sh_audio ||
562 (mpctx->sh_video && video_start_pts < start_pts))
563 start_pts = video_start_pts;
565 if (start_pts != MP_NOPTS_VALUE)
566 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_START_TIME=%.2f\n", start_pts);
567 else
568 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_START_TIME=unknown\n");
569 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_LENGTH=%.2f\n", get_time_length(mpctx));
570 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_SEEKABLE=%d\n",
571 mpctx->stream->seek && (!mpctx->demuxer || mpctx->demuxer->seekable));
572 if (mpctx->demuxer) {
573 if (mpctx->demuxer->num_chapters == 0)
574 stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_NUM_CHAPTERS, &mpctx->demuxer->num_chapters);
575 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_CHAPTERS=%d\n", mpctx->demuxer->num_chapters);
579 /// step size of mixer changes
580 int volstep = 3;
582 #ifdef CONFIG_DVDNAV
583 static void mp_dvdnav_context_free(MPContext *ctx){
584 if (ctx->nav_smpi) free_mp_image(ctx->nav_smpi);
585 ctx->nav_smpi = NULL;
586 free(ctx->nav_buffer);
587 ctx->nav_buffer = NULL;
588 ctx->nav_start = NULL;
589 ctx->nav_in_size = 0;
591 #endif
593 static void uninit_subs(struct demuxer *demuxer)
595 for (int i = 0; i < MAX_S_STREAMS; i++) {
596 struct sh_sub *sh = demuxer->s_streams[i];
597 if (sh && sh->initialized)
598 sub_uninit(sh);
602 void uninit_player(struct MPContext *mpctx, unsigned int mask){
603 mask &= mpctx->initialized_flags;
605 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n*** uninit(0x%X)\n",mask);
607 if(mask&INITIALIZED_ACODEC){
608 mpctx->initialized_flags&=~INITIALIZED_ACODEC;
609 current_module="uninit_acodec";
610 if(mpctx->sh_audio) uninit_audio(mpctx->sh_audio);
611 mpctx->sh_audio=NULL;
612 mpctx->mixer.afilter = NULL;
615 if (mask & INITIALIZED_SUB) {
616 mpctx->initialized_flags &= ~INITIALIZED_SUB;
617 if (mpctx->d_sub->sh)
618 sub_switchoff(mpctx->d_sub->sh, mpctx->osd);
621 if(mask&INITIALIZED_VCODEC){
622 mpctx->initialized_flags&=~INITIALIZED_VCODEC;
623 current_module="uninit_vcodec";
624 if(mpctx->sh_video) uninit_video(mpctx->sh_video);
625 mpctx->sh_video=NULL;
626 #ifdef CONFIG_MENU
627 vf_menu=NULL;
628 #endif
631 if(mask&INITIALIZED_DEMUXER){
632 mpctx->initialized_flags&=~INITIALIZED_DEMUXER;
633 current_module="free_demuxer";
634 if (mpctx->num_sources) {
635 mpctx->demuxer = mpctx->sources[0].demuxer;
636 for (int i = 1; i < mpctx->num_sources; i++) {
637 uninit_subs(mpctx->sources[i].demuxer);
638 free_stream(mpctx->sources[i].stream);
639 free_demuxer(mpctx->sources[i].demuxer);
642 talloc_free(mpctx->sources);
643 mpctx->sources = NULL;
644 mpctx->num_sources = 0;
645 talloc_free(mpctx->timeline);
646 mpctx->timeline = NULL;
647 mpctx->num_timeline_parts = 0;
648 talloc_free(mpctx->chapters);
649 mpctx->chapters = NULL;
650 mpctx->num_chapters = 0;
651 mpctx->video_offset = 0;
652 if(mpctx->demuxer){
653 mpctx->stream=mpctx->demuxer->stream;
654 uninit_subs(mpctx->demuxer);
655 free_demuxer(mpctx->demuxer);
657 mpctx->demuxer=NULL;
660 // kill the cache process:
661 if(mask&INITIALIZED_STREAM){
662 mpctx->initialized_flags&=~INITIALIZED_STREAM;
663 current_module="uninit_stream";
664 if(mpctx->stream) free_stream(mpctx->stream);
665 mpctx->stream=NULL;
668 if(mask&INITIALIZED_VO){
669 mpctx->initialized_flags&=~INITIALIZED_VO;
670 current_module="uninit_vo";
671 vo_destroy(mpctx->video_out);
672 mpctx->video_out=NULL;
673 #ifdef CONFIG_DVDNAV
674 mp_dvdnav_context_free(mpctx);
675 #endif
678 // Must be after libvo uninit, as few vo drivers (svgalib) have tty code.
679 if(mask&INITIALIZED_GETCH2){
680 mpctx->initialized_flags&=~INITIALIZED_GETCH2;
681 current_module="uninit_getch2";
682 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[uninit getch2]]]\n");
683 // restore terminal:
684 getch2_disable();
687 if(mask&INITIALIZED_VOBSUB){
688 mpctx->initialized_flags&=~INITIALIZED_VOBSUB;
689 current_module="uninit_vobsub";
690 if(vo_vobsub) vobsub_close(vo_vobsub);
691 vo_vobsub=NULL;
694 if (mask&INITIALIZED_SPUDEC){
695 mpctx->initialized_flags&=~INITIALIZED_SPUDEC;
696 current_module="uninit_spudec";
697 spudec_free(vo_spudec);
698 vo_spudec=NULL;
701 if(mask&INITIALIZED_AO){
702 mpctx->initialized_flags&=~INITIALIZED_AO;
703 current_module="uninit_ao";
704 if (mpctx->edl_muted) mixer_mute(&mpctx->mixer);
705 if (mpctx->ao)
706 ao_uninit(mpctx->ao, mpctx->stop_play != AT_END_OF_FILE);
707 mpctx->ao = NULL;
710 current_module=NULL;
713 void exit_player_with_rc(struct MPContext *mpctx, enum exit_reason how, int rc)
715 if (mpctx->user_muted && !mpctx->edl_muted) mixer_mute(&mpctx->mixer);
716 uninit_player(mpctx, INITIALIZED_ALL);
717 #if defined(__MINGW32__) || defined(__CYGWIN__)
718 timeEndPeriod(1);
719 #endif
720 #ifdef CONFIG_X11
721 vo_uninit(mpctx->x11_state); // Close the X11 connection (if any is open).
722 #endif
724 current_module="uninit_input";
725 mp_input_uninit(mpctx->input);
726 #ifdef CONFIG_MENU
727 if (use_menu)
728 menu_uninit();
729 #endif
731 #ifdef CONFIG_FREETYPE
732 current_module="uninit_font";
733 if (mpctx->osd && mpctx->osd->sub_font != vo_font)
734 free_font_desc(mpctx->osd->sub_font);
735 free_font_desc(vo_font);
736 vo_font = NULL;
737 done_freetype();
738 #endif
739 osd_free(mpctx->osd);
741 #ifdef CONFIG_ASS
742 ass_library_done(ass_library);
743 ass_library = NULL;
744 #endif
746 current_module="exit_player";
748 // free mplayer config
749 if(mpctx->mconfig)
750 m_config_free(mpctx->mconfig);
751 mpctx->mconfig = NULL;
753 if(mpctx->playtree_iter)
754 play_tree_iter_free(mpctx->playtree_iter);
755 mpctx->playtree_iter = NULL;
756 if(mpctx->playtree)
757 play_tree_free(mpctx->playtree, 1);
758 mpctx->playtree = NULL;
760 talloc_free(mpctx->key_fifo);
762 free(edl_records); // free mem allocated for EDL
763 edl_records = NULL;
764 switch(how) {
765 case EXIT_QUIT:
766 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Quit");
767 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=QUIT\n");
768 break;
769 case EXIT_EOF:
770 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","End of file");
771 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=EOF\n");
772 break;
773 case EXIT_ERROR:
774 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Fatal error");
775 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=ERROR\n");
776 break;
777 default:
778 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=NONE\n");
780 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"max framesize was %d bytes\n",max_framesize);
782 exit(rc);
785 static void exit_player(struct MPContext *mpctx, enum exit_reason how)
787 exit_player_with_rc(mpctx, how, 1);
790 #ifndef __MINGW32__
791 static void child_sighandler(int x){
792 pid_t pid;
793 while((pid=waitpid(-1,NULL,WNOHANG)) > 0);
795 #endif
797 #ifdef CONFIG_CRASH_DEBUG
798 static char *prog_path;
799 static int crash_debug = 0;
800 #endif
802 static void exit_sighandler(int x){
803 static int sig_count=0;
804 #ifdef CONFIG_CRASH_DEBUG
805 if (!crash_debug || x != SIGTRAP)
806 #endif
807 ++sig_count;
808 if(sig_count==5)
810 /* We're crashing bad and can't uninit cleanly :(
811 * by popular request, we make one last (dirty)
812 * effort to restore the user's
813 * terminal. */
814 getch2_disable();
815 exit(1);
817 if(sig_count==6) exit(1);
818 if(sig_count>6){
819 // can't stop :(
820 #ifndef __MINGW32__
821 kill(getpid(),SIGKILL);
822 #endif
824 mp_msg(MSGT_CPLAYER, MSGL_FATAL, "\n");
825 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,
826 "\nMPlayer interrupted by signal %d in module: %s\n", x,
827 current_module ? current_module : "unknown");
828 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SIGNAL=%d\n", x);
829 if(sig_count<=1)
830 switch(x){
831 case SIGINT:
832 case SIGPIPE:
833 case SIGQUIT:
834 case SIGTERM:
835 case SIGKILL:
836 async_quit_request = 1;
837 return; // killed from keyboard (^C) or killed [-9]
838 case SIGILL:
839 #if CONFIG_RUNTIME_CPUDETECT
840 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL_RTCpuSel);
841 #else
842 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL);
843 #endif
844 case SIGFPE:
845 case SIGSEGV:
846 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGSEGV_SIGFPE);
847 default:
848 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGCRASH);
849 #ifdef CONFIG_CRASH_DEBUG
850 if (crash_debug) {
851 int gdb_pid;
852 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forking...\n");
853 gdb_pid = fork();
854 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forked...\n");
855 if (gdb_pid == 0) { // We are the child
856 char spid[20];
857 snprintf(spid, sizeof(spid), "%i", getppid());
858 getch2_disable(); // allow terminal to work properly with gdb
859 if (execlp("gdb", "gdb", prog_path, spid, "-ex", "bt", NULL) == -1)
860 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't start gdb\n");
861 } else if (gdb_pid < 0)
862 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't fork\n");
863 else {
864 waitpid(gdb_pid, NULL, 0);
866 if (x == SIGTRAP) return;
868 #endif
870 getch2_disable();
871 exit(1);
874 #include "cfg-mplayer.h"
876 static int cfg_include(m_option_t *conf, char *filename)
878 return m_config_parse_config_file(conf->priv, filename);
881 #define DEF_CONFIG "# Write your default config options here!\n\n\n"
883 static void parse_cfgfiles(struct MPContext *mpctx, m_config_t* conf)
885 struct MPOpts *opts = &mpctx->opts;
886 char *conffile;
887 int conffile_fd;
888 if (!(opts->noconfig & 2) &&
889 m_config_parse_config_file(conf, MPLAYER_CONFDIR "/mplayer.conf") < 0)
890 exit_player(mpctx, EXIT_NONE);
891 if ((conffile = get_path("")) == NULL) {
892 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"Cannot find HOME directory.\n");
893 } else {
894 #ifdef __MINGW32__
895 mkdir(conffile);
896 #else
897 mkdir(conffile, 0777);
898 #endif
899 free(conffile);
900 if ((conffile = get_path("config")) == NULL) {
901 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"get_path(\"config\") problem\n");
902 } else {
903 if ((conffile_fd = open(conffile, O_CREAT | O_EXCL | O_WRONLY, 0666)) != -1) {
904 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Creating config file: %s\n", conffile);
905 write(conffile_fd, DEF_CONFIG, sizeof(DEF_CONFIG) - 1);
906 close(conffile_fd);
908 if (!(opts->noconfig & 1) &&
909 m_config_parse_config_file(conf, conffile) < 0)
910 exit_player(mpctx, EXIT_NONE);
911 free(conffile);
916 #define PROFILE_CFG_PROTOCOL "protocol."
918 static void load_per_protocol_config (m_config_t* conf, const char *const file)
920 char *str;
921 char protocol[strlen (PROFILE_CFG_PROTOCOL) + strlen (file) + 1];
922 m_profile_t *p;
924 /* does filename actually uses a protocol ? */
925 str = strstr (file, "://");
926 if (!str)
927 return;
929 sprintf (protocol, "%s%s", PROFILE_CFG_PROTOCOL, file);
930 protocol[strlen (PROFILE_CFG_PROTOCOL)+strlen(file)-strlen(str)] = '\0';
931 p = m_config_get_profile (conf, protocol);
932 if (p)
934 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading protocol-related profile '%s'\n", protocol);
935 m_config_set_profile(conf,p);
939 #define PROFILE_CFG_EXTENSION "extension."
941 static void load_per_extension_config (m_config_t* conf, const char *const file)
943 char *str;
944 char extension[strlen (PROFILE_CFG_EXTENSION) + 8];
945 m_profile_t *p;
947 /* does filename actually have an extension ? */
948 str = strrchr (file, '.');
949 if (!str)
950 return;
952 sprintf (extension, PROFILE_CFG_EXTENSION);
953 strncat (extension, ++str, 7);
954 p = m_config_get_profile (conf, extension);
955 if (p)
957 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", extension);
958 m_config_set_profile(conf,p);
962 #define PROFILE_CFG_VO "vo."
963 #define PROFILE_CFG_AO "ao."
965 static void load_per_output_config (m_config_t* conf, char *cfg, char *out)
967 char profile[strlen (cfg) + strlen (out) + 1];
968 m_profile_t *p;
970 sprintf (profile, "%s%s", cfg, out);
971 p = m_config_get_profile (conf, profile);
972 if (p)
974 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", profile);
975 m_config_set_profile(conf,p);
980 * Tries to load a config file
981 * @return 0 if file was not found, 1 otherwise
983 static int try_load_config(m_config_t *conf, const char *file)
985 struct stat st;
986 if (stat(file, &st))
987 return 0;
988 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Loading config '%s'\n", file);
989 m_config_parse_config_file (conf, file);
990 return 1;
993 static void load_per_file_config (m_config_t* conf, const char *const file)
995 char *confpath;
996 char cfg[PATH_MAX];
997 const char *name;
999 if (strlen(file) > PATH_MAX - 14) {
1000 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Filename is too long, can not load file or directory specific config files\n");
1001 return;
1003 sprintf (cfg, "%s.conf", file);
1005 name = mp_basename(cfg);
1006 if (use_filedir_conf) {
1007 char dircfg[PATH_MAX];
1008 strcpy(dircfg, cfg);
1009 strcpy(dircfg + (name - cfg), "mplayer.conf");
1010 try_load_config(conf, dircfg);
1012 if (try_load_config(conf, cfg))
1013 return;
1016 if ((confpath = get_path (name)) != NULL)
1018 try_load_config(conf, confpath);
1020 free (confpath);
1024 /* When libmpdemux performs a blocking operation (network connection or
1025 * cache filling) if the operation fails we use this function to check
1026 * if it was interrupted by the user.
1027 * The function returns a new value for eof. */
1028 static int libmpdemux_was_interrupted(struct MPContext *mpctx, int stop_play)
1030 mp_cmd_t* cmd;
1031 if((cmd = mp_input_get_cmd(mpctx->input, 0, 0)) != NULL) {
1032 switch(cmd->id) {
1033 case MP_CMD_QUIT:
1034 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
1035 case MP_CMD_PLAY_TREE_STEP: {
1036 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_ENTRY : PT_PREV_ENTRY;
1037 mpctx->play_tree_step = (cmd->args[0].v.i == 0) ? 1 : cmd->args[0].v.i;
1038 } break;
1039 case MP_CMD_PLAY_TREE_UP_STEP: {
1040 stop_play = (cmd->args[0].v.i > 0) ? PT_UP_NEXT : PT_UP_PREV;
1041 } break;
1042 case MP_CMD_PLAY_ALT_SRC_STEP: {
1043 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_SRC : PT_PREV_SRC;
1044 } break;
1046 mp_cmd_free(cmd);
1048 return stop_play;
1051 static int playtree_add_playlist(struct MPContext *mpctx, play_tree_t* entry)
1053 play_tree_add_bpf(entry,mpctx->filename);
1056 if(!entry) {
1057 entry = mpctx->playtree_iter->tree;
1058 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1059 return PT_NEXT_ENTRY;
1061 if(mpctx->playtree_iter->tree == entry ) { // Loop with a single file
1062 if(play_tree_iter_up_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1063 return PT_NEXT_ENTRY;
1066 play_tree_remove(entry,1,1);
1067 return PT_NEXT_SRC;
1069 play_tree_insert_entry(mpctx->playtree_iter->tree,entry);
1070 play_tree_set_params_from(entry,mpctx->playtree_iter->tree);
1071 entry = mpctx->playtree_iter->tree;
1072 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1073 return PT_NEXT_ENTRY;
1075 play_tree_remove(entry,1,1);
1077 return PT_NEXT_SRC;
1080 void add_subtitles(struct MPContext *mpctx, char *filename, float fps, int noerr)
1082 struct MPOpts *opts = &mpctx->opts;
1083 sub_data *subd = NULL;
1084 struct ass_track *asst = NULL;
1085 bool is_native_ass = false;
1087 if (filename == NULL || mpctx->set_of_sub_size >= MAX_SUBTITLE_FILES)
1088 return;
1090 #ifdef CONFIG_ASS
1091 if (opts->ass_enabled) {
1092 #ifdef CONFIG_ICONV
1093 asst = mp_ass_read_stream(ass_library, filename, sub_cp);
1094 #else
1095 asst = mp_ass_read_stream(ass_library, filename, 0);
1096 #endif
1097 is_native_ass = asst;
1098 if (!asst) {
1099 subd = sub_read_file(filename, fps, &mpctx->opts);
1100 if (subd) {
1101 asst = mp_ass_read_subdata(ass_library, subd, fps);
1102 sub_free(subd);
1103 subd = NULL;
1106 } else
1107 #endif
1108 subd = sub_read_file(filename, fps, &mpctx->opts);
1111 if (!asst && !subd) {
1112 mp_tmsg(MSGT_CPLAYER, noerr ? MSGL_WARN : MSGL_ERR,
1113 "Cannot load subtitles: %s\n", filename_recode(filename));
1114 return;
1117 mpctx->set_of_ass_tracks[mpctx->set_of_sub_size] = asst;
1118 mpctx->set_of_subtitles[mpctx->set_of_sub_size] = subd;
1119 mpctx->track_was_native_ass[mpctx->set_of_sub_size] = is_native_ass;
1120 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_ID=%d\n", mpctx->set_of_sub_size);
1121 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_FILENAME=%s\n",
1122 filename_recode(filename));
1123 ++mpctx->set_of_sub_size;
1124 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "SUB: Added subtitle file (%d): %s\n", mpctx->set_of_sub_size,
1125 filename_recode(filename));
1128 void init_vo_spudec(struct MPContext *mpctx)
1130 spudec_free(vo_spudec);
1131 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
1132 vo_spudec = NULL;
1134 // we currently can't work without video stream
1135 if (!mpctx->sh_video)
1136 return;
1138 if (spudec_ifo) {
1139 unsigned int palette[16], width, height;
1140 current_module="spudec_init_vobsub";
1141 if (vobsub_parse_ifo(NULL,spudec_ifo, palette, &width, &height, 1, -1, NULL) >= 0)
1142 vo_spudec=spudec_new_scaled(palette, width, height, NULL, 0);
1145 #ifdef CONFIG_DVDREAD
1146 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVD) {
1147 current_module="spudec_init_dvdread";
1148 vo_spudec=spudec_new_scaled(((dvd_priv_t *)(mpctx->stream->priv))->cur_pgc->palette,
1149 mpctx->sh_video->disp_w, mpctx->sh_video->disp_h,
1150 NULL, 0);
1152 #endif
1154 #ifdef CONFIG_DVDNAV
1155 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVDNAV) {
1156 unsigned int *palette = mp_dvdnav_get_spu_clut(mpctx->stream);
1157 current_module="spudec_init_dvdnav";
1158 vo_spudec=spudec_new_scaled(palette, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, NULL, 0);
1160 #endif
1162 if (vo_spudec==NULL) {
1163 sh_sub_t *sh = mpctx->d_sub->sh;
1164 current_module="spudec_init_normal";
1165 vo_spudec=spudec_new_scaled(NULL, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, sh->extradata, sh->extradata_len);
1166 spudec_set_font_factor(vo_spudec,font_factor);
1169 if (vo_spudec!=NULL) {
1170 mpctx->initialized_flags|=INITIALIZED_SPUDEC;
1171 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
1176 * In Mac OS X the SDL-lib is built upon Cocoa. The easiest way to
1177 * make it all work is to use the builtin SDL-bootstrap code, which
1178 * will be done automatically by replacing our main() if we include SDL.h.
1180 #if defined(__APPLE__) && defined(CONFIG_SDL)
1181 #ifdef CONFIG_SDL_SDL_H
1182 #include <SDL/SDL.h>
1183 #else
1184 #include <SDL.h>
1185 #endif
1186 #endif
1189 * \brief append a formatted string
1190 * \param buf buffer to print into
1191 * \param pos position of terminating 0 in buf
1192 * \param len maximum number of characters in buf, not including terminating 0
1193 * \param format printf format string
1195 static void saddf(char *buf, unsigned *pos, int len, const char *format, ...)
1197 va_list va;
1198 va_start(va, format);
1199 *pos += vsnprintf(&buf[*pos], len - *pos, format, va);
1200 va_end(va);
1201 if (*pos >= len ) {
1202 buf[len] = 0;
1203 *pos = len;
1208 * \brief append time in the hh:mm:ss.f format
1209 * \param buf buffer to print into
1210 * \param pos position of terminating 0 in buf
1211 * \param len maximum number of characters in buf, not including terminating 0
1212 * \param time time value to convert/append
1214 static void sadd_hhmmssf(char *buf, unsigned *pos, int len, float time) {
1215 int64_t tenths = 10 * time;
1216 int f1 = tenths % 10;
1217 int ss = (tenths / 10) % 60;
1218 int mm = (tenths / 600) % 60;
1219 int hh = tenths / 36000;
1220 if (time <= 0) {
1221 saddf(buf, pos, len, "unknown");
1222 return;
1224 if (hh > 0)
1225 saddf(buf, pos, len, "%2d:", hh);
1226 if (hh > 0 || mm > 0)
1227 saddf(buf, pos, len, "%02d:", mm);
1228 saddf(buf, pos, len, "%02d.%1d", ss, f1);
1231 static void print_status(struct MPContext *mpctx, double a_pos, bool at_frame)
1233 struct MPOpts *opts = &mpctx->opts;
1234 sh_video_t * const sh_video = mpctx->sh_video;
1236 if (mpctx->sh_audio && a_pos == MP_NOPTS_VALUE)
1237 a_pos = playing_audio_pts(mpctx);
1238 if (mpctx->sh_audio && sh_video && at_frame) {
1239 mpctx->last_av_difference = a_pos - mpctx->video_pts - audio_delay;
1240 if (mpctx->time_frame > 0)
1241 mpctx->last_av_difference += mpctx->time_frame * opts->playback_speed;
1242 if (mpctx->last_av_difference > 0.5 && drop_frame_cnt > 50
1243 && !mpctx->drop_message_shown) {
1244 mp_tmsg(MSGT_AVSYNC,MSGL_WARN,SystemTooSlow);
1245 mpctx->drop_message_shown = true;
1248 if (opts->quiet)
1249 return;
1252 int width;
1253 char *line;
1254 unsigned pos = 0;
1255 get_screen_size();
1256 if (screen_width > 0)
1257 width = screen_width;
1258 else
1259 width = 80;
1260 #if defined(__MINGW32__) || defined(__CYGWIN__) || defined(__OS2__)
1261 /* Windows command line is broken (MinGW's rxvt works, but we
1262 * should not depend on that). */
1263 width--;
1264 #endif
1265 line = malloc(width + 1); // one additional char for the terminating null
1267 // Audio time
1268 if (mpctx->sh_audio) {
1269 saddf(line, &pos, width, "A:%6.1f ", a_pos);
1270 if (!sh_video) {
1271 float len = get_time_length(mpctx);
1272 saddf(line, &pos, width, "(");
1273 sadd_hhmmssf(line, &pos, width, a_pos);
1274 saddf(line, &pos, width, ") of %.1f (", len);
1275 sadd_hhmmssf(line, &pos, width, len);
1276 saddf(line, &pos, width, ") ");
1280 // Video time
1281 if (sh_video)
1282 saddf(line, &pos, width, "V:%6.1f ", mpctx->video_pts);
1284 // A-V sync
1285 if (mpctx->sh_audio && sh_video)
1286 saddf(line, &pos, width, "A-V:%7.3f ct:%7.3f ",
1287 mpctx->last_av_difference, mpctx->total_avsync_change);
1289 // Video stats
1290 if (sh_video)
1291 saddf(line, &pos, width, "%3d/%3d ",
1292 (int)sh_video->num_frames,
1293 (int)sh_video->num_frames_decoded);
1295 // CPU usage
1296 if (sh_video) {
1297 if (sh_video->timer > 0.5)
1298 saddf(line, &pos, width, "%2d%% %2d%% %4.1f%% ",
1299 (int)(100.0*video_time_usage*opts->playback_speed/(double)sh_video->timer),
1300 (int)(100.0*vout_time_usage*opts->playback_speed/(double)sh_video->timer),
1301 (100.0*audio_time_usage*opts->playback_speed/(double)sh_video->timer));
1302 else
1303 saddf(line, &pos, width, "??%% ??%% ??,?%% ");
1304 } else if (mpctx->sh_audio) {
1305 if (mpctx->delay > 0.5)
1306 saddf(line, &pos, width, "%4.1f%% ",
1307 100.0*audio_time_usage/(double)mpctx->delay);
1308 else
1309 saddf(line, &pos, width, "??,?%% ");
1312 // VO stats
1313 if (sh_video)
1314 saddf(line, &pos, width, "%d %d ", drop_frame_cnt, output_quality);
1316 #ifdef CONFIG_STREAM_CACHE
1317 // cache stats
1318 if (stream_cache_size > 0)
1319 saddf(line, &pos, width, "%d%% ", cache_fill_status(mpctx->stream));
1320 #endif
1322 // other
1323 if (opts->playback_speed != 1)
1324 saddf(line, &pos, width, "%4.2fx ", opts->playback_speed);
1326 // end
1327 if (erase_to_end_of_line) {
1328 line[pos] = 0;
1329 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s%s\r", line, erase_to_end_of_line);
1330 } else {
1331 memset(&line[pos], ' ', width - pos);
1332 line[width] = 0;
1333 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s\r", line);
1335 free(line);
1339 * \brief build a chain of audio filters that converts the input format
1340 * to the ao's format, taking into account the current playback_speed.
1341 * sh_audio describes the requested input format of the chain.
1342 * ao describes the requested output format of the chain.
1344 static int build_afilter_chain(struct MPContext *mpctx)
1346 struct sh_audio *sh_audio = mpctx->sh_audio;
1347 struct ao *ao = mpctx->ao;
1348 struct MPOpts *opts = &mpctx->opts;
1349 int new_srate;
1350 int result;
1351 if (!sh_audio)
1353 mpctx->mixer.afilter = NULL;
1354 return 0;
1356 if(af_control_any_rev(sh_audio->afilter,
1357 AF_CONTROL_PLAYBACK_SPEED | AF_CONTROL_SET,
1358 &opts->playback_speed)) {
1359 new_srate = sh_audio->samplerate;
1360 } else {
1361 new_srate = sh_audio->samplerate * opts->playback_speed;
1362 if (new_srate != ao->samplerate) {
1363 // limits are taken from libaf/af_resample.c
1364 if (new_srate < 8000)
1365 new_srate = 8000;
1366 if (new_srate > 192000)
1367 new_srate = 192000;
1368 opts->playback_speed = (float)new_srate / (float)sh_audio->samplerate;
1371 result = init_audio_filters(sh_audio, new_srate,
1372 &ao->samplerate, &ao->channels, &ao->format);
1373 mpctx->mixer.afilter = sh_audio->afilter;
1374 return result;
1378 typedef struct mp_osd_msg mp_osd_msg_t;
1379 struct mp_osd_msg {
1380 /// Previous message on the stack.
1381 mp_osd_msg_t* prev;
1382 /// Message text.
1383 char msg[128];
1384 int id,level,started;
1385 /// Display duration in ms.
1386 unsigned time;
1389 /// OSD message stack.
1390 static mp_osd_msg_t* osd_msg_stack = NULL;
1393 * \brief Add a message on the OSD message stack
1395 * If a message with the same id is already present in the stack
1396 * it is pulled on top of the stack, otherwise a new message is created.
1399 static void set_osd_msg_va(int id, int level, int time, const char *fmt,
1400 va_list ap)
1402 mp_osd_msg_t *msg,*last=NULL;
1403 int r;
1405 // look if the id is already in the stack
1406 for(msg = osd_msg_stack ; msg && msg->id != id ;
1407 last = msg, msg = msg->prev);
1408 // not found: alloc it
1409 if(!msg) {
1410 msg = calloc(1,sizeof(mp_osd_msg_t));
1411 msg->prev = osd_msg_stack;
1412 osd_msg_stack = msg;
1413 } else if(last) { // found, but it's not on top of the stack
1414 last->prev = msg->prev;
1415 msg->prev = osd_msg_stack;
1416 osd_msg_stack = msg;
1418 // write the msg
1419 r = vsnprintf(msg->msg, 128, fmt, ap);
1420 if(r >= 128) msg->msg[127] = 0;
1421 // set id and time
1422 msg->id = id;
1423 msg->level = level;
1424 msg->time = time;
1428 void set_osd_msg(int id, int level, int time, const char *fmt, ...)
1430 va_list ap;
1431 va_start(ap, fmt);
1432 set_osd_msg_va(id, level, time, fmt, ap);
1433 va_end(ap);
1436 void set_osd_tmsg(int id, int level, int time, const char *fmt, ...)
1438 va_list ap;
1439 va_start(ap, fmt);
1440 set_osd_msg_va(id, level, time, mp_gtext(fmt), ap);
1441 va_end(ap);
1446 * \brief Remove a message from the OSD stack
1448 * This function can be used to get rid of a message right away.
1452 void rm_osd_msg(int id) {
1453 mp_osd_msg_t *msg,*last=NULL;
1455 // Search for the msg
1456 for(msg = osd_msg_stack ; msg && msg->id != id ;
1457 last = msg, msg = msg->prev);
1458 if(!msg) return;
1460 // Detach it from the stack and free it
1461 if(last)
1462 last->prev = msg->prev;
1463 else
1464 osd_msg_stack = msg->prev;
1465 free(msg);
1469 * \brief Remove all messages from the OSD stack
1473 static void clear_osd_msgs(void) {
1474 mp_osd_msg_t* msg = osd_msg_stack, *prev = NULL;
1475 while(msg) {
1476 prev = msg->prev;
1477 free(msg);
1478 msg = prev;
1480 osd_msg_stack = NULL;
1484 * \brief Get the current message from the OSD stack.
1486 * This function decrements the message timer and destroys the old ones.
1487 * The message that should be displayed is returned (if any).
1491 static mp_osd_msg_t* get_osd_msg(struct MPContext *mpctx)
1493 struct MPOpts *opts = &mpctx->opts;
1494 mp_osd_msg_t *msg,*prev,*last = NULL;
1495 static unsigned last_update = 0;
1496 unsigned now = GetTimerMS();
1497 unsigned diff;
1498 char hidden_dec_done = 0;
1500 if (mpctx->osd_visible) {
1501 // 36000000 means max timed visibility is 1 hour into the future, if
1502 // the difference is greater assume it's wrapped around from below 0
1503 if (mpctx->osd_visible - now > 36000000) {
1504 mpctx->osd_visible = 0;
1505 vo_osd_progbar_type = -1; // disable
1506 vo_osd_changed(OSDTYPE_PROGBAR);
1507 mpctx->osd_function = mpctx->paused ? OSD_PAUSE : OSD_PLAY;
1510 if (mpctx->osd_show_percentage_until - now > 36000000)
1511 mpctx->osd_show_percentage_until = 0;
1513 if(!last_update) last_update = now;
1514 diff = now >= last_update ? now - last_update : 0;
1516 last_update = now;
1518 // Look for the first message in the stack with high enough level.
1519 for(msg = osd_msg_stack ; msg ; last = msg, msg = prev) {
1520 prev = msg->prev;
1521 if (msg->level > opts->osd_level && hidden_dec_done)
1522 continue;
1523 // The message has a high enough level or it is the first hidden one
1524 // in both cases we decrement the timer or kill it.
1525 if(!msg->started || msg->time > diff) {
1526 if(msg->started) msg->time -= diff;
1527 else msg->started = 1;
1528 // display it
1529 if (msg->level <= opts->osd_level)
1530 return msg;
1531 hidden_dec_done = 1;
1532 continue;
1534 // kill the message
1535 free(msg);
1536 if(last) {
1537 last->prev = prev;
1538 msg = last;
1539 } else {
1540 osd_msg_stack = prev;
1541 msg = NULL;
1544 // Nothing found
1545 return NULL;
1549 * \brief Display the OSD bar.
1551 * Display the OSD bar or fall back on a simple message.
1555 void set_osd_bar(struct MPContext *mpctx, int type,const char* name,double min,double max,double val) {
1556 struct MPOpts *opts = &mpctx->opts;
1557 if (opts->osd_level < 1)
1558 return;
1560 if(mpctx->sh_video) {
1561 mpctx->osd_visible = (GetTimerMS() + 1000) | 1;
1562 vo_osd_progbar_type = type;
1563 vo_osd_progbar_value = 256*(val-min)/(max-min);
1564 vo_osd_changed(OSDTYPE_PROGBAR);
1565 return;
1568 set_osd_msg(OSD_MSG_BAR, 1, opts->osd_duration, "%s: %d %%",
1569 name, ROUND(100*(val-min)/(max-min)));
1573 * \brief Display text subtitles on the OSD
1575 void set_osd_subtitle(struct MPContext *mpctx, subtitle *subs)
1577 int i;
1578 vo_sub = subs;
1579 vo_osd_changed(OSDTYPE_SUBTITLE);
1580 if (!mpctx->sh_video) {
1581 // reverse order, since newest set_osd_msg is displayed first
1582 for (i = SUB_MAX_TEXT - 1; i >= 0; i--) {
1583 if (!subs || i >= subs->lines || !subs->text[i])
1584 rm_osd_msg(OSD_MSG_SUB_BASE + i);
1585 else {
1586 // HACK: currently display time for each sub line except the last is set to 2 seconds.
1587 int display_time = i == subs->lines - 1 ? 180000 : 2000;
1588 set_osd_msg(OSD_MSG_SUB_BASE + i, 1, display_time, "%s", subs->text[i]);
1595 * \brief Update the OSD message line.
1597 * This function displays the current message on the vo OSD or on the term.
1598 * If the stack is empty and the OSD level is high enough the timer
1599 * is displayed (only on the vo OSD).
1603 static void update_osd_msg(struct MPContext *mpctx)
1605 struct MPOpts *opts = &mpctx->opts;
1606 mp_osd_msg_t *msg;
1607 struct osd_state *osd = mpctx->osd;
1608 char osd_text_timer[128];
1610 if (mpctx->add_osd_seek_info) {
1611 double percentage = get_percent_pos(mpctx);
1612 set_osd_bar(mpctx, 0, "Position", 0, 100, percentage);
1613 if (mpctx->sh_video)
1614 mpctx->osd_show_percentage_until = (GetTimerMS() + 1000) | 1;
1615 mpctx->add_osd_seek_info = false;
1618 // Look if we have a msg
1619 if((msg = get_osd_msg(mpctx))) {
1620 if (strcmp(osd->osd_text, msg->msg)) {
1621 strncpy(osd->osd_text, msg->msg, 127);
1622 if(mpctx->sh_video) vo_osd_changed(OSDTYPE_OSD); else
1623 if(opts->term_osd)
1624 mp_msg(MSGT_CPLAYER,MSGL_STATUS, "%s%s\n", opts->term_osd_esc,
1625 msg->msg);
1627 return;
1630 if(mpctx->sh_video) {
1631 // fallback on the timer
1632 if (opts->osd_level >= 2) {
1633 int len = get_time_length(mpctx);
1634 int percentage = -1;
1635 char percentage_text[10];
1636 char fractions_text[4];
1637 double fpts = get_current_time(mpctx);
1638 int pts = fpts;
1640 if (mpctx->osd_show_percentage_until)
1641 percentage = get_percent_pos(mpctx);
1643 if (percentage >= 0)
1644 snprintf(percentage_text, 9, " (%d%%)", percentage);
1645 else
1646 percentage_text[0] = 0;
1648 if (opts->osd_fractions == 1) {
1649 //print fractions as sub-second timestamp
1650 snprintf(fractions_text, sizeof(fractions_text), ".%02d",
1651 (int)((fpts - pts) * 100));
1652 } else if (opts->osd_fractions == 2) {
1653 /* Print fractions by estimating the frame count within the
1654 * second.
1656 * Rounding or cutting off numbers after the decimal point
1657 * causes problems because of float's precision and movies
1658 * whose first frame is not exactly at timestamp 0. Therefore,
1659 * we add 0.2 and cut off at the decimal point, which proved
1660 * to be good heuristic.
1662 double fps = mpctx->sh_video->fps;
1663 if (fps <= 1 || fps > 99)
1664 strcpy(fractions_text, ".??");
1665 else
1666 snprintf(fractions_text, sizeof(fractions_text), ".%02d",
1667 (int) ( (fpts - pts) * fps + 0.2 ) );
1668 } else {
1669 //do not print fractions
1670 fractions_text[0] = 0;
1673 if (opts->osd_level == 3)
1674 snprintf(osd_text_timer, 63,
1675 "%c %02d:%02d:%02d%s / %02d:%02d:%02d%s",
1676 mpctx->osd_function,pts/3600,(pts/60)%60,pts%60,
1677 fractions_text, len/3600, (len/60)%60, len%60,
1678 percentage_text);
1679 else
1680 snprintf(osd_text_timer, 63, "%c %02d:%02d:%02d%s%s",
1681 mpctx->osd_function,pts/3600,(pts/60)%60,
1682 pts%60, fractions_text, percentage_text);
1683 } else
1684 osd_text_timer[0]=0;
1686 if (strcmp(osd->osd_text, osd_text_timer)) {
1687 strncpy(osd->osd_text, osd_text_timer, 63);
1688 vo_osd_changed(OSDTYPE_OSD);
1690 return;
1693 // Clear the term osd line
1694 if (opts->term_osd && osd->osd_text[0]) {
1695 osd->osd_text[0] = 0;
1696 printf("%s\n", opts->term_osd_esc);
1700 ///@}
1701 // OSDMsgStack
1704 void reinit_audio_chain(struct MPContext *mpctx)
1706 struct MPOpts *opts = &mpctx->opts;
1707 struct ao *ao;
1708 if (!mpctx->sh_audio)
1709 return;
1710 if (!(mpctx->initialized_flags & INITIALIZED_ACODEC)) {
1711 current_module="init_audio_codec";
1712 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1713 if(!init_best_audio_codec(mpctx->sh_audio,audio_codec_list,audio_fm_list)){
1714 goto init_error;
1716 mpctx->initialized_flags|=INITIALIZED_ACODEC;
1717 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1721 current_module="af_preinit";
1722 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1723 mpctx->initialized_flags |= INITIALIZED_AO;
1724 mpctx->ao = ao_create();
1725 mpctx->ao->samplerate = force_srate;
1726 mpctx->ao->format = opts->audio_output_format;
1728 ao = mpctx->ao;
1730 // first init to detect best values
1731 if(!init_audio_filters(mpctx->sh_audio, // preliminary init
1732 // input:
1733 mpctx->sh_audio->samplerate,
1734 // output:
1735 &ao->samplerate, &ao->channels, &ao->format)) {
1736 mp_tmsg(MSGT_CPLAYER,MSGL_ERR, "Error at audio filter chain "
1737 "pre-init!\n");
1738 exit_player(mpctx, EXIT_ERROR);
1740 if (!ao->initialized) {
1741 current_module="ao2_init";
1742 ao->buffersize = opts->ao_buffersize;
1743 ao_init(ao, opts->audio_driver_list);
1744 if (!ao->initialized) {
1745 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Could not open/initialize audio device -> no sound.\n");
1746 goto init_error;
1748 mp_msg(MSGT_CPLAYER,MSGL_INFO,"AO: [%s] %dHz %dch %s (%d bytes per sample)\n",
1749 ao->driver->info->short_name,
1750 ao->samplerate, ao->channels,
1751 af_fmt2str_short(ao->format),
1752 af_fmt2bits(ao->format)/8 );
1753 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Description: %s\nAO: Author: %s\n",
1754 ao->driver->info->name, ao->driver->info->author);
1755 if (strlen(ao->driver->info->comment) > 0)
1756 mp_msg(MSGT_CPLAYER, MSGL_V, "AO: Comment: %s\n",
1757 ao->driver->info->comment);
1760 // init audio filters:
1761 current_module="af_init";
1762 if (!build_afilter_chain(mpctx)) {
1763 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Couldn't find matching filter/ao format!\n");
1764 goto init_error;
1766 mpctx->mixer.ao = ao;
1767 mpctx->mixer.volstep = volstep;
1768 mpctx->syncing_audio = true;
1769 return;
1771 init_error:
1772 uninit_player(mpctx, INITIALIZED_ACODEC|INITIALIZED_AO); // close codec and possibly AO
1773 mpctx->sh_audio=mpctx->d_audio->sh=NULL; // -> nosound
1774 mpctx->d_audio->id = -2;
1778 ///@}
1779 // Command2Property
1782 // Return pts value corresponding to the end point of audio written to the
1783 // ao so far.
1784 static double written_audio_pts(struct MPContext *mpctx)
1786 sh_audio_t *sh_audio = mpctx->sh_audio;
1787 demux_stream_t *d_audio = mpctx->d_audio;
1788 double buffered_output;
1789 // first calculate the end pts of audio that has been output by decoder
1790 double a_pts = sh_audio->pts;
1791 if (a_pts != MP_NOPTS_VALUE)
1792 // Good, decoder supports new way of calculating audio pts.
1793 // sh_audio->pts is the timestamp of the latest input packet with
1794 // known pts that the decoder has decoded. sh_audio->pts_bytes is
1795 // the amount of bytes the decoder has written after that timestamp.
1796 a_pts += sh_audio->pts_bytes / (double) sh_audio->o_bps;
1797 else {
1798 // Decoder doesn't support new way of calculating pts (or we're
1799 // being called before it has decoded anything with known timestamp).
1800 // Use the old method of audio pts calculation: take the timestamp
1801 // of last packet with known pts the decoder has read data from,
1802 // and add amount of bytes read after the beginning of that packet
1803 // divided by input bps. This will be inaccurate if the input/output
1804 // ratio is not constant for every audio packet or if it is constant
1805 // but not accurately known in sh_audio->i_bps.
1807 a_pts = d_audio->pts;
1808 // ds_tell_pts returns bytes read after last timestamp from
1809 // demuxing layer, decoder might use sh_audio->a_in_buffer for bytes
1810 // it has read but not decoded
1811 if (sh_audio->i_bps)
1812 a_pts += (ds_tell_pts(d_audio) - sh_audio->a_in_buffer_len) /
1813 (double)sh_audio->i_bps;
1815 // Now a_pts hopefully holds the pts for end of audio from decoder.
1816 // Substract data in buffers between decoder and audio out.
1818 // Decoded but not filtered
1819 a_pts -= sh_audio->a_buffer_len / (double)sh_audio->o_bps;
1821 // Data buffered in audio filters, measured in bytes of "missing" output
1822 buffered_output = af_calc_delay(sh_audio->afilter);
1824 // Data that was ready for ao but was buffered because ao didn't fully
1825 // accept everything to internal buffers yet
1826 buffered_output += sh_audio->a_out_buffer_len;
1828 // Filters divide audio length by playback_speed, so multiply by it
1829 // to get the length in original units without speedup or slowdown
1830 a_pts -= buffered_output * mpctx->opts.playback_speed / mpctx->ao->bps;
1832 return a_pts + mpctx->video_offset;
1835 // Return pts value corresponding to currently playing audio.
1836 double playing_audio_pts(struct MPContext *mpctx)
1838 return written_audio_pts(mpctx) - mpctx->opts.playback_speed *
1839 ao_get_delay(mpctx->ao);
1842 static bool is_av_sub(int type)
1844 return type == 'b' || type == 'p' || type == 'x';
1847 void update_subtitles(struct MPContext *mpctx, double refpts,
1848 double sub_offset, bool reset)
1850 struct MPOpts *opts = &mpctx->opts;
1851 struct sh_video *sh_video = mpctx->sh_video;
1852 struct demux_stream *d_sub = mpctx->d_sub;
1853 double curpts = refpts + sub_delay;
1854 unsigned char *packet=NULL;
1855 int len;
1856 struct sh_sub *sh_sub = d_sub->sh;
1857 int type = sh_sub ? sh_sub->type : 'v';
1858 static subtitle subs;
1859 if (reset) {
1860 if (sh_sub)
1861 sub_reset(sh_sub, mpctx->osd);
1862 sub_clear_text(&subs, MP_NOPTS_VALUE);
1863 if (vo_sub)
1864 set_osd_subtitle(mpctx, NULL);
1865 if (vo_spudec) {
1866 spudec_reset(vo_spudec);
1867 vo_osd_changed(OSDTYPE_SPU);
1869 #ifdef CONFIG_FFMPEG
1870 if (is_av_sub(type))
1871 reset_avsub(sh_sub);
1872 #endif
1873 return;
1875 // find sub
1876 if (mpctx->subdata) {
1877 if (sub_fps==0) sub_fps = sh_video ? sh_video->fps : 25;
1878 current_module = "find_sub";
1879 find_sub(mpctx, mpctx->subdata, curpts *
1880 (mpctx->subdata->sub_uses_time ? 100. : sub_fps));
1881 if (vo_sub)
1882 mpctx->vo_sub_last = vo_sub;
1885 // DVD sub:
1886 if (vobsub_id >= 0 || type == 'v') {
1887 int timestamp;
1888 current_module = "spudec";
1889 /* Get a sub packet from the DVD or a vobsub */
1890 while(1) {
1891 // Vobsub
1892 len = 0;
1893 if (vo_vobsub) {
1894 if (curpts >= 0) {
1895 len = vobsub_get_packet(vo_vobsub, curpts,
1896 (void**)&packet, &timestamp);
1897 if (len > 0) {
1898 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);
1901 } else {
1902 // DVD sub
1903 len = ds_get_packet_sub(d_sub, (unsigned char**)&packet);
1904 if (len > 0) {
1905 // XXX This is wrong, sh_video->pts can be arbitrarily
1906 // much behind demuxing position. Unfortunately using
1907 // d_video->pts which would have been the simplest
1908 // improvement doesn't work because mpeg specific hacks
1909 // in video.c set d_video->pts to 0.
1910 float x = d_sub->pts - refpts;
1911 if (x > -20 && x < 20) // prevent missing subs on pts reset
1912 timestamp = 90000*d_sub->pts;
1913 else timestamp = 90000*curpts;
1914 mp_dbg(MSGT_CPLAYER, MSGL_V, "\rDVD sub: len=%d "
1915 "v_pts=%5.3f s_pts=%5.3f ts=%d \n", len,
1916 refpts, d_sub->pts, timestamp);
1919 if (len<=0 || !packet) break;
1920 // create it only here, since with some broken demuxers we might
1921 // type = v but no DVD sub and we currently do not change the
1922 // "original frame size" ever after init, leading to wrong-sized
1923 // PGS subtitles.
1924 if (!vo_spudec)
1925 vo_spudec = spudec_new(NULL);
1926 if (vo_vobsub || timestamp >= 0)
1927 spudec_assemble(vo_spudec, packet, len, timestamp);
1929 } else if (is_text_sub(type) || is_av_sub(type) || type == 'd') {
1930 if (type == 'd' && !d_sub->demuxer->teletext) {
1931 tt_stream_props tsp = {0};
1932 void *ptr = &tsp;
1933 if (teletext_control(NULL, TV_VBI_CONTROL_START, &ptr) == VBI_CONTROL_TRUE)
1934 d_sub->demuxer->teletext = ptr;
1936 if (d_sub->non_interleaved)
1937 ds_get_next_pts(d_sub);
1939 while (d_sub->first) {
1940 double subpts = ds_get_next_pts(d_sub) + sub_offset;
1941 if (subpts > curpts) {
1942 // Libass handled subs can be fed to it in advance
1943 if (!opts->ass_enabled || !is_text_sub(type))
1944 break;
1945 // Try to avoid demuxing whole file at once
1946 if (d_sub->non_interleaved && subpts > curpts + 1)
1947 break;
1949 double duration = d_sub->first->duration;
1950 len = ds_get_packet_sub(d_sub, &packet);
1951 if (is_av_sub(type)) {
1952 #ifdef CONFIG_FFMPEG
1953 int ret = decode_avsub(sh_sub, packet, len, subpts, duration);
1954 if (ret < 0)
1955 mp_msg(MSGT_SPUDEC, MSGL_WARN, "lavc failed decoding "
1956 "subtitle\n");
1957 #endif
1958 continue;
1960 if (type == 'm') {
1961 if (len < 2) continue;
1962 len = FFMIN(len - 2, AV_RB16(packet));
1963 packet += 2;
1965 if (type == 'd') {
1966 if (d_sub->demuxer->teletext) {
1967 uint8_t *p = packet;
1968 p++;
1969 len--;
1970 while (len >= 46) {
1971 int sublen = p[1];
1972 if (p[0] == 2 || p[0] == 3)
1973 teletext_control(d_sub->demuxer->teletext,
1974 TV_VBI_CONTROL_DECODE_DVB, p + 2);
1975 p += sublen + 2;
1976 len -= sublen + 2;
1979 continue;
1981 if (sh_sub && sh_sub->active) {
1982 sub_decode(sh_sub, mpctx->osd, packet, len, subpts, duration);
1983 continue;
1985 if (subpts != MP_NOPTS_VALUE) {
1986 if (duration < 0)
1987 sub_clear_text(&subs, MP_NOPTS_VALUE);
1988 if (type == 'a') { // ssa/ass subs without libass => convert to plaintext
1989 int i;
1990 unsigned char* p = packet;
1991 for (i=0; i < 8 && *p != '\0'; p++)
1992 if (*p == ',')
1993 i++;
1994 if (*p == '\0') /* Broken line? */
1995 continue;
1996 len -= p - packet;
1997 packet = p;
1999 double endpts = MP_NOPTS_VALUE;
2000 if (subpts != MP_NOPTS_VALUE && duration >= 0)
2001 endpts = subpts + duration;
2002 sub_add_text(&subs, packet, len, endpts);
2003 set_osd_subtitle(mpctx, &subs);
2005 if (d_sub->non_interleaved)
2006 ds_get_next_pts(d_sub);
2008 if (!opts->ass_enabled)
2009 if (sub_clear_text(&subs, curpts))
2010 set_osd_subtitle(mpctx, &subs);
2012 if (vo_spudec) {
2013 spudec_heartbeat(vo_spudec, 90000*curpts);
2014 if (spudec_changed(vo_spudec))
2015 vo_osd_changed(OSDTYPE_SPU);
2018 current_module=NULL;
2021 static void update_teletext(sh_video_t *sh_video, demuxer_t *demuxer, int reset)
2023 int page_changed;
2025 if (!demuxer->teletext)
2026 return;
2028 //Also forcing page update when such ioctl is not supported or call error occured
2029 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_IS_CHANGED,&page_changed)!=VBI_CONTROL_TRUE)
2030 page_changed=1;
2032 if(!page_changed)
2033 return;
2035 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_GET_VBIPAGE,&vo_osd_teletext_page)!=VBI_CONTROL_TRUE)
2036 vo_osd_teletext_page=NULL;
2037 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_GET_HALF_PAGE,&vo_osd_teletext_half)!=VBI_CONTROL_TRUE)
2038 vo_osd_teletext_half=0;
2039 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_GET_MODE,&vo_osd_teletext_mode)!=VBI_CONTROL_TRUE)
2040 vo_osd_teletext_mode=0;
2041 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_GET_FORMAT,&vo_osd_teletext_format)!=VBI_CONTROL_TRUE)
2042 vo_osd_teletext_format=0;
2043 vo_osd_changed(OSDTYPE_TELETEXT);
2045 teletext_control(demuxer->teletext,TV_VBI_CONTROL_MARK_UNCHANGED,NULL);
2048 static int check_framedrop(struct MPContext *mpctx, double frame_time) {
2049 struct MPOpts *opts = &mpctx->opts;
2050 // check for frame-drop:
2051 current_module = "check_framedrop";
2052 if (mpctx->sh_audio && !mpctx->ao->untimed && !mpctx->d_audio->eof) {
2053 static int dropped_frames;
2054 float delay = opts->playback_speed * ao_get_delay(mpctx->ao);
2055 float d = delay-mpctx->delay;
2056 ++total_frame_cnt;
2057 // we should avoid dropping too many frames in sequence unless we
2058 // are too late. and we allow 100ms A-V delay here:
2059 if (d < -dropped_frames*frame_time-0.100 && !mpctx->paused
2060 && !mpctx->restart_playback) {
2061 ++drop_frame_cnt;
2062 ++dropped_frames;
2063 return frame_dropping;
2064 } else
2065 dropped_frames = 0;
2067 return 0;
2071 #ifdef HAVE_RTC
2072 int rtc_fd = -1;
2073 #endif
2075 static float timing_sleep(struct MPContext *mpctx, float time_frame)
2077 #ifdef HAVE_RTC
2078 if (rtc_fd >= 0){
2079 // -------- RTC -----------
2080 current_module="sleep_rtc";
2081 while (time_frame > 0.000) {
2082 unsigned long rtc_ts;
2083 if (read(rtc_fd, &rtc_ts, sizeof(rtc_ts)) <= 0)
2084 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC read error: %s\n", strerror(errno));
2085 time_frame -= get_relative_time(mpctx);
2087 } else
2088 #endif
2090 // assume kernel HZ=100 for softsleep, works with larger HZ but with
2091 // unnecessarily high CPU usage
2092 struct MPOpts *opts = &mpctx->opts;
2093 float margin = opts->softsleep ? 0.011 : 0;
2094 current_module = "sleep_timer";
2095 while (time_frame > margin) {
2096 usec_sleep(1000000 * (time_frame - margin));
2097 time_frame -= get_relative_time(mpctx);
2099 if (opts->softsleep){
2100 current_module = "sleep_soft";
2101 if (time_frame < 0)
2102 mp_tmsg(MSGT_AVSYNC, MSGL_WARN, "Warning! Softsleep underflow!\n");
2103 while (time_frame > 0)
2104 time_frame -= get_relative_time(mpctx); // burn the CPU
2107 return time_frame;
2110 static int select_subtitle(MPContext *mpctx)
2112 struct MPOpts *opts = &mpctx->opts;
2113 // find the best sub to use
2114 int id;
2115 int found = 0;
2116 mpctx->global_sub_pos = -1; // no subs by default
2117 if (vobsub_id >= 0) {
2118 // if user asks for a vobsub id, use that first.
2119 id = vobsub_id;
2120 found = mp_property_do("sub_vob", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
2123 if (!found && opts->sub_id >= 0) {
2124 // if user asks for a dvd sub id, use that next.
2125 id = opts->sub_id;
2126 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
2129 if (!found) {
2130 // if there are text subs to use, use those. (autosubs come last here)
2131 id = 0;
2132 found = mp_property_do("sub_file", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
2135 if (!found && opts->sub_id == -1) {
2136 // finally select subs by language and container hints
2137 if (opts->sub_id == -1)
2138 opts->sub_id =
2139 demuxer_sub_track_by_lang_and_default(mpctx->d_sub->demuxer,
2140 opts->sub_lang);
2141 if (opts->sub_id >= 0) {
2142 id = opts->sub_id;
2143 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
2146 return found;
2149 #ifdef CONFIG_DVDNAV
2150 #ifndef FF_B_TYPE
2151 #define FF_B_TYPE 3
2152 #endif
2153 /// store decoded video image
2154 static mp_image_t * mp_dvdnav_copy_mpi(mp_image_t *to_mpi,
2155 mp_image_t *from_mpi) {
2156 mp_image_t *mpi;
2158 /// Do not store B-frames
2159 if (from_mpi->pict_type == FF_B_TYPE)
2160 return to_mpi;
2162 if (to_mpi &&
2163 to_mpi->w == from_mpi->w &&
2164 to_mpi->h == from_mpi->h &&
2165 to_mpi->imgfmt == from_mpi->imgfmt)
2166 mpi = to_mpi;
2167 else {
2168 if (to_mpi)
2169 free_mp_image(to_mpi);
2170 if (from_mpi->w == 0 || from_mpi->h == 0)
2171 return NULL;
2172 mpi = alloc_mpi(from_mpi->w,from_mpi->h,from_mpi->imgfmt);
2175 copy_mpi(mpi,from_mpi);
2176 return mpi;
2179 static void mp_dvdnav_reset_stream (MPContext *ctx) {
2180 struct MPOpts *opts = &ctx->opts;
2181 if (ctx->sh_video) {
2182 /// clear video pts
2183 ctx->d_video->pts = 0.0f;
2184 ctx->sh_video->pts = 0.0f;
2185 ctx->sh_video->i_pts = 0.0f;
2186 ctx->sh_video->last_pts = 0.0f;
2187 ctx->sh_video->num_buffered_pts = 0;
2188 ctx->sh_video->num_frames = 0;
2189 ctx->sh_video->num_frames_decoded = 0;
2190 ctx->sh_video->timer = 0.0f;
2191 ctx->sh_video->stream_delay = 0.0f;
2192 ctx->sh_video->timer = 0;
2193 ctx->demuxer->stream_pts = MP_NOPTS_VALUE;
2196 if (ctx->sh_audio) {
2197 /// free audio packets and reset
2198 ds_free_packs(ctx->d_audio);
2199 audio_delay -= ctx->sh_audio->stream_delay;
2200 ctx->delay =- audio_delay;
2201 ao_reset(ctx->ao);
2202 resync_audio_stream(ctx->sh_audio);
2205 audio_delay = 0.0f;
2206 ctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(ctx->stream);
2207 if (opts->sub_lang && opts->sub_id == dvdsub_lang_id) {
2208 dvdsub_lang_id = mp_dvdnav_sid_from_lang(ctx->stream, opts->sub_lang);
2209 if (dvdsub_lang_id != opts->sub_id) {
2210 opts->sub_id = dvdsub_lang_id;
2211 select_subtitle(ctx);
2215 /// clear all EOF related flags
2216 ctx->d_video->eof = ctx->d_audio->eof = ctx->stream->eof = 0;
2219 /// Restore last decoded DVDNAV (still frame)
2220 static mp_image_t *mp_dvdnav_restore_smpi(struct MPContext *mpctx,
2221 int *in_size,
2222 unsigned char **start,
2223 mp_image_t *decoded_frame)
2225 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2226 return decoded_frame;
2228 /// a change occured in dvdnav stream
2229 if (mp_dvdnav_cell_has_changed(mpctx->stream,0)) {
2230 mp_dvdnav_read_wait(mpctx->stream, 1, 1);
2231 mp_dvdnav_context_free(mpctx);
2232 mp_dvdnav_reset_stream(mpctx);
2233 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
2234 mp_dvdnav_cell_has_changed(mpctx->stream,1);
2237 if (*in_size < 0) {
2238 float len;
2240 /// Display still frame, if any
2241 if (mpctx->nav_smpi && !mpctx->nav_buffer)
2242 decoded_frame = mpctx->nav_smpi;
2244 /// increment video frame : continue playing after still frame
2245 len = get_time_length(mpctx);
2246 if (mpctx->sh_video->pts >= len &&
2247 mpctx->sh_video->pts > 0.0 && len > 0.0) {
2248 mp_dvdnav_skip_still(mpctx->stream);
2249 mp_dvdnav_skip_wait(mpctx->stream);
2251 mpctx->sh_video->pts += 1 / mpctx->sh_video->fps;
2253 if (mpctx->nav_buffer) {
2254 *start = mpctx->nav_start;
2255 *in_size = mpctx->nav_in_size;
2256 if (mpctx->nav_start)
2257 memcpy(*start,mpctx->nav_buffer,mpctx->nav_in_size);
2261 return decoded_frame;
2264 /// Save last decoded DVDNAV (still frame)
2265 static void mp_dvdnav_save_smpi(struct MPContext *mpctx, int in_size,
2266 unsigned char *start,
2267 mp_image_t *decoded_frame)
2269 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2270 return;
2272 free(mpctx->nav_buffer);
2274 mpctx->nav_buffer = malloc(in_size);
2275 mpctx->nav_start = start;
2276 mpctx->nav_in_size = mpctx->nav_buffer ? in_size : -1;
2277 if (mpctx->nav_buffer)
2278 memcpy(mpctx->nav_buffer,start,in_size);
2280 if (decoded_frame && mpctx->nav_smpi != decoded_frame)
2281 mpctx->nav_smpi = mp_dvdnav_copy_mpi(mpctx->nav_smpi,decoded_frame);
2283 #endif /* CONFIG_DVDNAV */
2285 /* Modify video timing to match the audio timeline. There are two main
2286 * reasons this is needed. First, video and audio can start from different
2287 * positions at beginning of file or after a seek (MPlayer starts both
2288 * immediately even if they have different pts). Second, the file can have
2289 * audio timestamps that are inconsistent with the duration of the audio
2290 * packets, for example two consecutive timestamp values differing by
2291 * one second but only a packet with enough samples for half a second
2292 * of playback between them.
2294 static void adjust_sync(struct MPContext *mpctx, double frame_time)
2296 current_module = "av_sync";
2298 if (!mpctx->sh_audio || mpctx->syncing_audio)
2299 return;
2301 double a_pts = written_audio_pts(mpctx) - mpctx->delay;
2302 double v_pts = mpctx->sh_video->pts;
2303 double av_delay = a_pts - v_pts;
2304 // Try to sync vo_flip() so it will *finish* at given time
2305 av_delay += mpctx->last_vo_flip_duration;
2306 av_delay -= audio_delay; // This much pts difference is desired
2308 double change = av_delay * 0.1;
2309 double max_change = default_max_pts_correction >= 0 ?
2310 default_max_pts_correction : frame_time * 0.1;
2311 if (change < -max_change)
2312 change = -max_change;
2313 else if (change > max_change)
2314 change = max_change;
2315 mpctx->delay += change;
2316 mpctx->total_avsync_change += change;
2319 #define ASYNC_PLAY_DONE -3
2320 static int audio_start_sync(struct MPContext *mpctx, int playsize)
2322 struct ao *ao = mpctx->ao;
2323 struct MPOpts *opts = &mpctx->opts;
2324 sh_audio_t * const sh_audio = mpctx->sh_audio;
2325 int res;
2327 // Timing info may not be set without
2328 res = decode_audio(sh_audio, 1);
2329 if (res < 0)
2330 return res;
2332 int bytes;
2333 bool did_retry = false;
2334 while (1) {
2335 double written_pts = written_audio_pts(mpctx);
2336 double ptsdiff = written_pts - mpctx->video_pts - mpctx->delay
2337 - audio_delay;
2338 bytes = ptsdiff * ao->bps / mpctx->opts.playback_speed;
2339 bytes -= bytes % (ao->channels * af_fmt2bits(ao->format) / 8);
2341 // ogg demuxers give packets without timing
2342 if (written_pts <= 1 && sh_audio->pts == MP_NOPTS_VALUE) {
2343 if (!did_retry) {
2344 // Try to read more data to see packets that have pts
2345 int res = decode_audio(sh_audio, ao->bps);
2346 if (res < 0)
2347 return res;
2348 did_retry = true;
2349 continue;
2351 bytes = 0;
2354 if (fabs(ptsdiff) > 300) // pts reset or just broken?
2355 bytes = 0;
2357 if (bytes > 0)
2358 break;
2360 mpctx->syncing_audio = false;
2361 int a = FFMIN(-bytes, FFMAX(playsize, 20000));
2362 int res = decode_audio(sh_audio, a);
2363 bytes += sh_audio->a_out_buffer_len;
2364 if (bytes >= 0) {
2365 memmove(sh_audio->a_out_buffer,
2366 sh_audio->a_out_buffer +
2367 sh_audio->a_out_buffer_len - bytes,
2368 bytes);
2369 sh_audio->a_out_buffer_len = bytes;
2370 if (res < 0)
2371 return res;
2372 return decode_audio(sh_audio, playsize);
2374 sh_audio->a_out_buffer_len = 0;
2375 if (res < 0)
2376 return res;
2378 int fillbyte = 0;
2379 if ((ao->format & AF_FORMAT_SIGN_MASK) == AF_FORMAT_US)
2380 fillbyte = 0x80;
2381 if (bytes >= playsize) {
2382 /* This case could fall back to the one below with
2383 * bytes = playsize, but then silence would keep accumulating
2384 * in a_out_buffer if the AO accepts less data than it asks for
2385 * in playsize. */
2386 char *p = malloc(playsize);
2387 memset(p, fillbyte, playsize);
2388 playsize = ao_play(ao, p, playsize, 0);
2389 free(p);
2390 mpctx->delay += opts->playback_speed*playsize/(double)ao->bps;
2391 return ASYNC_PLAY_DONE;
2393 mpctx->syncing_audio = false;
2394 decode_audio_prepend_bytes(sh_audio, bytes, fillbyte);
2395 return decode_audio(sh_audio, playsize);
2398 static int fill_audio_out_buffers(struct MPContext *mpctx)
2400 struct MPOpts *opts = &mpctx->opts;
2401 struct ao *ao = mpctx->ao;
2402 unsigned int t;
2403 double tt;
2404 int playsize;
2405 int playflags=0;
2406 bool audio_eof = false;
2407 bool partial_fill = false;
2408 bool format_change = false;
2409 sh_audio_t * const sh_audio = mpctx->sh_audio;
2410 bool modifiable_audio_format = !(ao->format & AF_FORMAT_SPECIAL_MASK);
2411 int unitsize = ao->channels * af_fmt2bits(ao->format) / 8;
2413 current_module="play_audio";
2415 if (ao->untimed && mpctx->sh_video && mpctx->delay > 0)
2416 return 0;
2418 // all the current uses of ao->pts seem to be in aos that handle
2419 // sync completely wrong; there should be no need to use ao->pts
2420 // in get_space()
2421 ao->pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2422 playsize = ao_get_space(ao);
2424 // Fill buffer if needed:
2425 current_module="decode_audio";
2426 t = GetTimer();
2428 if (!opts->initial_audio_sync || !modifiable_audio_format)
2429 mpctx->syncing_audio = false;
2431 int res;
2432 if (mpctx->syncing_audio && mpctx->sh_video)
2433 res = audio_start_sync(mpctx, playsize);
2434 else
2435 res = decode_audio(sh_audio, playsize);
2436 if (res < 0) { // EOF, error or format change
2437 if (res == -2)
2438 format_change = true;
2439 else if (res == ASYNC_PLAY_DONE)
2440 return 0;
2441 else if (mpctx->d_audio->eof)
2442 audio_eof = true;
2444 t = GetTimer() - t;
2445 tt = t*0.000001f; audio_time_usage+=tt;
2446 if (mpctx->timeline && modifiable_audio_format) {
2447 double endpts = mpctx->timeline[mpctx->timeline_part + 1].start;
2448 double bytes = (endpts - written_audio_pts(mpctx) + audio_delay)
2449 * ao->bps / opts->playback_speed;
2450 if (playsize > bytes) {
2451 playsize = FFMAX(bytes, 0);
2452 playflags |= AOPLAY_FINAL_CHUNK;
2453 audio_eof = true;
2454 partial_fill = true;
2458 assert(sh_audio->a_out_buffer_len % unitsize == 0);
2459 if (playsize > sh_audio->a_out_buffer_len) {
2460 partial_fill = true;
2461 playsize = sh_audio->a_out_buffer_len;
2462 if (audio_eof)
2463 playflags |= AOPLAY_FINAL_CHUNK;
2465 playsize -= playsize % unitsize;
2466 if (!playsize)
2467 return partial_fill && audio_eof ? -2 : -partial_fill;
2469 // play audio:
2470 current_module="play_audio";
2472 // Is this pts value actually useful for the aos that access it?
2473 // They're obviously badly broken in the way they handle av sync;
2474 // would not having access to this make them more broken?
2475 ao->pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2476 playsize = ao_play(ao, sh_audio->a_out_buffer, playsize, playflags);
2477 assert(playsize % unitsize == 0);
2479 if (playsize > 0) {
2480 sh_audio->a_out_buffer_len -= playsize;
2481 memmove(sh_audio->a_out_buffer, &sh_audio->a_out_buffer[playsize],
2482 sh_audio->a_out_buffer_len);
2483 mpctx->delay += opts->playback_speed*playsize/(double)ao->bps;
2484 } else if (audio_eof && ao_get_delay(ao) < .04) {
2485 // Sanity check to avoid hanging in case current ao doesn't output
2486 // partial chunks and doesn't check for AOPLAY_FINAL_CHUNK
2487 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Audio output truncated at end.\n");
2488 sh_audio->a_out_buffer_len = 0;
2491 /* The format change isn't handled too gracefully. A more precise
2492 * implementation would require draining buffered old-format audio
2493 * while displaying video, then doing the output format switch.
2495 if (format_change) {
2496 uninit_player(mpctx, INITIALIZED_AO);
2497 reinit_audio_chain(mpctx);
2498 return -1;
2501 return -partial_fill;
2504 static int sleep_until_near_frame(struct MPContext *mpctx, float *time_frame,
2505 bool sync_to_audio, float *aq_sleep_time)
2507 struct MPOpts *opts = &mpctx->opts;
2508 double audio_limit = 2;
2509 current_module="calc_sleep_time";
2511 if (mpctx->restart_playback)
2512 return 0;
2514 *time_frame -= get_relative_time(mpctx); // reset timer
2516 if (sync_to_audio) {
2517 float delay = ao_get_delay(mpctx->ao);
2518 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "delay=%f\n", delay);
2520 if (opts->autosync) {
2522 * Adjust this raw delay value by calculating the expected
2523 * delay for this frame and generating a new value which is
2524 * weighted between the two. The higher autosync is, the
2525 * closer to the delay value gets to that which "-nosound"
2526 * would have used, and the longer it will take for A/V
2527 * sync to settle at the right value (but it eventually will.)
2528 * This settling time is very short for values below 100.
2530 float predicted = mpctx->delay / opts->playback_speed + *time_frame;
2531 float difference = delay - predicted;
2532 delay = predicted + difference / (float)opts->autosync;
2535 *time_frame = delay - mpctx->delay / opts->playback_speed;
2537 // delay = amount of audio buffered in soundcard/driver
2538 delay = FFMIN(delay, 0.5);
2539 delay = FFMAX(delay, 0.1);
2540 audio_limit = delay;
2541 } else {
2542 // If we're lagging more than 200 ms behind the right playback rate,
2543 // don't try to "catch up".
2544 // If benchmark is set always output frames as fast as possible
2545 // without sleeping.
2546 if (*time_frame < -0.2 || opts->benchmark)
2547 *time_frame = 0;
2550 double t = *time_frame - mpctx->video_out->flip_queue_offset;
2552 if (t <= 0.05)
2553 return 0;
2555 t -= 0.05;
2556 if (t > audio_limit * 0.6)
2557 t = audio_limit * 0.5;
2558 *aq_sleep_time += t;
2559 mp_input_get_cmd(mpctx->input, t * 1000 + 1, 1);
2560 return 1;
2563 int reinit_video_chain(struct MPContext *mpctx)
2565 struct MPOpts *opts = &mpctx->opts;
2566 sh_video_t * const sh_video = mpctx->sh_video;
2567 if (!sh_video)
2568 return 0;
2569 double ar=-1.0;
2570 //================== Init VIDEO (codec & libvo) ==========================
2571 if (!opts->fixed_vo || !(mpctx->initialized_flags & INITIALIZED_VO)) {
2572 current_module="preinit_libvo";
2574 //shouldn't we set dvideo->id=-2 when we fail?
2575 //if((mpctx->video_out->preinit(vo_subdevice))!=0){
2576 if(!(mpctx->video_out=init_best_video_out(opts, mpctx->x11_state, mpctx->key_fifo, mpctx->input))){
2577 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Error opening/initializing the selected video_out (-vo) device.\n");
2578 goto err_out;
2580 mpctx->initialized_flags|=INITIALIZED_VO;
2583 if(stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_ASPECT_RATIO, &ar) != STREAM_UNSUPPORTED)
2584 mpctx->sh_video->stream_aspect = ar;
2585 current_module="init_video_filters";
2587 char* vf_arg[] = { "_oldargs_", (char*)mpctx->video_out , NULL };
2588 sh_video->vfilter = vf_open_filter(opts, NULL,"vo",vf_arg);
2590 #ifdef CONFIG_MENU
2591 if(use_menu) {
2592 char* vf_arg[] = { "_oldargs_", menu_root, NULL };
2593 vf_menu = vf_open_plugin(opts,libmenu_vfs,sh_video->vfilter,"menu",vf_arg);
2594 if(!vf_menu) {
2595 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Can't open libmenu video filter with root menu %s.\n",menu_root);
2596 use_menu = 0;
2599 if(vf_menu)
2600 sh_video->vfilter = vf_menu;
2601 #endif
2603 #ifdef CONFIG_ASS
2604 if(opts->ass_enabled) {
2605 int i;
2606 int insert = 1;
2607 if (opts->vf_settings)
2608 for (i = 0; opts->vf_settings[i].name; ++i)
2609 if (strcmp(opts->vf_settings[i].name, "ass") == 0) {
2610 insert = 0;
2611 break;
2613 if (insert) {
2614 extern vf_info_t vf_info_ass;
2615 const vf_info_t* libass_vfs[] = {&vf_info_ass, NULL};
2616 char* vf_arg[] = {"auto", "1", NULL};
2617 int retcode = 0;
2618 struct vf_instance *vf_ass = vf_open_plugin_noerr(opts, libass_vfs,
2619 sh_video->vfilter,
2620 "ass", vf_arg,
2621 &retcode);
2622 if (vf_ass)
2623 sh_video->vfilter = vf_ass;
2624 else if (retcode == -1) // vf_ass open() returns -1 if there's VO EOSD
2625 mp_msg(MSGT_CPLAYER, MSGL_V, "[ass] vf_ass not needed\n");
2626 else
2627 mp_msg(MSGT_CPLAYER,MSGL_ERR, "ASS: cannot add video filter\n");
2630 #endif
2632 sh_video->vfilter = append_filters(sh_video->vfilter, opts->vf_settings);
2634 #ifdef CONFIG_ASS
2635 if (opts->ass_enabled)
2636 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_INIT_EOSD, ass_library);
2637 #endif
2639 current_module="init_video_codec";
2641 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2642 init_best_video_codec(sh_video,video_codec_list,video_fm_list);
2643 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2645 if(!sh_video->initialized){
2646 if(!opts->fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
2647 goto err_out;
2650 mpctx->initialized_flags|=INITIALIZED_VCODEC;
2652 if (sh_video->codec)
2653 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODEC=%s\n", sh_video->codec->name);
2655 sh_video->last_pts = MP_NOPTS_VALUE;
2656 sh_video->num_buffered_pts = 0;
2657 sh_video->next_frame_time = 0;
2659 if (opts->auto_quality > 0) {
2660 // Auto quality option enabled
2661 output_quality=get_video_quality_max(sh_video);
2662 if (opts->auto_quality > output_quality)
2663 opts->auto_quality = output_quality;
2664 else
2665 output_quality = opts->auto_quality;
2666 mp_msg(MSGT_CPLAYER,MSGL_V,"AutoQ: setting quality to %d.\n",output_quality);
2667 set_video_quality(sh_video,output_quality);
2670 // ========== Init display (sh_video->disp_w*sh_video->disp_h/out_fmt) ============
2672 current_module="init_vo";
2674 return 1;
2676 err_out:
2677 mpctx->sh_video = mpctx->d_video->sh = NULL;
2678 return 0;
2681 static double update_video_nocorrect_pts(struct MPContext *mpctx)
2683 struct sh_video *sh_video = mpctx->sh_video;
2684 double frame_time = 0;
2685 struct vo *video_out = mpctx->video_out;
2686 while (1) {
2687 current_module = "filter_video";
2688 // In nocorrect-pts mode there is no way to properly time these frames
2689 if (vo_get_buffered_frame(video_out, 0) >= 0)
2690 break;
2691 if (vf_output_queued_frame(sh_video->vfilter))
2692 break;
2693 unsigned char *packet = NULL;
2694 frame_time = sh_video->next_frame_time;
2695 if (mpctx->restart_playback)
2696 frame_time = 0;
2697 int in_size = video_read_frame(sh_video, &sh_video->next_frame_time,
2698 &packet, force_fps);
2699 if (in_size < 0) {
2700 #ifdef CONFIG_DVDNAV
2701 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
2702 if (mp_dvdnav_is_eof(mpctx->stream))
2703 return -1;
2704 if (mpctx->d_video)
2705 mpctx->d_video->eof = 0;
2706 if (mpctx->d_audio)
2707 mpctx->d_audio->eof = 0;
2708 mpctx->stream->eof = 0;
2709 } else
2710 #endif
2711 return -1;
2713 if (in_size > max_framesize)
2714 max_framesize = in_size;
2715 sh_video->timer += frame_time;
2716 if (mpctx->sh_audio)
2717 mpctx->delay -= frame_time;
2718 // video_read_frame can change fps (e.g. for ASF video)
2719 vo_fps = sh_video->fps;
2720 int framedrop_type = check_framedrop(mpctx, frame_time);
2721 current_module = "decode video";
2723 void *decoded_frame;
2724 #ifdef CONFIG_DVDNAV
2725 decoded_frame = mp_dvdnav_restore_smpi(mpctx, &in_size, &packet, NULL);
2726 if (in_size >= 0 && !decoded_frame)
2727 #endif
2728 decoded_frame = decode_video(sh_video, packet, in_size, framedrop_type,
2729 sh_video->pts);
2730 #ifdef CONFIG_DVDNAV
2731 // Save last still frame for future display
2732 mp_dvdnav_save_smpi(mpctx, in_size, packet, decoded_frame);
2733 #endif
2734 if (decoded_frame) {
2735 current_module = "filter video";
2736 filter_video(sh_video, decoded_frame, sh_video->pts);
2738 break;
2740 return frame_time;
2743 static void determine_frame_pts(struct MPContext *mpctx)
2745 struct sh_video *sh_video = mpctx->sh_video;
2746 struct MPOpts *opts = &mpctx->opts;
2748 if (opts->user_pts_assoc_mode) {
2749 sh_video->pts_assoc_mode = opts->user_pts_assoc_mode;
2750 } else if (sh_video->pts_assoc_mode == 0) {
2751 if (mpctx->d_video->demuxer->timestamp_type == TIMESTAMP_TYPE_PTS
2752 && sh_video->codec_reordered_pts != MP_NOPTS_VALUE)
2753 sh_video->pts_assoc_mode = 1;
2754 else
2755 sh_video->pts_assoc_mode = 2;
2756 } else {
2757 int probcount1 = sh_video->num_reordered_pts_problems;
2758 int probcount2 = sh_video->num_sorted_pts_problems;
2759 if (sh_video->pts_assoc_mode == 2) {
2760 int tmp = probcount1;
2761 probcount1 = probcount2;
2762 probcount2 = tmp;
2764 if (probcount1 >= probcount2 * 1.5 + 2) {
2765 sh_video->pts_assoc_mode = 3 - sh_video->pts_assoc_mode;
2766 mp_msg(MSGT_CPLAYER, MSGL_V, "Switching to pts association mode "
2767 "%d.\n", sh_video->pts_assoc_mode);
2770 sh_video->pts = sh_video->pts_assoc_mode == 1 ?
2771 sh_video->codec_reordered_pts : sh_video->sorted_pts;
2774 static double update_video(struct MPContext *mpctx)
2776 struct sh_video *sh_video = mpctx->sh_video;
2777 struct vo *video_out = mpctx->video_out;
2778 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_SET_OSD_OBJ,
2779 mpctx->osd); // hack for vf_expand
2780 if (!mpctx->opts.correct_pts)
2781 return update_video_nocorrect_pts(mpctx);
2783 double pts;
2785 while (1) {
2786 current_module = "filter_video";
2787 if (!mpctx->hrseek_active
2788 && vo_get_buffered_frame(video_out, false) >= 0)
2789 break;
2790 // XXX Time used in this call is not counted in any performance
2791 // timer now
2792 if (vf_output_queued_frame(sh_video->vfilter))
2793 break;
2794 unsigned char *packet = NULL;
2795 int in_size = ds_get_packet_pts(mpctx->d_video, &packet, &pts);
2796 if (pts != MP_NOPTS_VALUE)
2797 pts += mpctx->video_offset;
2798 bool hit_eof = false;
2799 if (in_size < 0) {
2800 // try to extract last frames in case of decoder lag
2801 in_size = 0;
2802 pts = MP_NOPTS_VALUE;
2803 hit_eof = true;
2805 if (in_size > max_framesize)
2806 max_framesize = in_size;
2807 current_module = "decode video";
2808 if (pts >= mpctx->hrseek_pts - .005)
2809 mpctx->hrseek_framedrop = false;
2810 int framedrop_type = mpctx->hrseek_framedrop ? 1 :
2811 check_framedrop(mpctx, sh_video->frametime);
2812 void *decoded_frame = decode_video(sh_video, packet, in_size,
2813 framedrop_type, pts);
2814 if (decoded_frame) {
2815 determine_frame_pts(mpctx);
2816 current_module = "filter video";
2817 filter_video(sh_video, decoded_frame, sh_video->pts);
2818 } else if (hit_eof) {
2819 if (vo_get_buffered_frame(video_out, true) < 0)
2820 return -1;
2822 break;
2825 if (!video_out->frame_loaded)
2826 return 0;
2828 pts = video_out->next_pts;
2829 if (pts == MP_NOPTS_VALUE) {
2830 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Video pts after filters MISSING\n");
2831 // Try to use decoder pts from before filters
2832 pts = sh_video->pts;
2833 if (pts == MP_NOPTS_VALUE)
2834 pts = sh_video->last_pts;
2836 if (mpctx->hrseek_active && pts < mpctx->hrseek_pts - .005) {
2837 vo_skip_frame(video_out);
2838 return 0;
2840 mpctx->hrseek_active = false;
2841 sh_video->pts = pts;
2842 if (sh_video->last_pts == MP_NOPTS_VALUE)
2843 sh_video->last_pts = sh_video->pts;
2844 else if (sh_video->last_pts > sh_video->pts) {
2845 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Decreasing video pts: %f < %f\n",
2846 sh_video->pts, sh_video->last_pts);
2847 /* If the difference in pts is small treat it as jitter around the
2848 * right value (possibly caused by incorrect timestamp ordering) and
2849 * just show this frame immediately after the last one.
2850 * Treat bigger differences as timestamp resets and start counting
2851 * timing of later frames from the position of this one. */
2852 if (sh_video->last_pts - sh_video->pts > 0.5)
2853 sh_video->last_pts = sh_video->pts;
2854 else
2855 sh_video->pts = sh_video->last_pts;
2857 double frame_time = sh_video->pts - sh_video->last_pts;
2858 sh_video->last_pts = sh_video->pts;
2859 sh_video->timer += frame_time;
2860 if (mpctx->sh_audio)
2861 mpctx->delay -= frame_time;
2862 return frame_time;
2865 void pause_player(struct MPContext *mpctx)
2867 if (mpctx->paused)
2868 return;
2869 mpctx->paused = 1;
2870 mpctx->step_frames = 0;
2871 mpctx->time_frame -= get_relative_time(mpctx);
2873 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2874 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2876 if (mpctx->ao && mpctx->sh_audio)
2877 ao_pause(mpctx->ao); // pause audio, keep data if possible
2880 void unpause_player(struct MPContext *mpctx)
2882 if (!mpctx->paused)
2883 return;
2884 mpctx->paused = 0;
2886 if (mpctx->ao && mpctx->sh_audio)
2887 ao_resume(mpctx->ao);
2888 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok
2889 && !mpctx->step_frames)
2890 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL); // resume video
2891 (void)get_relative_time(mpctx); // ignore time that passed during pause
2894 void add_step_frame(struct MPContext *mpctx)
2896 mpctx->step_frames++;
2897 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2898 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2899 unpause_player(mpctx);
2902 static void pause_loop(struct MPContext *mpctx)
2904 struct MPOpts *opts = &mpctx->opts;
2905 mp_cmd_t* cmd;
2906 #ifdef CONFIG_STREAM_CACHE
2907 int old_cache_fill = stream_cache_size > 0 ?
2908 cache_fill_status(mpctx->stream) : 0;
2909 #endif
2910 if (!opts->quiet) {
2911 if (opts->term_osd && !mpctx->sh_video) {
2912 set_osd_tmsg(OSD_MSG_PAUSE, 1, 0, " ===== PAUSE =====");
2913 update_osd_msg(mpctx);
2914 } else
2915 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "\n%s\r",
2916 mp_gtext(" ===== PAUSE ====="));
2917 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_PAUSED\n");
2920 while ( (cmd = mp_input_get_cmd(mpctx->input, 20, 1)) == NULL
2921 || cmd->id == MP_CMD_SET_MOUSE_POS || cmd->pausing == 4) {
2922 if (cmd) {
2923 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
2924 run_command(mpctx, cmd);
2925 mp_cmd_free(cmd);
2926 continue;
2928 if (mpctx->sh_video && mpctx->video_out)
2929 vo_check_events(mpctx->video_out);
2930 #ifdef CONFIG_MENU
2931 if (vf_menu)
2932 vf_menu_pause_update(vf_menu);
2933 #endif
2934 usec_sleep(20000);
2935 update_osd_msg(mpctx);
2936 int hack = vo_osd_changed(0);
2937 vo_osd_changed(hack);
2938 if (hack)
2939 break;
2940 #ifdef CONFIG_STREAM_CACHE
2941 if (!opts->quiet && stream_cache_size > 0) {
2942 int new_cache_fill = cache_fill_status(mpctx->stream);
2943 if (new_cache_fill != old_cache_fill) {
2944 if (opts->term_osd && !mpctx->sh_video) {
2945 set_osd_tmsg(OSD_MSG_PAUSE, 1, 0, "%s %d%%",
2946 mp_gtext(" ===== PAUSE ====="),
2947 new_cache_fill);
2948 update_osd_msg(mpctx);
2949 } else
2950 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "%s %d%%\r",
2951 mp_gtext(" ===== PAUSE ====="),
2952 new_cache_fill);
2953 old_cache_fill = new_cache_fill;
2956 #endif
2961 // Find the right mute status and record position for new file position
2962 static void edl_seek_reset(MPContext *mpctx)
2964 mpctx->edl_muted = 0;
2965 next_edl_record = edl_records;
2967 while (next_edl_record) {
2968 if (next_edl_record->start_sec >= get_current_time(mpctx))
2969 break;
2971 if (next_edl_record->action == EDL_MUTE)
2972 mpctx->edl_muted = !mpctx->edl_muted;
2973 next_edl_record = next_edl_record->next;
2975 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2976 mixer_mute(&mpctx->mixer);
2980 // Execute EDL command for the current position if one exists
2981 static void edl_update(MPContext *mpctx)
2983 if (!next_edl_record)
2984 return;
2986 if (!mpctx->sh_video) {
2987 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot use EDL without video, disabling.\n");
2988 free_edl(edl_records);
2989 next_edl_record = NULL;
2990 edl_records = NULL;
2991 return;
2994 if (get_current_time(mpctx) >= next_edl_record->start_sec) {
2995 if (next_edl_record->action == EDL_SKIP) {
2996 mpctx->osd_function = OSD_FFW;
2997 queue_seek(mpctx, MPSEEK_RELATIVE, next_edl_record->length_sec, 0);
2998 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_SKIP: start [%f], stop "
2999 "[%f], length [%f]\n", next_edl_record->start_sec,
3000 next_edl_record->stop_sec, next_edl_record->length_sec);
3002 else if (next_edl_record->action == EDL_MUTE) {
3003 mpctx->edl_muted = !mpctx->edl_muted;
3004 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
3005 mixer_mute(&mpctx->mixer);
3006 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_MUTE: [%f]\n",
3007 next_edl_record->start_sec );
3009 next_edl_record = next_edl_record->next;
3013 static void reinit_decoders(struct MPContext *mpctx)
3015 reinit_video_chain(mpctx);
3016 reinit_audio_chain(mpctx);
3017 mp_property_do("sub", M_PROPERTY_SET, &(int){mpctx->global_sub_pos}, mpctx);
3020 static void seek_reset(struct MPContext *mpctx, bool reset_ao)
3022 if (mpctx->sh_video) {
3023 current_module = "seek_video_reset";
3024 resync_video_stream(mpctx->sh_video);
3025 mpctx->sh_video->timer = 0;
3026 vo_seek_reset(mpctx->video_out);
3027 mpctx->sh_video->timer = 0;
3028 mpctx->sh_video->num_buffered_pts = 0;
3029 mpctx->sh_video->last_pts = MP_NOPTS_VALUE;
3030 mpctx->delay = 0;
3031 mpctx->time_frame = 0;
3032 mpctx->restart_playback = true;
3033 // Not all demuxers set d_video->pts during seek, so this value
3034 // (which is used by at least vobsub and edl code below) may
3035 // be completely wrong (probably 0).
3036 mpctx->sh_video->pts = mpctx->d_video->pts + mpctx->video_offset;
3037 mpctx->video_pts = mpctx->sh_video->pts;
3038 update_subtitles(mpctx, mpctx->sh_video->pts, mpctx->video_offset,
3039 true);
3040 update_teletext(mpctx->sh_video, mpctx->demuxer, 1);
3043 if (mpctx->sh_audio) {
3044 current_module = "seek_audio_reset";
3045 resync_audio_stream(mpctx->sh_audio);
3046 if (reset_ao)
3047 // stop audio, throwing away buffered data
3048 ao_reset(mpctx->ao);
3049 mpctx->sh_audio->a_buffer_len = 0;
3050 mpctx->sh_audio->a_out_buffer_len = 0;
3051 if (!mpctx->sh_video)
3052 update_subtitles(mpctx, mpctx->sh_audio->pts,
3053 mpctx->video_offset, true);
3056 if (vo_vobsub && mpctx->sh_video) {
3057 current_module = "seek_vobsub_reset";
3058 vobsub_seek(vo_vobsub, mpctx->sh_video->pts);
3061 edl_seek_reset(mpctx);
3063 mpctx->hrseek_active = false;
3064 mpctx->hrseek_framedrop = false;
3065 mpctx->total_avsync_change = 0;
3066 audio_time_usage = 0; video_time_usage = 0; vout_time_usage = 0;
3067 drop_frame_cnt = 0;
3069 current_module = NULL;
3072 static bool timeline_set_part(struct MPContext *mpctx, int i)
3074 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
3075 struct timeline_part *n = mpctx->timeline + i;
3076 mpctx->timeline_part = i;
3077 mpctx->video_offset = n->start - n->source_start;
3078 if (n->source == p->source)
3079 return false;
3080 enum stop_play_reason orig_stop_play = mpctx->stop_play;
3081 if (!mpctx->sh_video && mpctx->stop_play == KEEP_PLAYING)
3082 mpctx->stop_play = AT_END_OF_FILE; // let audio uninit drain data
3083 uninit_player(mpctx, INITIALIZED_VCODEC | (mpctx->opts.fixed_vo ? 0 : INITIALIZED_VO) | (mpctx->opts.gapless_audio ? 0 : INITIALIZED_AO) | INITIALIZED_ACODEC | INITIALIZED_SUB);
3084 mpctx->stop_play = orig_stop_play;
3085 mpctx->demuxer = n->source->demuxer;
3086 mpctx->d_video = mpctx->demuxer->video;
3087 mpctx->d_audio = mpctx->demuxer->audio;
3088 mpctx->d_sub = mpctx->demuxer->sub;
3089 mpctx->sh_video = mpctx->d_video->sh;
3090 mpctx->sh_audio = mpctx->d_audio->sh;
3091 return true;
3094 // Given pts, switch playback to the corresponding part.
3095 // Return offset within that part.
3096 static double timeline_set_from_time(struct MPContext *mpctx, double pts,
3097 bool *need_reset)
3099 if (pts < 0)
3100 pts = 0;
3101 for (int i = 0; i < mpctx->num_timeline_parts; i++) {
3102 struct timeline_part *p = mpctx->timeline + i;
3103 if (pts < (p+1)->start) {
3104 *need_reset = timeline_set_part(mpctx, i);
3105 return pts - p->start + p->source_start;
3108 return -1;
3112 // return -1 if seek failed (non-seekable stream?), 0 otherwise
3113 static int seek(MPContext *mpctx, struct seek_params seek,
3114 bool timeline_fallthrough)
3116 struct MPOpts *opts = &mpctx->opts;
3118 current_module = "seek";
3119 if (mpctx->stop_play == AT_END_OF_FILE)
3120 mpctx->stop_play = KEEP_PLAYING;
3121 bool hr_seek = mpctx->demuxer->accurate_seek && opts->correct_pts;
3122 hr_seek &= seek.exact >= 0 && seek.type != MPSEEK_FACTOR;
3123 hr_seek &= opts->hr_seek == 0 && seek.type == MPSEEK_ABSOLUTE
3124 || opts->hr_seek > 0 || seek.exact > 0;
3125 if (seek.type == MPSEEK_FACTOR
3126 || seek.type == MPSEEK_ABSOLUTE
3127 && seek.amount < mpctx->last_chapter_pts
3128 || seek.amount < 0)
3129 mpctx->last_chapter_seek = -1;
3130 if (mpctx->timeline && seek.type == MPSEEK_FACTOR) {
3131 seek.amount *= mpctx->timeline[mpctx->num_timeline_parts].start;
3132 seek.type = MPSEEK_ABSOLUTE;
3134 if ((mpctx->demuxer->accurate_seek || mpctx->timeline)
3135 && seek.type == MPSEEK_RELATIVE) {
3136 seek.type = MPSEEK_ABSOLUTE;
3137 seek.direction = seek.amount > 0 ? 1 : -1;
3138 seek.amount += get_current_time(mpctx);
3141 /* At least the liba52 decoder wants to read from the input stream
3142 * during initialization, so reinit must be done after the demux_seek()
3143 * call that clears possible stream EOF. */
3144 bool need_reset = false;
3145 double demuxer_amount = seek.amount;
3146 if (mpctx->timeline) {
3147 demuxer_amount = timeline_set_from_time(mpctx, seek.amount,
3148 &need_reset);
3149 if (demuxer_amount == -1) {
3150 mpctx->stop_play = AT_END_OF_FILE;
3151 // Clear audio from current position
3152 if (mpctx->sh_audio) {
3153 ao_reset(mpctx->ao);
3154 mpctx->sh_audio->a_buffer_len = 0;
3155 mpctx->sh_audio->a_out_buffer_len = 0;
3157 return -1;
3160 int demuxer_style = 0;
3161 switch (seek.type) {
3162 case MPSEEK_FACTOR:
3163 demuxer_style |= SEEK_FACTOR; // fallthrough
3164 case MPSEEK_ABSOLUTE:
3165 demuxer_style |= SEEK_ABSOLUTE;
3167 if (hr_seek || seek.direction < 0)
3168 demuxer_style |= SEEK_BACKWARD;
3169 else if (seek.direction > 0)
3170 demuxer_style |= SEEK_FORWARD;
3172 int seekresult = demux_seek(mpctx->demuxer, demuxer_amount, audio_delay,
3173 demuxer_style);
3174 if (need_reset)
3175 reinit_decoders(mpctx);
3176 if (seekresult == 0)
3177 return -1;
3179 seek_reset(mpctx, !timeline_fallthrough);
3181 /* Use the target time as "current position" for further relative
3182 * seeks etc until a new video frame has been decoded */
3183 if (seek.type == MPSEEK_ABSOLUTE)
3184 mpctx->video_pts = seek.amount;
3186 if (hr_seek) {
3187 mpctx->hrseek_active = true;
3188 mpctx->hrseek_framedrop = true;
3189 mpctx->hrseek_pts = seek.amount;
3192 mpctx->start_timestamp = GetTimerMS();
3194 return 0;
3197 void queue_seek(struct MPContext *mpctx, enum seek_type type, double amount,
3198 int exact)
3200 struct seek_params *seek = &mpctx->seek;
3201 switch (type) {
3202 case MPSEEK_RELATIVE:
3203 if (seek->type == MPSEEK_FACTOR)
3204 return; // Well... not common enough to bother doing better
3205 seek->amount += amount;
3206 seek->exact = FFMAX(seek->exact, exact);
3207 if (seek->type == MPSEEK_NONE)
3208 seek->exact = exact;
3209 if (seek->type == MPSEEK_ABSOLUTE)
3210 return;
3211 if (seek->amount == 0) {
3212 *seek = (struct seek_params){0};
3213 return;
3215 seek->type = MPSEEK_RELATIVE;
3216 return;
3217 case MPSEEK_ABSOLUTE:
3218 case MPSEEK_FACTOR:
3219 *seek = (struct seek_params) {
3220 .type = type,
3221 .amount = amount,
3222 .exact = exact,
3224 return;
3225 case MPSEEK_NONE:
3226 *seek = (struct seek_params){0};
3227 return;
3229 abort();
3233 double get_time_length(struct MPContext *mpctx)
3235 if (mpctx->timeline)
3236 return mpctx->timeline[mpctx->num_timeline_parts].start;
3238 struct demuxer *demuxer = mpctx->demuxer;
3239 double get_time_ans;
3240 // <= 0 means DEMUXER_CTRL_NOTIMPL or DEMUXER_CTRL_DONTKNOW
3241 if (demux_control(demuxer, DEMUXER_CTRL_GET_TIME_LENGTH,
3242 (void *) &get_time_ans) > 0)
3243 return get_time_ans;
3245 struct sh_video *sh_video = mpctx->d_video->sh;
3246 struct sh_audio *sh_audio = mpctx->d_audio->sh;
3247 if (sh_video && sh_video->i_bps && sh_audio && sh_audio->i_bps)
3248 return (double) (demuxer->movi_end - demuxer->movi_start) /
3249 (sh_video->i_bps + sh_audio->i_bps);
3250 if (sh_video && sh_video->i_bps)
3251 return (double) (demuxer->movi_end - demuxer->movi_start) /
3252 sh_video->i_bps;
3253 if (sh_audio && sh_audio->i_bps)
3254 return (double) (demuxer->movi_end - demuxer->movi_start) /
3255 sh_audio->i_bps;
3256 return 0;
3259 /* If there are timestamps from stream level then use those (for example
3260 * DVDs can have consistent times there while the MPEG-level timestamps
3261 * reset). */
3262 double get_current_time(struct MPContext *mpctx)
3264 struct demuxer *demuxer = mpctx->demuxer;
3265 if (demuxer->stream_pts != MP_NOPTS_VALUE)
3266 return demuxer->stream_pts;
3267 struct sh_video *sh_video = demuxer->video->sh;
3268 if (sh_video)
3269 return mpctx->video_pts;
3270 return playing_audio_pts(mpctx);
3273 int get_percent_pos(struct MPContext *mpctx)
3275 struct demuxer *demuxer = mpctx->demuxer;
3276 int ans = 0;
3277 if (mpctx->timeline)
3278 ans = get_current_time(mpctx) * 100 /
3279 mpctx->timeline[mpctx->num_timeline_parts].start;
3280 else if (demux_control(demuxer, DEMUXER_CTRL_GET_PERCENT_POS, &ans) > 0)
3282 else {
3283 int len = (demuxer->movi_end - demuxer->movi_start) / 100;
3284 off_t pos = demuxer->filepos > 0 ?
3285 demuxer->filepos : stream_tell(demuxer->stream);
3286 if (len > 0)
3287 ans = (pos - demuxer->movi_start) / len;
3288 else
3289 ans = 0;
3291 if (ans < 0)
3292 ans = 0;
3293 if (ans > 100)
3294 ans = 100;
3295 return ans;
3298 // -2 is no chapters, -1 is before first chapter
3299 int get_current_chapter(struct MPContext *mpctx)
3301 double current_pts = get_current_time(mpctx);
3302 if (!mpctx->chapters)
3303 return FFMAX(mpctx->last_chapter_seek,
3304 demuxer_get_current_chapter(mpctx->demuxer, current_pts));
3306 int i;
3307 for (i = 1; i < mpctx->num_chapters; i++)
3308 if (current_pts < mpctx->chapters[i].start)
3309 break;
3310 return FFMAX(mpctx->last_chapter_seek, i - 1);
3313 // currently returns a string allocated with malloc, not talloc
3314 char *chapter_display_name(struct MPContext *mpctx, int chapter)
3316 if (!mpctx->chapters || !mpctx->sh_video)
3317 return demuxer_chapter_display_name(mpctx->demuxer, chapter);
3318 return strdup(mpctx->chapters[chapter].name);
3321 int seek_chapter(struct MPContext *mpctx, int chapter, double *seek_pts,
3322 char **chapter_name)
3324 mpctx->last_chapter_seek = -1;
3325 if (!mpctx->chapters || !mpctx->sh_video) {
3326 int res = demuxer_seek_chapter(mpctx->demuxer, chapter, seek_pts,
3327 chapter_name);
3328 if (res >= 0) {
3329 if (*seek_pts == -1)
3330 seek_reset(mpctx, true);
3331 else {
3332 mpctx->last_chapter_seek = res;
3333 mpctx->last_chapter_pts = *seek_pts;
3336 return res;
3339 if (chapter >= mpctx->num_chapters)
3340 return -1;
3341 if (chapter < 0)
3342 chapter = 0;
3343 *seek_pts = mpctx->chapters[chapter].start;
3344 mpctx->last_chapter_seek = chapter;
3345 mpctx->last_chapter_pts = *seek_pts;
3346 if (chapter_name)
3347 *chapter_name = talloc_strdup(NULL, mpctx->chapters[chapter].name);
3348 return chapter;
3352 static void run_playloop(struct MPContext *mpctx)
3354 struct MPOpts *opts = &mpctx->opts;
3355 float aq_sleep_time = 0;
3356 bool full_audio_buffers = false;
3358 if (opts->chapterrange[1] > 0) {
3359 int cur_chapter = get_current_chapter(mpctx);
3360 if (cur_chapter!=-1 && cur_chapter + 1 > opts->chapterrange[1])
3361 mpctx->stop_play = PT_NEXT_ENTRY;
3364 if (!mpctx->sh_audio && mpctx->d_audio->sh) {
3365 mpctx->sh_audio = mpctx->d_audio->sh;
3366 mpctx->sh_audio->ds = mpctx->d_audio;
3367 reinit_audio_chain(mpctx);
3370 /*========================== PLAY AUDIO ============================*/
3372 if (mpctx->sh_audio && !mpctx->paused
3373 && (!mpctx->restart_playback || !mpctx->sh_video)) {
3374 int status = fill_audio_out_buffers(mpctx);
3375 full_audio_buffers = status >= 0 && !mpctx->ao->untimed;
3376 if (status == -2)
3377 // at eof, all audio at least written to ao
3378 if (!mpctx->sh_video)
3379 mpctx->stop_play = AT_END_OF_FILE;
3383 if (!mpctx->sh_video) {
3384 mpctx->restart_playback = false;
3385 if (mpctx->step_frames) {
3386 mpctx->step_frames = 0;
3387 pause_player(mpctx);
3389 // handle audio-only case:
3390 double a_pos = 0, a_buf = 0;
3391 // sh_audio can be NULL due to video stream switching
3392 // TODO: handle this better
3393 if (mpctx->sh_audio) {
3394 a_buf = ao_get_delay(mpctx->ao);
3395 a_pos = written_audio_pts(mpctx) - mpctx->opts.playback_speed *
3396 a_buf;
3399 print_status(mpctx, a_pos, false);
3401 update_subtitles(mpctx, a_pos, mpctx->video_offset, false);
3402 update_osd_msg(mpctx);
3403 if (end_at.type == END_AT_TIME && end_at.pos < a_pos) {
3404 mpctx->stop_play = AT_END_OF_FILE;
3405 } else if (mpctx->timeline && mpctx->stop_play == AT_END_OF_FILE
3406 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts
3407 && mpctx->sh_audio) {
3408 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
3409 if (!opts->gapless_audio && p->source != (p+1)->source
3410 && a_buf > 0.05) {
3411 mpctx->stop_play = KEEP_PLAYING;
3412 mp_input_get_cmd(mpctx->input, (a_buf-.05) * 1000, true);
3413 } else {
3414 seek(mpctx, (struct seek_params){ .type = MPSEEK_ABSOLUTE,
3415 .amount = (p+1)->start },
3416 true);
3418 } else if (!mpctx->stop_play) {
3419 int sleep_time = 100;
3420 if (mpctx->sh_audio) {
3421 if (mpctx->ao->untimed)
3422 sleep_time = 0;
3423 else if (full_audio_buffers)
3424 sleep_time = FFMAX(20, a_buf * 1000 - 50);
3425 else
3426 sleep_time = 20;
3427 sleep_time = FFMIN(sleep_time, 100);
3429 mp_input_get_cmd(mpctx->input, sleep_time, true);
3431 } else {
3433 /*========================== PLAY VIDEO ============================*/
3435 vo_pts = mpctx->sh_video->timer * 90000.0;
3436 vo_fps = mpctx->sh_video->fps;
3438 bool blit_frame = mpctx->video_out->frame_loaded;
3439 if (!blit_frame || mpctx->hrseek_active) {
3440 double frame_time = update_video(mpctx);
3441 blit_frame = mpctx->video_out->frame_loaded;
3442 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "*** ftime=%5.3f ***\n", frame_time);
3443 if (mpctx->sh_video->vf_initialized < 0) {
3444 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
3445 "\nFATAL: Could not initialize video filters (-vf) "
3446 "or video output (-vo).\n");
3447 mpctx->stop_play = PT_NEXT_ENTRY;
3448 return;
3450 if (frame_time < 0)
3451 mpctx->stop_play = AT_END_OF_FILE;
3452 else if (!mpctx->restart_playback) {
3453 mpctx->time_frame += frame_time / opts->playback_speed;
3454 adjust_sync(mpctx, frame_time);
3457 if (mpctx->timeline) {
3458 struct timeline_part *next =
3459 mpctx->timeline + mpctx->timeline_part + 1;
3460 if (mpctx->sh_video->pts >= next->start
3461 || mpctx->stop_play == AT_END_OF_FILE
3462 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts) {
3463 seek(mpctx, (struct seek_params){ .type = MPSEEK_ABSOLUTE,
3464 .amount = next->start },
3465 true);
3466 return;
3470 // ==========================================================================
3472 current_module = "vo_check_events";
3473 vo_check_events(mpctx->video_out);
3475 #ifdef CONFIG_X11
3476 if (stop_xscreensaver) {
3477 current_module = "stop_xscreensaver";
3478 xscreensaver_heartbeat(mpctx->x11_state);
3480 #endif
3481 if (heartbeat_cmd) {
3482 static unsigned last_heartbeat;
3483 unsigned now = GetTimerMS();
3484 if (now - last_heartbeat > 30000) {
3485 last_heartbeat = now;
3486 system(heartbeat_cmd);
3490 bool frame_time_remaining = sleep_until_near_frame(mpctx,
3491 &mpctx->time_frame,
3492 full_audio_buffers,
3493 &aq_sleep_time);
3495 //====================== FLIP PAGE (VIDEO BLT): =========================
3497 current_module = "flip_page";
3498 if (!frame_time_remaining && blit_frame) {
3499 struct sh_video *sh_video = mpctx->sh_video;
3500 mpctx->video_pts = sh_video->pts;
3501 update_subtitles(mpctx, sh_video->pts, mpctx->video_offset, false);
3502 update_teletext(sh_video, mpctx->demuxer, 0);
3503 update_osd_msg(mpctx);
3504 struct vf_instance *vf = sh_video->vfilter;
3505 vf->control(vf, VFCTRL_DRAW_EOSD, mpctx->osd);
3506 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
3507 vo_osd_changed(0);
3509 mpctx->time_frame -= mpctx->video_out->flip_queue_offset;
3510 aq_sleep_time += mpctx->time_frame;
3511 // flag 256 means: libvo driver does its timing (dvb card)
3512 if (mpctx->time_frame > 0.001
3513 && !(mpctx->sh_video->output_flags & VFCAP_TIMER))
3514 mpctx->time_frame = timing_sleep(mpctx, mpctx->time_frame);
3515 mpctx->time_frame += mpctx->video_out->flip_queue_offset;
3517 unsigned int t2 = GetTimer();
3518 /* Playing with playback speed it's possible to get pathological
3519 * cases with mpctx->time_frame negative enough to cause an
3520 * overflow in pts_us calculation, thus the FFMAX. */
3521 double time_frame = FFMAX(mpctx->time_frame, -1);
3522 unsigned int pts_us = mpctx->last_time + time_frame * 1e6;
3523 int duration = -1;
3524 double pts2 = mpctx->video_out->next_pts2;
3525 if (pts2 != MP_NOPTS_VALUE && opts->correct_pts
3526 && !mpctx->restart_playback) {
3527 // expected A/V sync correction is ignored
3528 double diff = (pts2 - mpctx->video_pts);
3529 diff /= opts->playback_speed;
3530 if (mpctx->time_frame < 0)
3531 diff += mpctx->time_frame;
3532 if (diff < 0)
3533 diff = 0;
3534 if (diff > 10)
3535 diff = 10;
3536 duration = diff * 1e6;
3538 vo_flip_page(mpctx->video_out, pts_us | 1, duration);
3540 mpctx->last_vo_flip_duration = (GetTimer() - t2) * 0.000001;
3541 vout_time_usage += mpctx->last_vo_flip_duration;
3542 if (mpctx->video_out->driver->flip_page_timed) {
3543 // No need to adjust sync based on flip speed
3544 mpctx->last_vo_flip_duration = 0;
3545 // For print_status - VO call finishing early is OK for sync
3546 mpctx->time_frame -= get_relative_time(mpctx);
3548 if (mpctx->restart_playback) {
3549 mpctx->syncing_audio = true;
3550 if (mpctx->sh_audio && !mpctx->paused)
3551 fill_audio_out_buffers(mpctx);
3552 mpctx->restart_playback = false;
3553 mpctx->time_frame = 0;
3554 get_relative_time(mpctx);
3556 print_status(mpctx, MP_NOPTS_VALUE, true);
3557 } else
3558 print_status(mpctx, MP_NOPTS_VALUE, false);
3560 //============================ Auto QUALITY ============================
3562 /*Output quality adjustments:*/
3563 if (opts->auto_quality > 0) {
3564 current_module = "autoq";
3565 if (output_quality < opts->auto_quality && aq_sleep_time > 0)
3566 ++output_quality;
3567 else
3568 if (output_quality>1 && aq_sleep_time<0)
3569 --output_quality;
3570 else if (output_quality>0 && aq_sleep_time<-0.050f) // 50ms
3571 output_quality = 0;
3572 set_video_quality(mpctx->sh_video, output_quality);
3575 if (!frame_time_remaining && blit_frame) {
3576 if (play_n_frames >= 0) {
3577 --play_n_frames;
3578 if (play_n_frames <= 0)
3579 mpctx->stop_play = PT_NEXT_ENTRY;
3581 if (mpctx->step_frames > 0) {
3582 mpctx->step_frames--;
3583 if (mpctx->step_frames == 0)
3584 pause_player(mpctx);
3588 // FIXME: add size based support for -endpos
3589 if (end_at.type == END_AT_TIME &&
3590 !frame_time_remaining && end_at.pos <= mpctx->sh_video->pts)
3591 mpctx->stop_play = PT_NEXT_ENTRY;
3593 } // end if(mpctx->sh_video)
3595 #ifdef CONFIG_DVDNAV
3596 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
3597 nav_highlight_t hl;
3598 mp_dvdnav_get_highlight(mpctx->stream, &hl);
3599 if (!vo_spudec || !spudec_apply_palette_crop(vo_spudec, hl.palette, hl.sx, hl.sy, hl.ex, hl.ey)) {
3600 osd_set_nav_box(hl.sx, hl.sy, hl.ex, hl.ey);
3601 vo_osd_changed(OSDTYPE_DVDNAV);
3602 } else {
3603 osd_set_nav_box(0, 0, 0, 0);
3604 vo_osd_changed(OSDTYPE_DVDNAV);
3605 vo_osd_changed(OSDTYPE_SPU);
3608 if (mp_dvdnav_stream_has_changed(mpctx->stream)) {
3609 double ar = -1.0;
3610 if (mpctx->sh_video &&
3611 stream_control(mpctx->demuxer->stream,
3612 STREAM_CTRL_GET_ASPECT_RATIO, &ar)
3613 != STREAM_UNSUPPORTED)
3614 mpctx->sh_video->stream_aspect = ar;
3617 #endif
3619 //================= Keyboard events, SEEKing ====================
3621 current_module = "key_events";
3623 while (1) {
3624 mp_cmd_t *cmd;
3625 while ((cmd = mp_input_get_cmd(mpctx->input, 0, 1)) != NULL) {
3626 /* Allow running consecutive seek commands to combine them,
3627 * but execute the seek before running other commands.
3628 * If the user seeks continuously (keeps arrow key down)
3629 * try to finish showing a frame from one location before doing
3630 * another seek (which could lead to unchanging display). */
3631 if (mpctx->seek.type && cmd->id != MP_CMD_SEEK
3632 || mpctx->restart_playback && cmd->id == MP_CMD_SEEK
3633 && GetTimerMS() - mpctx->start_timestamp < 300)
3634 break;
3635 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
3636 run_command(mpctx, cmd);
3637 mp_cmd_free(cmd);
3638 if (mpctx->stop_play)
3639 break;
3641 if (!mpctx->paused || mpctx->stop_play || mpctx->seek.type
3642 || mpctx->restart_playback)
3643 break;
3644 if (mpctx->sh_video) {
3645 update_osd_msg(mpctx);
3646 int hack = vo_osd_changed(0);
3647 vo_osd_changed(hack);
3648 if (hack) {
3649 if (redraw_osd(mpctx->sh_video, mpctx->osd) < 0) {
3650 add_step_frame(mpctx);
3651 break;
3652 } else
3653 vo_osd_changed(0);
3656 pause_loop(mpctx);
3659 // handle -sstep
3660 if (step_sec > 0 && !mpctx->paused) {
3661 mpctx->osd_function = OSD_FFW;
3662 queue_seek(mpctx, MPSEEK_RELATIVE, step_sec, 0);
3665 edl_update(mpctx);
3667 /* Looping. */
3668 if (mpctx->stop_play==AT_END_OF_FILE && opts->loop_times>=0) {
3669 mp_msg(MSGT_CPLAYER, MSGL_V, "loop_times = %d\n", opts->loop_times);
3671 if (opts->loop_times>1)
3672 opts->loop_times--;
3673 else if (opts->loop_times==1)
3674 opts->loop_times = -1;
3675 play_n_frames = play_n_frames_mf;
3676 mpctx->stop_play = 0;
3677 queue_seek(mpctx, MPSEEK_ABSOLUTE, 0, 0);
3680 if (mpctx->seek.type) {
3681 seek(mpctx, mpctx->seek, false);
3682 mpctx->seek = (struct seek_params){0};
3687 static int read_keys(void *ctx, int fd)
3689 getch2(ctx);
3690 return mplayer_get_key(ctx, 0);
3693 static bool attachment_is_font(struct demux_attachment *att)
3695 if (!att->name || !att->type || !att->data || !att->data_size)
3696 return false;
3697 // match against MIME types
3698 if (strcmp(att->type, "application/x-truetype-font") == 0
3699 || strcmp(att->type, "application/x-font") == 0)
3700 return true;
3701 // fallback: match against file extension
3702 if (strlen(att->name) > 4) {
3703 char *ext = att->name + strlen(att->name) - 4;
3704 if (strcasecmp(ext, ".ttf") == 0 || strcasecmp(ext, ".ttc") == 0
3705 || strcasecmp(ext, ".otf") == 0)
3706 return true;
3708 return false;
3711 static int select_audio(demuxer_t *demuxer, int audio_id, char **audio_lang)
3713 if (audio_id == -1)
3714 audio_id = demuxer_audio_track_by_lang_and_default(demuxer, audio_lang);
3715 if (audio_id != -1) // -1 (automatic) is the default behaviour of demuxers
3716 demuxer_switch_audio(demuxer, audio_id);
3717 if (audio_id == -2) { // some demuxers don't yet know how to switch to no sound
3718 demuxer->audio->id = -2;
3719 demuxer->audio->sh = NULL;
3721 return demuxer->audio->id;
3724 static void print_version(const char* name)
3726 mp_msg(MSGT_CPLAYER, MSGL_INFO, MP_TITLE, name);
3728 /* Test for CPU capabilities (and corresponding OS support) for optimizing */
3729 GetCpuCaps(&gCpuCaps);
3730 #if ARCH_X86
3731 mp_msg(MSGT_CPLAYER, MSGL_V,
3732 "CPUflags: MMX: %d MMX2: %d 3DNow: %d 3DNowExt: %d SSE: %d SSE2: %d SSSE3: %d\n",
3733 gCpuCaps.hasMMX, gCpuCaps.hasMMX2,
3734 gCpuCaps.has3DNow, gCpuCaps.has3DNowExt,
3735 gCpuCaps.hasSSE, gCpuCaps.hasSSE2, gCpuCaps.hasSSSE3);
3736 #if CONFIG_RUNTIME_CPUDETECT
3737 mp_tmsg(MSGT_CPLAYER,MSGL_V, "Compiled with runtime CPU detection.\n");
3738 #else
3739 mp_tmsg(MSGT_CPLAYER,MSGL_V, "Compiled for x86 CPU with extensions:");
3740 if (HAVE_MMX)
3741 mp_msg(MSGT_CPLAYER,MSGL_V," MMX");
3742 if (HAVE_MMX2)
3743 mp_msg(MSGT_CPLAYER,MSGL_V," MMX2");
3744 if (HAVE_AMD3DNOW)
3745 mp_msg(MSGT_CPLAYER,MSGL_V," 3DNow");
3746 if (HAVE_AMD3DNOWEXT)
3747 mp_msg(MSGT_CPLAYER,MSGL_V," 3DNowExt");
3748 if (HAVE_SSE)
3749 mp_msg(MSGT_CPLAYER,MSGL_V," SSE");
3750 if (HAVE_SSE2)
3751 mp_msg(MSGT_CPLAYER,MSGL_V," SSE2");
3752 if (HAVE_SSSE3)
3753 mp_msg(MSGT_CPLAYER,MSGL_V," SSSE3");
3754 if (HAVE_CMOV)
3755 mp_msg(MSGT_CPLAYER,MSGL_V," CMOV");
3756 mp_msg(MSGT_CPLAYER,MSGL_V,"\n");
3757 #endif /* CONFIG_RUNTIME_CPUDETECT */
3758 #endif /* ARCH_X86 */
3761 #ifdef PTW32_STATIC_LIB
3762 static void detach_ptw32(void)
3764 pthread_win32_thread_detach_np();
3765 pthread_win32_process_detach_np();
3767 #endif
3769 /* This preprocessor directive is a hack to generate a mplayer-nomain.o object
3770 * file for some tools to link against. */
3771 #ifndef DISABLE_MAIN
3772 int main(int argc,char* argv[]){
3773 #ifdef PTW32_STATIC_LIB
3774 pthread_win32_process_attach_np();
3775 pthread_win32_thread_attach_np();
3776 atexit(detach_ptw32);
3777 #endif
3778 if (argc > 1 && !strcmp(argv[1], "-leak-report"))
3779 talloc_enable_leak_report();
3781 char * mem_ptr;
3783 // movie info:
3785 /* Flag indicating whether MPlayer should exit without playing anything. */
3786 int opt_exit = 0;
3787 int i;
3789 struct MPContext *mpctx = &(struct MPContext){
3790 .osd_function = OSD_PLAY,
3791 .begin_skip = MP_NOPTS_VALUE,
3792 .play_tree_step = 1,
3793 .global_sub_pos = -1,
3794 .set_of_sub_pos = -1,
3795 .file_format = DEMUXER_TYPE_UNKNOWN,
3796 .last_dvb_step = 1,
3799 InitTimer();
3800 srand(GetTimerMS());
3802 mp_msg_init();
3803 set_av_log_callback();
3805 #ifdef CONFIG_X11
3806 mpctx->x11_state = vo_x11_init_state();
3807 #endif
3808 struct MPOpts *opts = &mpctx->opts;
3809 set_default_mplayer_options(opts);
3810 // Create the config context and register the options
3811 mpctx->mconfig = m_config_new(opts, cfg_include);
3812 m_config_register_options(mpctx->mconfig,mplayer_opts);
3813 m_config_register_options(mpctx->mconfig, common_opts);
3814 mp_input_register_options(mpctx->mconfig);
3816 // Preparse the command line
3817 m_config_preparse_command_line(mpctx->mconfig,argc,argv);
3819 #if (defined(__MINGW32__) || defined(__CYGWIN__)) && defined(CONFIG_WIN32DLL)
3820 set_path_env();
3821 #endif
3823 #ifdef CONFIG_TV
3824 stream_tv_defaults.immediate = 1;
3825 #endif
3827 parse_cfgfiles(mpctx, mpctx->mconfig);
3829 mpctx->playtree = m_config_parse_mp_command_line(mpctx->mconfig, argc, argv);
3830 if(mpctx->playtree == NULL)
3831 opt_exit = 1;
3832 else {
3833 mpctx->playtree = play_tree_cleanup(mpctx->playtree);
3834 if(mpctx->playtree) {
3835 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,mpctx->mconfig);
3836 if(mpctx->playtree_iter) {
3837 if(play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
3838 play_tree_iter_free(mpctx->playtree_iter);
3839 mpctx->playtree_iter = NULL;
3841 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,1);
3845 mpctx->key_fifo = mp_fifo_create(opts);
3847 print_version("MPlayer2");
3849 #if defined(__MINGW32__) || defined(__CYGWIN__)
3851 HMODULE kernel32 = GetModuleHandle("Kernel32.dll");
3852 BOOL WINAPI (*setDEP)(DWORD) = NULL;
3853 BOOL WINAPI (*setDllDir)(LPCTSTR) = NULL;
3854 if (kernel32) {
3855 setDEP = GetProcAddress(kernel32, "SetProcessDEPPolicy");
3856 setDllDir = GetProcAddress(kernel32, "SetDllDirectoryA");
3858 if (setDEP) setDEP(3);
3859 if (setDllDir) setDllDir("");
3861 // stop Windows from showing all kinds of annoying error dialogs
3862 SetErrorMode(0x8003);
3863 // request 1ms timer resolution
3864 timeBeginPeriod(1);
3865 #endif
3867 #ifdef CONFIG_PRIORITY
3868 set_priority();
3869 #endif
3871 if (codec_path)
3872 set_codec_path(codec_path);
3874 if(opts->video_driver_list && strcmp(opts->video_driver_list[0],"help")==0){
3875 list_video_out();
3876 opt_exit = 1;
3879 if(opts->audio_driver_list && strcmp(opts->audio_driver_list[0],"help")==0){
3880 list_audio_out();
3881 opt_exit = 1;
3884 /* Check codecs.conf. */
3885 if(!codecs_file || !parse_codec_cfg(codecs_file)){
3886 if(!parse_codec_cfg(mem_ptr=get_path("codecs.conf"))){
3887 if(!parse_codec_cfg(MPLAYER_CONFDIR "/codecs.conf")){
3888 if(!parse_codec_cfg(NULL)){
3889 exit_player_with_rc(mpctx, EXIT_NONE, 0);
3891 mp_tmsg(MSGT_CPLAYER,MSGL_V,"Using built-in default codecs.conf.\n");
3894 free( mem_ptr ); // release the buffer created by get_path()
3897 if(audio_codec_list && strcmp(audio_codec_list[0],"help")==0){
3898 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available audio codecs:\n");
3899 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AUDIO_CODECS\n");
3900 list_codecs(1);
3901 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3902 opt_exit = 1;
3904 if(video_codec_list && strcmp(video_codec_list[0],"help")==0){
3905 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available video codecs:\n");
3906 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODECS\n");
3907 list_codecs(0);
3908 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3909 opt_exit = 1;
3911 if(video_fm_list && strcmp(video_fm_list[0],"help")==0){
3912 vfm_help();
3913 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3914 opt_exit = 1;
3916 if(audio_fm_list && strcmp(audio_fm_list[0],"help")==0){
3917 afm_help();
3918 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3919 opt_exit = 1;
3921 if(af_cfg.list && strcmp(af_cfg.list[0],"help")==0){
3922 af_help();
3923 printf("\n");
3924 opt_exit = 1;
3926 #ifdef CONFIG_X11
3927 if(vo_fstype_list && strcmp(vo_fstype_list[0],"help")==0){
3928 fstype_help();
3929 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3930 opt_exit = 1;
3932 #endif
3933 if((opts->demuxer_name && strcmp(opts->demuxer_name,"help")==0) ||
3934 (opts->audio_demuxer_name && strcmp(opts->audio_demuxer_name,"help")==0) ||
3935 (opts->sub_demuxer_name && strcmp(opts->sub_demuxer_name,"help")==0)){
3936 demuxer_help();
3937 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
3938 opt_exit = 1;
3940 if (opts->list_properties) {
3941 property_print_help();
3942 opt_exit = 1;
3945 if(opt_exit)
3946 exit_player(mpctx, EXIT_NONE);
3948 if (!mpctx->filename && !opts->player_idle_mode) {
3949 // no file/vcd/dvd -> show HELP:
3950 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", mp_gtext(help_text));
3951 exit_player_with_rc(mpctx, EXIT_NONE, 0);
3954 /* Display what configure line was used */
3955 mp_msg(MSGT_CPLAYER, MSGL_V, "Configuration: " CONFIGURATION "\n");
3957 // Many users forget to include command line in bugreports...
3958 if( mp_msg_test(MSGT_CPLAYER,MSGL_V) ){
3959 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "CommandLine:");
3960 for(i=1;i<argc;i++)mp_msg(MSGT_CPLAYER, MSGL_INFO," '%s'",argv[i]);
3961 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
3964 //------ load global data first ------
3966 mpctx->osd = osd_create();
3968 // check font
3969 #ifdef CONFIG_FREETYPE
3970 init_freetype();
3971 #endif
3972 #ifdef CONFIG_FONTCONFIG
3973 if(font_fontconfig <= 0)
3975 #endif
3976 #ifdef CONFIG_BITMAP_FONT
3977 if(font_name){
3978 vo_font=read_font_desc(font_name,font_factor,verbose>1);
3979 if(!vo_font) mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load bitmap font: %s\n",
3980 filename_recode(font_name));
3981 } else {
3982 // try default:
3983 vo_font=read_font_desc( mem_ptr=get_path("font/font.desc"),font_factor,verbose>1);
3984 free(mem_ptr); // release the buffer created by get_path()
3985 if(!vo_font)
3986 vo_font=read_font_desc(MPLAYER_DATADIR "/font/font.desc",font_factor,verbose>1);
3988 if (sub_font_name)
3989 mpctx->osd->sub_font = read_font_desc(sub_font_name, font_factor, verbose>1);
3990 else
3991 mpctx->osd->sub_font = vo_font;
3992 #endif
3993 #ifdef CONFIG_FONTCONFIG
3995 #endif
3997 #ifdef CONFIG_ASS
3998 ass_library = mp_ass_init();
3999 #endif
4001 #ifdef HAVE_RTC
4002 if(opts->rtc)
4004 char *rtc_device = opts->rtc_device;
4005 // seteuid(0); /* Can't hurt to try to get root here */
4006 if ((rtc_fd = open(rtc_device ? rtc_device : "/dev/rtc", O_RDONLY)) < 0)
4007 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Failed to open %s: %s (it should be readable by the user.)\n",
4008 rtc_device ? rtc_device : "/dev/rtc", strerror(errno));
4009 else {
4010 unsigned long irqp = 1024; /* 512 seemed OK. 128 is jerky. */
4012 if (ioctl(rtc_fd, RTC_IRQP_SET, irqp) < 0) {
4013 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Linux RTC init error in ioctl (rtc_irqp_set %lu): %s\n", irqp, strerror(errno));
4014 mp_tmsg(MSGT_CPLAYER, MSGL_HINT, "Try adding \"echo %lu > /proc/sys/dev/rtc/max-user-freq\" to your system startup scripts.\n", irqp);
4015 close (rtc_fd);
4016 rtc_fd = -1;
4017 } else if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
4018 /* variable only by the root */
4019 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC init error in ioctl (rtc_pie_on): %s\n", strerror(errno));
4020 close (rtc_fd);
4021 rtc_fd = -1;
4022 } else
4023 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Using Linux hardware RTC timing (%ldHz).\n", irqp);
4026 if(rtc_fd<0)
4027 #endif /* HAVE_RTC */
4028 mp_msg(MSGT_CPLAYER, MSGL_V, "Using %s timing\n",
4029 opts->softsleep ? "software" : timer_name);
4031 #ifdef HAVE_TERMCAP
4032 load_termcap(NULL); // load key-codes
4033 #endif
4035 // ========== Init keyboard FIFO (connection to libvo) ============
4037 // Init input system
4038 current_module = "init_input";
4039 mpctx->input = mp_input_init(&opts->input);
4040 mp_input_add_key_fd(mpctx->input, -1,0,mplayer_get_key,NULL, mpctx->key_fifo);
4041 if(slave_mode) {
4042 #if USE_FD0_CMD_SELECT
4043 int flags = fcntl(0, F_GETFL);
4044 if (flags != -1)
4045 fcntl(0, F_SETFL, flags | O_NONBLOCK);
4046 #endif
4047 mp_input_add_cmd_fd(mpctx->input, 0,USE_FD0_CMD_SELECT,MP_INPUT_SLAVE_CMD_FUNC,NULL);
4049 else if (opts->consolecontrols)
4050 mp_input_add_key_fd(mpctx->input, 0, 1, read_keys, NULL, mpctx->key_fifo);
4051 // Set the libstream interrupt callback
4052 stream_set_interrupt_callback(mp_input_check_interrupt, mpctx->input);
4054 #ifdef CONFIG_MENU
4055 if(use_menu) {
4056 if(menu_cfg && menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
4057 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
4058 else {
4059 menu_cfg = get_path("menu.conf");
4060 if(menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
4061 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
4062 else {
4063 if(menu_init(mpctx, mpctx->mconfig, mpctx->input,
4064 MPLAYER_CONFDIR "/menu.conf"))
4065 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", MPLAYER_CONFDIR"/menu.conf");
4066 else {
4067 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Menu init failed.\n");
4068 use_menu = 0;
4073 #endif
4075 current_module = NULL;
4077 /// Catch signals
4078 #ifndef __MINGW32__
4079 signal(SIGCHLD,child_sighandler);
4080 #endif
4082 #ifdef CONFIG_CRASH_DEBUG
4083 prog_path = argv[0];
4084 #endif
4085 //========= Catch terminate signals: ================
4086 // terminate requests:
4087 signal(SIGTERM,exit_sighandler); // kill
4088 signal(SIGHUP,exit_sighandler); // kill -HUP / xterm closed
4090 signal(SIGINT,exit_sighandler); // Interrupt from keyboard
4092 signal(SIGQUIT,exit_sighandler); // Quit from keyboard
4093 signal(SIGPIPE,exit_sighandler); // Some window managers cause this
4094 #ifdef CONFIG_SIGHANDLER
4095 // fatal errors:
4096 signal(SIGBUS,exit_sighandler); // bus error
4097 signal(SIGSEGV,exit_sighandler); // segfault
4098 signal(SIGILL,exit_sighandler); // illegal instruction
4099 signal(SIGFPE,exit_sighandler); // floating point exc.
4100 signal(SIGABRT,exit_sighandler); // abort()
4101 #ifdef CONFIG_CRASH_DEBUG
4102 if (crash_debug)
4103 signal(SIGTRAP,exit_sighandler);
4104 #endif
4105 #endif
4107 // ******************* Now, let's see the per-file stuff ********************
4109 play_next_file:
4111 // init global sub numbers
4112 mpctx->global_sub_size = 0;
4113 memset(mpctx->sub_counts, 0, sizeof(mpctx->sub_counts));
4115 if (mpctx->filename) {
4116 load_per_protocol_config (mpctx->mconfig, mpctx->filename);
4117 load_per_extension_config (mpctx->mconfig, mpctx->filename);
4118 load_per_file_config (mpctx->mconfig, mpctx->filename);
4121 if (opts->video_driver_list)
4122 load_per_output_config (mpctx->mconfig, PROFILE_CFG_VO, opts->video_driver_list[0]);
4123 if (opts->audio_driver_list)
4124 load_per_output_config (mpctx->mconfig, PROFILE_CFG_AO, opts->audio_driver_list[0]);
4126 // We must enable getch2 here to be able to interrupt network connection
4127 // or cache filling
4128 if (opts->consolecontrols && !slave_mode) {
4129 if(mpctx->initialized_flags&INITIALIZED_GETCH2)
4130 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"WARNING: getch2_init called twice!\n");
4131 else
4132 getch2_enable(); // prepare stdin for hotkeys...
4133 mpctx->initialized_flags|=INITIALIZED_GETCH2;
4134 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[init getch2]]]\n");
4137 // =================== GUI idle loop (STOP state) ===========================
4138 while (opts->player_idle_mode && !mpctx->filename) {
4139 play_tree_t * entry = NULL;
4140 mp_cmd_t * cmd;
4141 if (mpctx->video_out && mpctx->video_out->config_ok)
4142 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
4143 while (!(cmd = mp_input_get_cmd(mpctx->input, 0, 0))) { // wait for command
4144 if (mpctx->video_out)
4145 vo_check_events(mpctx->video_out);
4146 usec_sleep(20000);
4148 switch (cmd->id) {
4149 case MP_CMD_LOADFILE:
4150 // prepare a tree entry with the new filename
4151 entry = play_tree_new();
4152 play_tree_add_file(entry, cmd->args[0].v.s);
4153 // The entry is added to the main playtree after the switch().
4154 break;
4155 case MP_CMD_LOADLIST:
4156 entry = parse_playlist_file(mpctx->mconfig, cmd->args[0].v.s);
4157 break;
4158 case MP_CMD_QUIT:
4159 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
4160 break;
4161 case MP_CMD_VO_FULLSCREEN:
4162 case MP_CMD_GET_PROPERTY:
4163 case MP_CMD_SET_PROPERTY:
4164 case MP_CMD_STEP_PROPERTY:
4165 run_command(mpctx, cmd);
4166 break;
4169 mp_cmd_free(cmd);
4171 if (entry) { // user entered a command that gave a valid entry
4172 if (mpctx->playtree) // the playtree is always a node with one child. let's clear it
4173 play_tree_free_list(mpctx->playtree->child, 1);
4174 else mpctx->playtree=play_tree_new(); // .. or make a brand new playtree
4176 if (!mpctx->playtree) continue; // couldn't make playtree! wait for next command
4178 play_tree_set_child(mpctx->playtree, entry);
4180 /* Make iterator start at the top the of tree. */
4181 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree, mpctx->mconfig);
4182 if (!mpctx->playtree_iter) continue;
4184 // find the first real item in the tree
4185 if (play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
4186 // no items!
4187 play_tree_iter_free(mpctx->playtree_iter);
4188 mpctx->playtree_iter = NULL;
4189 continue; // wait for next command
4191 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, 1);
4194 //---------------------------------------------------------------------------
4196 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
4197 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL);
4199 if (mpctx->filename) {
4200 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nPlaying %s.\n",
4201 filename_recode(mpctx->filename));
4202 if(use_filename_title && opts->vo_wintitle == NULL)
4203 opts->vo_wintitle = strdup(mp_basename(mpctx->filename));
4206 if (edl_filename) {
4207 if (edl_records) free_edl(edl_records);
4208 next_edl_record = edl_records = edl_parse_file();
4210 if (edl_output_filename) {
4211 if (edl_fd) fclose(edl_fd);
4212 if ((edl_fd = fopen(edl_output_filename, "w")) == NULL)
4214 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Can't open EDL file [%s] for writing.\n",
4215 filename_recode(edl_output_filename));
4219 //==================== Open VOB-Sub ============================
4221 current_module="vobsub";
4222 if (opts->vobsub_name){
4223 vo_vobsub=vobsub_open(opts->vobsub_name,spudec_ifo,1,&vo_spudec);
4224 if(vo_vobsub==NULL)
4225 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load subtitles: %s\n",
4226 filename_recode(opts->vobsub_name));
4227 } else if (opts->sub_auto && mpctx->filename){
4228 char **vob = find_vob_subtitles(opts, mpctx->filename);
4229 for (int i = 0; i < MP_TALLOC_ELEMS(vob); i++) {
4230 vo_vobsub = vobsub_open(vob[i], spudec_ifo, 0, &vo_spudec);
4231 if (vo_vobsub)
4232 break;
4234 talloc_free(vob);
4236 if(vo_vobsub){
4237 mpctx->initialized_flags|=INITIALIZED_VOBSUB;
4238 vobsub_set_from_lang(vo_vobsub, opts->sub_lang);
4239 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
4241 // setup global sub numbering
4242 mpctx->sub_counts[SUB_SOURCE_VOBSUB] = vobsub_get_indexes_count(vo_vobsub);
4245 //============ Open & Sync STREAM --- fork cache2 ====================
4247 mpctx->stream=NULL;
4248 mpctx->demuxer=NULL;
4249 mpctx->d_audio=NULL;
4250 mpctx->d_video=NULL;
4251 mpctx->d_sub = NULL;
4252 mpctx->sh_audio=NULL;
4253 mpctx->sh_video=NULL;
4255 current_module="open_stream";
4256 mpctx->stream = open_stream(mpctx->filename, opts, &mpctx->file_format);
4257 if(!mpctx->stream) { // error...
4258 mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY);
4259 goto goto_next_file;
4261 mpctx->initialized_flags|=INITIALIZED_STREAM;
4263 if(mpctx->file_format == DEMUXER_TYPE_PLAYLIST) {
4264 mp_msg(MSGT_CPLAYER, MSGL_ERR, "\nThis looks like a playlist, but "
4265 "playlist support will not be used automatically.\n"
4266 "MPlayer's playlist code is unsafe and should only be used with "
4267 "trusted sources.\nPlayback will probably fail.\n\n");
4268 #if 0
4269 play_tree_t* entry;
4270 // Handle playlist
4271 current_module="handle_playlist";
4272 mp_msg(MSGT_CPLAYER,MSGL_V,"Parsing playlist %s...\n",
4273 filename_recode(mpctx->filename));
4274 entry = parse_playtree(mpctx->stream, mpctx->mconfig, 0);
4275 mpctx->eof=playtree_add_playlist(mpctx, entry);
4276 goto goto_next_file;
4277 #endif
4279 mpctx->stream->start_pos+=seek_to_byte;
4281 if(stream_dump_type==5){
4282 unsigned char buf[4096];
4283 int len;
4284 FILE *f;
4285 current_module="dumpstream";
4286 stream_reset(mpctx->stream);
4287 stream_seek(mpctx->stream,mpctx->stream->start_pos);
4288 f=fopen(opts->stream_dump_name,"wb");
4289 if(!f){
4290 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
4291 exit_player(mpctx, EXIT_ERROR);
4293 if (opts->chapterrange[0] > 1) {
4294 int chapter = opts->chapterrange[0] - 1;
4295 stream_control(mpctx->stream, STREAM_CTRL_SEEK_TO_CHAPTER, &chapter);
4297 while(!mpctx->stream->eof && !async_quit_request){
4298 len=stream_read(mpctx->stream,buf,4096);
4299 if(len>0) {
4300 if(fwrite(buf,len,1,f) != 1) {
4301 mp_tmsg(MSGT_GLOBAL,MSGL_FATAL,"%s: Error writing file.\n",opts->stream_dump_name);
4302 exit_player(mpctx, EXIT_ERROR);
4305 if (opts->chapterrange[1] > 0) {
4306 int chapter = -1;
4307 if (stream_control(mpctx->stream, STREAM_CTRL_GET_CURRENT_CHAPTER,
4308 &chapter) == STREAM_OK
4309 && chapter + 1 > opts->chapterrange[1])
4310 break;
4313 if(fclose(f)) {
4314 mp_tmsg(MSGT_GLOBAL,MSGL_FATAL,"%s: Error writing file.\n",opts->stream_dump_name);
4315 exit_player(mpctx, EXIT_ERROR);
4317 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Stream dump complete.\n");
4318 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4321 #ifdef CONFIG_DVDREAD
4322 if(mpctx->stream->type==STREAMTYPE_DVD){
4323 current_module="dvd lang->id";
4324 if(opts->audio_lang && opts->audio_id==-1) opts->audio_id=dvd_aid_from_lang(mpctx->stream,opts->audio_lang);
4325 if(opts->sub_lang && opts->sub_id==-1) opts->sub_id=dvd_sid_from_lang(mpctx->stream,opts->sub_lang);
4326 // setup global sub numbering
4327 mpctx->sub_counts[SUB_SOURCE_DEMUX] = dvd_number_of_subs(mpctx->stream);
4328 current_module=NULL;
4330 #endif
4332 #ifdef CONFIG_DVDNAV
4333 if(mpctx->stream->type==STREAMTYPE_DVDNAV){
4334 current_module="dvdnav lang->id";
4335 if(opts->audio_lang && opts->audio_id==-1) opts->audio_id=mp_dvdnav_aid_from_lang(mpctx->stream,opts->audio_lang);
4336 dvdsub_lang_id = -3;
4337 if(opts->sub_lang && opts->sub_id==-1)
4338 dvdsub_lang_id = opts->sub_id = mp_dvdnav_sid_from_lang(mpctx->stream,opts->sub_lang);
4339 // setup global sub numbering
4340 mpctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(mpctx->stream);
4341 current_module=NULL;
4343 #endif
4345 // CACHE2: initial prefill: 20% later: 5% (should be set by -cacheopts)
4346 goto_enable_cache:
4347 if(stream_cache_size>0){
4348 int res;
4349 float stream_cache_min_percent = opts->stream_cache_min_percent;
4350 float stream_cache_seek_min_percent = opts->stream_cache_seek_min_percent;
4351 current_module="enable_cache";
4352 res = stream_enable_cache(mpctx->stream,stream_cache_size*1024,
4353 stream_cache_size*1024*(stream_cache_min_percent / 100.0),
4354 stream_cache_size*1024*(stream_cache_seek_min_percent / 100.0));
4355 if(res == 0)
4356 if((mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY))) goto goto_next_file;
4359 //============ Open DEMUXERS --- DETECT file type =======================
4360 current_module="demux_open";
4362 mpctx->demuxer=demux_open(opts, mpctx->stream,mpctx->file_format,opts->audio_id,opts->video_id,opts->sub_id,mpctx->filename);
4364 // HACK to get MOV Reference Files working
4366 if (mpctx->demuxer && mpctx->demuxer->type==DEMUXER_TYPE_PLAYLIST)
4368 unsigned char* playlist_entry;
4369 play_tree_t *list = NULL, *entry = NULL;
4371 current_module="handle_demux_playlist";
4372 while (ds_get_packet(mpctx->demuxer->video,&playlist_entry)>0)
4374 char *temp;
4375 const char *bname;
4377 mp_msg(MSGT_CPLAYER,MSGL_V,"Adding file %s to element entry.\n",
4378 filename_recode(playlist_entry));
4380 bname=mp_basename(playlist_entry);
4381 if ((strlen(bname)>10) && !strncmp(bname,"qt",2) && !strncmp(bname+3,"gateQT",6))
4382 continue;
4384 if (!strcmp(playlist_entry, mpctx->filename)) // ignoring self-reference
4385 continue;
4387 entry = play_tree_new();
4389 if (mpctx->filename && !strcmp(mp_basename(playlist_entry),playlist_entry)) // add reference path of current file
4391 temp=malloc((strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))+strlen(playlist_entry)+1));
4392 if (temp)
4394 strncpy(temp, mpctx->filename, strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename)));
4395 temp[strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))]='\0';
4396 strcat(temp, playlist_entry);
4397 if (!strcmp(temp, mpctx->filename)) {
4398 free(temp);
4399 continue;
4401 play_tree_add_file(entry,temp);
4402 mp_msg(MSGT_CPLAYER,MSGL_V,"Resolving reference to %s.\n",temp);
4403 free(temp);
4406 else
4407 play_tree_add_file(entry,playlist_entry);
4409 if(!list)
4410 list = entry;
4411 else
4412 play_tree_append_entry(list,entry);
4414 free_demuxer(mpctx->demuxer);
4415 mpctx->demuxer = NULL;
4417 if (list)
4419 entry = play_tree_new();
4420 play_tree_set_child(entry,list);
4421 mpctx->stop_play = playtree_add_playlist(mpctx, entry);
4422 goto goto_next_file;
4426 if(!mpctx->demuxer) {
4427 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Failed to recognize file format.\n");
4428 goto goto_next_file;
4431 if (mpctx->demuxer->matroska_data.ordered_chapters)
4432 build_ordered_chapter_timeline(mpctx);
4434 if (mpctx->demuxer->type == DEMUXER_TYPE_EDL)
4435 build_edl_timeline(mpctx);
4437 if (mpctx->timeline) {
4438 mpctx->timeline_part = 0;
4439 mpctx->demuxer = mpctx->timeline[0].source->demuxer;
4441 int part_count = mpctx->num_timeline_parts;
4442 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline contains %d parts from %d "
4443 "sources. Total length %.3f seconds.\n", part_count,
4444 mpctx->num_sources, mpctx->timeline[part_count].start);
4445 mp_msg(MSGT_CPLAYER, MSGL_V, "Source files:\n");
4446 for (int i = 0; i < mpctx->num_sources; i++)
4447 mp_msg(MSGT_CPLAYER, MSGL_V, "%d: %s\n", i,
4448 filename_recode(mpctx->sources[i].demuxer->filename));
4449 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline parts: (number, start, "
4450 "source_start, source):\n");
4451 for (int i = 0; i < part_count; i++) {
4452 struct timeline_part *p = mpctx->timeline + i;
4453 mp_msg(MSGT_CPLAYER, MSGL_V, "%3d %9.3f %9.3f %3td\n", i, p->start,
4454 p->source_start, p->source - mpctx->sources);
4456 mp_msg(MSGT_CPLAYER, MSGL_V, "END %9.3f\n",
4457 mpctx->timeline[part_count].start);
4460 if (!mpctx->sources) {
4461 mpctx->sources = talloc_ptrtype(NULL, mpctx->sources);
4462 *mpctx->sources = (struct content_source){.stream = mpctx->stream,
4463 .demuxer = mpctx->demuxer};
4464 mpctx->num_sources = 1;
4467 mpctx->initialized_flags|=INITIALIZED_DEMUXER;
4469 #ifdef CONFIG_ASS
4470 if (opts->ass_enabled && ass_library) {
4471 for (int j = 0; j < mpctx->num_sources; j++) {
4472 struct demuxer *d = mpctx->sources[j].demuxer;
4473 for (int i = 0; i < d->num_attachments; i++) {
4474 struct demux_attachment *att = d->attachments + i;
4475 if (use_embedded_fonts && attachment_is_font(att))
4476 ass_add_font(ass_library, att->name, att->data, att->data_size);
4480 #endif
4482 current_module="demux_open2";
4484 mpctx->d_audio=mpctx->demuxer->audio;
4485 mpctx->d_video=mpctx->demuxer->video;
4486 mpctx->d_sub=mpctx->demuxer->sub;
4488 if (ts_prog) {
4489 int tmp = ts_prog;
4490 mp_property_do("switch_program", M_PROPERTY_SET, &tmp, mpctx);
4492 // select audio stream
4493 for (int i = 0; i < mpctx->num_sources; i++)
4494 select_audio(mpctx->sources[i].demuxer->audio->demuxer, opts->audio_id,
4495 opts->audio_lang);
4497 // DUMP STREAMS:
4498 if((stream_dump_type)&&(stream_dump_type<4)){
4499 FILE *f;
4500 demux_stream_t *ds=NULL;
4501 current_module="dump";
4502 // select stream to dump
4503 switch(stream_dump_type){
4504 case 1: ds=mpctx->d_audio;break;
4505 case 2: ds=mpctx->d_video;break;
4506 case 3: ds=mpctx->d_sub;break;
4508 if(!ds){
4509 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"dump: FATAL: Selected stream missing!\n");
4510 exit_player(mpctx, EXIT_ERROR);
4512 // disable other streams:
4513 if(mpctx->d_audio && mpctx->d_audio!=ds) {ds_free_packs(mpctx->d_audio); mpctx->d_audio->id=-2; }
4514 if(mpctx->d_video && mpctx->d_video!=ds) {ds_free_packs(mpctx->d_video); mpctx->d_video->id=-2; }
4515 if(mpctx->d_sub && mpctx->d_sub!=ds) {ds_free_packs(mpctx->d_sub); mpctx->d_sub->id=-2; }
4516 // let's dump it!
4517 f=fopen(opts->stream_dump_name,"wb");
4518 if(!f){
4519 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
4520 exit_player(mpctx, EXIT_ERROR);
4522 while(!ds->eof){
4523 unsigned char* start;
4524 int in_size=ds_get_packet(ds,&start);
4525 if( (mpctx->demuxer->file_format==DEMUXER_TYPE_AVI || mpctx->demuxer->file_format==DEMUXER_TYPE_ASF || mpctx->demuxer->file_format==DEMUXER_TYPE_MOV)
4526 && stream_dump_type==2) fwrite(&in_size,1,4,f);
4527 if(in_size>0) fwrite(start,in_size,1,f);
4528 if (opts->chapterrange[1] > 0) {
4529 int cur_chapter = demuxer_get_current_chapter(mpctx->demuxer, 0);
4530 if(cur_chapter!=-1 && cur_chapter+1 > opts->chapterrange[1])
4531 break;
4534 fclose(f);
4535 mp_tmsg(MSGT_CPLAYER ,MSGL_INFO, "Stream dump complete.\n");
4536 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4539 mpctx->sh_audio=mpctx->d_audio->sh;
4540 mpctx->sh_video=mpctx->d_video->sh;
4542 if(mpctx->sh_video){
4544 current_module="video_read_properties";
4545 if(!video_read_properties(mpctx->sh_video)) {
4546 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Video: Cannot read properties.\n");
4547 mpctx->sh_video=mpctx->d_video->sh=NULL;
4548 } else {
4549 mp_tmsg(MSGT_CPLAYER,MSGL_V,"[V] filefmt:%d fourcc:0x%X size:%dx%d fps:%5.3f ftime:=%6.4f\n",
4550 mpctx->demuxer->file_format,mpctx->sh_video->format, mpctx->sh_video->disp_w,mpctx->sh_video->disp_h,
4551 mpctx->sh_video->fps,mpctx->sh_video->frametime
4554 /* need to set fps here for output encoders to pick it up in their init */
4555 if(force_fps){
4556 mpctx->sh_video->fps=force_fps;
4557 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
4559 vo_fps = mpctx->sh_video->fps;
4561 if(!mpctx->sh_video->fps && !force_fps){
4562 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"FPS not specified in the header or invalid, use the -fps option.\n");
4563 mpctx->opts.correct_pts = 1;
4569 if(!mpctx->sh_video && !mpctx->sh_audio){
4570 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL, "No stream found.\n");
4571 #ifdef CONFIG_DVBIN
4572 if(mpctx->stream->type == STREAMTYPE_DVB)
4574 int dir;
4575 int v = mpctx->last_dvb_step;
4576 if(v > 0)
4577 dir = DVB_CHANNEL_HIGHER;
4578 else
4579 dir = DVB_CHANNEL_LOWER;
4581 if(dvb_step_channel(mpctx->stream, dir)) {
4582 mpctx->stop_play = PT_NEXT_ENTRY;
4583 mpctx->dvbin_reopen = 1;
4586 #endif
4587 goto goto_next_file; // exit_player(_("Fatal error"));
4590 /* display clip info */
4591 demux_info_print(mpctx->demuxer);
4593 //================== Read SUBTITLES (DVD & TEXT) ==========================
4594 if(vo_spudec==NULL &&
4595 (mpctx->stream->type==STREAMTYPE_DVD || mpctx->stream->type == STREAMTYPE_DVDNAV)){
4596 init_vo_spudec(mpctx);
4599 // after reading video params we should load subtitles because
4600 // we know fps so now we can adjust subtitle time to ~6 seconds AST
4601 // check .sub
4602 current_module="read_subtitles_file";
4603 double sub_fps = mpctx->sh_video ? mpctx->sh_video->fps : 25;
4604 if(opts->sub_name){
4605 for (i = 0; opts->sub_name[i] != NULL; ++i)
4606 add_subtitles(mpctx, opts->sub_name[i], sub_fps, 0);
4608 if(opts->sub_auto) { // auto load sub file ...
4609 char **tmp = find_text_subtitles(opts, mpctx->filename);
4610 int nsub = MP_TALLOC_ELEMS(tmp);
4611 for (int i = 0; i < nsub; i++)
4612 add_subtitles(mpctx, tmp[i], sub_fps, 1);
4613 talloc_free(tmp);
4615 if (mpctx->set_of_sub_size > 0)
4616 mpctx->sub_counts[SUB_SOURCE_SUBS] = mpctx->set_of_sub_size;
4618 if (select_subtitle(mpctx)) {
4619 if(mpctx->subdata)
4620 switch (stream_dump_type) {
4621 case 3: list_sub_file(mpctx->subdata); break;
4622 case 4: dump_mpsub(mpctx->subdata, mpctx->sh_video->fps); break;
4623 case 6: dump_srt(mpctx->subdata, mpctx->sh_video->fps); break;
4624 case 7: dump_microdvd(mpctx->subdata, mpctx->sh_video->fps); break;
4625 case 8: dump_jacosub(mpctx->subdata, mpctx->sh_video->fps); break;
4626 case 9: dump_sami(mpctx->subdata, mpctx->sh_video->fps); break;
4630 print_file_properties(mpctx, mpctx->filename);
4632 reinit_video_chain(mpctx);
4633 if (mpctx->sh_video) {
4634 if(mpctx->sh_video->output_flags & VFCAP_SPU && vo_spudec)
4635 spudec_set_hw_spu(vo_spudec,mpctx->video_out);
4636 #ifdef CONFIG_FREETYPE
4637 force_load_font = 1;
4638 #endif
4639 } else if (!mpctx->sh_audio)
4640 goto goto_next_file;
4642 //================== MAIN: ==========================
4643 current_module="main";
4645 if (opts->playing_msg) {
4646 char* msg = property_expand_string(mpctx, opts->playing_msg);
4647 mp_msg(MSGT_CPLAYER,MSGL_INFO,"%s",msg);
4648 free(msg);
4652 // Disable the term OSD in verbose mode
4653 if (verbose)
4654 opts->term_osd = 0;
4658 // Make sure old OSD does not stay around,
4659 // e.g. with -fixed-vo and same-resolution files
4660 clear_osd_msgs();
4661 update_osd_msg(mpctx);
4663 //================ SETUP AUDIO ==========================
4665 if(mpctx->sh_audio){
4666 reinit_audio_chain(mpctx);
4667 if (mpctx->sh_audio && mpctx->sh_audio->codec)
4668 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_CODEC=%s\n", mpctx->sh_audio->codec->name);
4671 current_module="av_init";
4673 if(mpctx->sh_video){
4674 mpctx->sh_video->timer=0;
4675 if (! ignore_start)
4676 audio_delay += mpctx->sh_video->stream_delay;
4678 if(mpctx->sh_audio){
4679 if (start_volume >= 0)
4680 mixer_setvolume(&mpctx->mixer, start_volume, start_volume);
4681 if (! ignore_start)
4682 audio_delay -= mpctx->sh_audio->stream_delay;
4683 mpctx->delay=-audio_delay;
4686 if(!mpctx->sh_audio){
4687 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Audio: no sound\n");
4688 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused audio chunks.\n",mpctx->d_audio->packs);
4689 ds_free_packs(mpctx->d_audio); // free buffered chunks
4690 //mpctx->d_audio->id=-2; // do not read audio chunks
4691 //uninit_player(mpctx, INITIALIZED_AO); // close device
4693 if(!mpctx->sh_video){
4694 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Video: no video\n");
4695 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused video chunks.\n",mpctx->d_video->packs);
4696 ds_free_packs(mpctx->d_video);
4697 mpctx->d_video->id=-2;
4698 //if(!fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
4701 if (!mpctx->sh_video && !mpctx->sh_audio)
4702 goto goto_next_file;
4704 //if(demuxer->file_format!=DEMUXER_TYPE_AVI) pts_from_bps=0; // it must be 0 for mpeg/asf!
4705 if(force_fps && mpctx->sh_video){
4706 vo_fps = mpctx->sh_video->fps=force_fps;
4707 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
4708 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"FPS forced to be %5.3f (ftime: %5.3f).\n",mpctx->sh_video->fps,mpctx->sh_video->frametime);
4711 mp_input_set_section(mpctx->input, NULL);
4712 //TODO: add desired (stream-based) sections here
4713 if (mpctx->stream->type==STREAMTYPE_TV) mp_input_set_section(mpctx->input, "tv");
4714 if (mpctx->stream->type==STREAMTYPE_DVDNAV) mp_input_set_section(mpctx->input, "dvdnav");
4716 //==================== START PLAYING =======================
4718 if(opts->loop_times>1) opts->loop_times--; else
4719 if(opts->loop_times==1) opts->loop_times = -1;
4721 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Starting playback...\n");
4723 total_time_usage_start=GetTimer();
4724 audio_time_usage=0; video_time_usage=0; vout_time_usage=0;
4725 total_frame_cnt=0; drop_frame_cnt=0; // fix for multifile fps benchmark
4726 play_n_frames=play_n_frames_mf;
4728 if(play_n_frames==0){
4729 mpctx->stop_play=PT_NEXT_ENTRY; goto goto_next_file;
4732 mpctx->time_frame = 0;
4733 mpctx->drop_message_shown = 0;
4734 mpctx->restart_playback = true;
4735 mpctx->video_pts = 0;
4736 mpctx->hrseek_active = false;
4737 mpctx->hrseek_framedrop = false;
4738 mpctx->step_frames = 0;
4739 mpctx->total_avsync_change = 0;
4740 mpctx->last_chapter_seek = -1;
4742 // If there's a timeline force an absolute seek to initialize state
4743 if (seek_to_sec || mpctx->timeline) {
4744 queue_seek(mpctx, MPSEEK_ABSOLUTE, seek_to_sec, 0);
4745 seek(mpctx, mpctx->seek, false);
4746 end_at.pos += seek_to_sec;
4748 if (opts->chapterrange[0] > 0) {
4749 double pts;
4750 if (seek_chapter(mpctx, opts->chapterrange[0]-1, &pts, NULL) >= 0
4751 && pts > -1.0) {
4752 queue_seek(mpctx, MPSEEK_ABSOLUTE, pts, 0);
4753 seek(mpctx, mpctx->seek, false);
4757 if (end_at.type == END_AT_SIZE) {
4758 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Option -endpos in MPlayer does not yet support size units.\n");
4759 end_at.type = END_AT_NONE;
4762 #ifdef CONFIG_DVDNAV
4763 mp_dvdnav_context_free(mpctx);
4764 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4765 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
4766 mp_dvdnav_cell_has_changed(mpctx->stream,1);
4768 #endif
4770 mpctx->seek = (struct seek_params){0};
4771 get_relative_time(mpctx); // reset current delta
4772 // Make sure VO knows current pause state
4773 if (mpctx->sh_video)
4774 vo_control(mpctx->video_out, mpctx->paused ? VOCTRL_PAUSE : VOCTRL_RESUME,
4775 NULL);
4777 while (!mpctx->stop_play)
4778 run_playloop(mpctx);
4780 mp_msg(MSGT_GLOBAL,MSGL_V,"EOF code: %d \n",mpctx->stop_play);
4782 #ifdef CONFIG_DVBIN
4783 if(mpctx->dvbin_reopen)
4785 mpctx->stop_play = 0;
4786 uninit_player(mpctx, INITIALIZED_ALL-(INITIALIZED_STREAM|INITIALIZED_GETCH2|(opts->fixed_vo?INITIALIZED_VO:0)));
4787 cache_uninit(mpctx->stream);
4788 mpctx->dvbin_reopen = 0;
4789 goto goto_enable_cache;
4791 #endif
4794 goto_next_file: // don't jump here after ao/vo/getch initialization!
4796 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\n");
4798 if (opts->benchmark) {
4799 double tot=video_time_usage+vout_time_usage+audio_time_usage;
4800 double total_time_usage;
4801 total_time_usage_start=GetTimer()-total_time_usage_start;
4802 total_time_usage = (float)total_time_usage_start*0.000001;
4803 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\nBENCHMARKs: VC:%8.3fs VO:%8.3fs A:%8.3fs Sys:%8.3fs = %8.3fs\n",
4804 video_time_usage,vout_time_usage,audio_time_usage,
4805 total_time_usage-tot,total_time_usage);
4806 if(total_time_usage>0.0)
4807 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARK%%: VC:%8.4f%% VO:%8.4f%% A:%8.4f%% Sys:%8.4f%% = %8.4f%%\n",
4808 100.0*video_time_usage/total_time_usage,
4809 100.0*vout_time_usage/total_time_usage,
4810 100.0*audio_time_usage/total_time_usage,
4811 100.0*(total_time_usage-tot)/total_time_usage,
4812 100.0);
4813 if(total_frame_cnt && frame_dropping)
4814 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARKn: disp: %d (%3.2f fps) drop: %d (%d%%) total: %d (%3.2f fps)\n",
4815 total_frame_cnt-drop_frame_cnt,
4816 (total_time_usage>0.5)?((total_frame_cnt-drop_frame_cnt)/total_time_usage):0,
4817 drop_frame_cnt,
4818 100*drop_frame_cnt/total_frame_cnt,
4819 total_frame_cnt,
4820 (total_time_usage>0.5)?(total_frame_cnt/total_time_usage):0);
4823 // time to uninit all, except global stuff:
4824 int uninitialize_parts = INITIALIZED_ALL;
4825 if (opts->fixed_vo)
4826 uninitialize_parts -= INITIALIZED_VO;
4827 if (opts->gapless_audio && mpctx->stop_play == AT_END_OF_FILE)
4828 uninitialize_parts -= INITIALIZED_AO;
4829 uninit_player(mpctx, uninitialize_parts);
4831 if(mpctx->set_of_sub_size > 0) {
4832 current_module="sub_free";
4833 for(i = 0; i < mpctx->set_of_sub_size; ++i) {
4834 sub_free(mpctx->set_of_subtitles[i]);
4835 #ifdef CONFIG_ASS
4836 if(mpctx->set_of_ass_tracks[i])
4837 ass_free_track( mpctx->set_of_ass_tracks[i] );
4838 #endif
4840 mpctx->set_of_sub_size = 0;
4842 mpctx->vo_sub_last = vo_sub=NULL;
4843 mpctx->subdata=NULL;
4844 #ifdef CONFIG_ASS
4845 mpctx->osd->ass_track = NULL;
4846 if(ass_library)
4847 ass_clear_fonts(ass_library);
4848 #endif
4850 if (!mpctx->stop_play) // In case some goto jumped here...
4851 mpctx->stop_play = PT_NEXT_ENTRY;
4853 int playtree_direction = 1;
4855 if(mpctx->stop_play == PT_NEXT_ENTRY || mpctx->stop_play == PT_PREV_ENTRY) {
4856 if(play_tree_iter_step(mpctx->playtree_iter,mpctx->play_tree_step,0) != PLAY_TREE_ITER_ENTRY) {
4857 play_tree_iter_free(mpctx->playtree_iter);
4858 mpctx->playtree_iter = NULL;
4860 mpctx->play_tree_step = 1;
4861 } else if(mpctx->stop_play == PT_UP_NEXT || mpctx->stop_play == PT_UP_PREV) {
4862 int direction = mpctx->stop_play == PT_UP_NEXT ? 1 : -1;
4863 if(mpctx->playtree_iter) {
4864 if(play_tree_iter_up_step(mpctx->playtree_iter,direction,0) != PLAY_TREE_ITER_ENTRY) {
4865 play_tree_iter_free(mpctx->playtree_iter);
4866 mpctx->playtree_iter = NULL;
4869 } else if (mpctx->stop_play == PT_STOP) {
4870 play_tree_iter_free(mpctx->playtree_iter);
4871 mpctx->playtree_iter = NULL;
4872 } else { // NEXT PREV SRC
4873 playtree_direction = mpctx->stop_play == PT_PREV_SRC ? -1 : 1;
4876 while(mpctx->playtree_iter != NULL) {
4877 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, playtree_direction);
4878 if(mpctx->filename == NULL) {
4879 if(play_tree_iter_step(mpctx->playtree_iter, playtree_direction, 0) != PLAY_TREE_ITER_ENTRY) {
4880 play_tree_iter_free(mpctx->playtree_iter);
4881 mpctx->playtree_iter = NULL;
4883 } else
4884 break;
4887 if (mpctx->playtree_iter != NULL || opts->player_idle_mode) {
4888 if(!mpctx->playtree_iter) mpctx->filename = NULL;
4889 mpctx->stop_play = 0;
4890 goto play_next_file;
4894 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4896 return 1;
4898 #endif /* DISABLE_MAIN */