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