Windows: vo/input: handle WM_XBUTTONDOWN message
[mplayer.git] / mplayer.c
blobaf26866be9ff6e4505b632cae49b5108b771d446
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 const 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 // free mplayer config
751 if(mpctx->mconfig)
752 m_config_free(mpctx->mconfig);
753 mpctx->mconfig = NULL;
755 if(mpctx->playtree_iter)
756 play_tree_iter_free(mpctx->playtree_iter);
757 mpctx->playtree_iter = NULL;
758 if(mpctx->playtree)
759 play_tree_free(mpctx->playtree, 1);
760 mpctx->playtree = NULL;
762 talloc_free(mpctx->key_fifo);
764 free(edl_records); // free mem allocated for EDL
765 edl_records = NULL;
766 switch(how) {
767 case EXIT_QUIT:
768 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Quit");
769 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=QUIT\n");
770 break;
771 case EXIT_EOF:
772 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","End of file");
773 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=EOF\n");
774 break;
775 case EXIT_ERROR:
776 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Fatal error");
777 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=ERROR\n");
778 break;
779 default:
780 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=NONE\n");
782 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"max framesize was %d bytes\n",max_framesize);
784 exit(rc);
787 static void exit_player(struct MPContext *mpctx, enum exit_reason how)
789 exit_player_with_rc(mpctx, how, 1);
792 #ifndef __MINGW32__
793 static void child_sighandler(int x){
794 pid_t pid;
795 while((pid=waitpid(-1,NULL,WNOHANG)) > 0);
797 #endif
799 #ifdef CONFIG_CRASH_DEBUG
800 static char *prog_path;
801 static int crash_debug = 0;
802 #endif
804 static void exit_sighandler(int x){
805 static int sig_count=0;
806 #ifdef CONFIG_CRASH_DEBUG
807 if (!crash_debug || x != SIGTRAP)
808 #endif
809 ++sig_count;
810 if(sig_count==5)
812 /* We're crashing bad and can't uninit cleanly :(
813 * by popular request, we make one last (dirty)
814 * effort to restore the user's
815 * terminal. */
816 getch2_disable();
817 exit(1);
819 if(sig_count==6) exit(1);
820 if(sig_count>6){
821 // can't stop :(
822 #ifndef __MINGW32__
823 kill(getpid(),SIGKILL);
824 #endif
826 mp_msg(MSGT_CPLAYER, MSGL_FATAL, "\n");
827 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,
828 "\nMPlayer interrupted by signal %d in module: %s\n", x,
829 current_module ? current_module : "unknown");
830 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SIGNAL=%d\n", x);
831 if(sig_count<=1)
832 switch(x){
833 case SIGINT:
834 case SIGPIPE:
835 case SIGQUIT:
836 case SIGTERM:
837 case SIGKILL:
838 async_quit_request = 1;
839 return; // killed from keyboard (^C) or killed [-9]
840 case SIGILL:
841 #if CONFIG_RUNTIME_CPUDETECT
842 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL_RTCpuSel);
843 #else
844 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL);
845 #endif
846 case SIGFPE:
847 case SIGSEGV:
848 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGSEGV_SIGFPE);
849 default:
850 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGCRASH);
851 #ifdef CONFIG_CRASH_DEBUG
852 if (crash_debug) {
853 int gdb_pid;
854 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forking...\n");
855 gdb_pid = fork();
856 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forked...\n");
857 if (gdb_pid == 0) { // We are the child
858 char spid[20];
859 snprintf(spid, sizeof(spid), "%i", getppid());
860 getch2_disable(); // allow terminal to work properly with gdb
861 if (execlp("gdb", "gdb", prog_path, spid, "-ex", "bt", NULL) == -1)
862 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't start gdb\n");
863 } else if (gdb_pid < 0)
864 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't fork\n");
865 else {
866 waitpid(gdb_pid, NULL, 0);
868 if (x == SIGTRAP) return;
870 #endif
872 getch2_disable();
873 exit(1);
876 #include "cfg-mplayer.h"
878 static int cfg_include(m_option_t *conf, char *filename)
880 return m_config_parse_config_file(conf->priv, filename);
883 #define DEF_CONFIG "# Write your default config options here!\n\n\n"
885 static void parse_cfgfiles(struct MPContext *mpctx, m_config_t* conf)
887 struct MPOpts *opts = &mpctx->opts;
888 char *conffile;
889 int conffile_fd;
890 if (!(opts->noconfig & 2) &&
891 m_config_parse_config_file(conf, MPLAYER_CONFDIR "/mplayer.conf") < 0)
892 exit_player(mpctx, EXIT_NONE);
893 if ((conffile = get_path("")) == NULL) {
894 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"Cannot find HOME directory.\n");
895 } else {
896 #ifdef __MINGW32__
897 mkdir(conffile);
898 #else
899 mkdir(conffile, 0777);
900 #endif
901 free(conffile);
902 if ((conffile = get_path("config")) == NULL) {
903 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"get_path(\"config\") problem\n");
904 } else {
905 if ((conffile_fd = open(conffile, O_CREAT | O_EXCL | O_WRONLY, 0666)) != -1) {
906 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Creating config file: %s\n", conffile);
907 write(conffile_fd, DEF_CONFIG, sizeof(DEF_CONFIG) - 1);
908 close(conffile_fd);
910 if (!(opts->noconfig & 1) &&
911 m_config_parse_config_file(conf, conffile) < 0)
912 exit_player(mpctx, EXIT_NONE);
913 free(conffile);
918 #define PROFILE_CFG_PROTOCOL "protocol."
920 static void load_per_protocol_config (m_config_t* conf, const char *const file)
922 char *str;
923 char protocol[strlen (PROFILE_CFG_PROTOCOL) + strlen (file) + 1];
924 m_profile_t *p;
926 /* does filename actually uses a protocol ? */
927 str = strstr (file, "://");
928 if (!str)
929 return;
931 sprintf (protocol, "%s%s", PROFILE_CFG_PROTOCOL, file);
932 protocol[strlen (PROFILE_CFG_PROTOCOL)+strlen(file)-strlen(str)] = '\0';
933 p = m_config_get_profile (conf, protocol);
934 if (p)
936 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading protocol-related profile '%s'\n", protocol);
937 m_config_set_profile(conf,p);
941 #define PROFILE_CFG_EXTENSION "extension."
943 static void load_per_extension_config (m_config_t* conf, const char *const file)
945 char *str;
946 char extension[strlen (PROFILE_CFG_EXTENSION) + 8];
947 m_profile_t *p;
949 /* does filename actually have an extension ? */
950 str = strrchr (file, '.');
951 if (!str)
952 return;
954 sprintf (extension, PROFILE_CFG_EXTENSION);
955 strncat (extension, ++str, 7);
956 p = m_config_get_profile (conf, extension);
957 if (p)
959 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", extension);
960 m_config_set_profile(conf,p);
964 #define PROFILE_CFG_VO "vo."
965 #define PROFILE_CFG_AO "ao."
967 static void load_per_output_config (m_config_t* conf, char *cfg, char *out)
969 char profile[strlen (cfg) + strlen (out) + 1];
970 m_profile_t *p;
972 sprintf (profile, "%s%s", cfg, out);
973 p = m_config_get_profile (conf, profile);
974 if (p)
976 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", profile);
977 m_config_set_profile(conf,p);
982 * Tries to load a config file
983 * @return 0 if file was not found, 1 otherwise
985 static int try_load_config(m_config_t *conf, const char *file)
987 struct stat st;
988 if (stat(file, &st))
989 return 0;
990 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Loading config '%s'\n", file);
991 m_config_parse_config_file (conf, file);
992 return 1;
995 static void load_per_file_config (m_config_t* conf, const char *const file)
997 char *confpath;
998 char cfg[PATH_MAX];
999 const char *name;
1001 if (strlen(file) > PATH_MAX - 14) {
1002 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Filename is too long, can not load file or directory specific config files\n");
1003 return;
1005 sprintf (cfg, "%s.conf", file);
1007 name = mp_basename(cfg);
1008 if (use_filedir_conf) {
1009 char dircfg[PATH_MAX];
1010 strcpy(dircfg, cfg);
1011 strcpy(dircfg + (name - cfg), "mplayer.conf");
1012 try_load_config(conf, dircfg);
1014 if (try_load_config(conf, cfg))
1015 return;
1018 if ((confpath = get_path (name)) != NULL)
1020 try_load_config(conf, confpath);
1022 free (confpath);
1026 /* When libmpdemux performs a blocking operation (network connection or
1027 * cache filling) if the operation fails we use this function to check
1028 * if it was interrupted by the user.
1029 * The function returns a new value for eof. */
1030 static int libmpdemux_was_interrupted(struct MPContext *mpctx, int stop_play)
1032 mp_cmd_t* cmd;
1033 if((cmd = mp_input_get_cmd(mpctx->input, 0, 0)) != NULL) {
1034 switch(cmd->id) {
1035 case MP_CMD_QUIT:
1036 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
1037 case MP_CMD_PLAY_TREE_STEP: {
1038 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_ENTRY : PT_PREV_ENTRY;
1039 mpctx->play_tree_step = (cmd->args[0].v.i == 0) ? 1 : cmd->args[0].v.i;
1040 } break;
1041 case MP_CMD_PLAY_TREE_UP_STEP: {
1042 stop_play = (cmd->args[0].v.i > 0) ? PT_UP_NEXT : PT_UP_PREV;
1043 } break;
1044 case MP_CMD_PLAY_ALT_SRC_STEP: {
1045 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_SRC : PT_PREV_SRC;
1046 } break;
1048 mp_cmd_free(cmd);
1050 return stop_play;
1053 static int playtree_add_playlist(struct MPContext *mpctx, play_tree_t* entry)
1055 play_tree_add_bpf(entry,mpctx->filename);
1058 if(!entry) {
1059 entry = mpctx->playtree_iter->tree;
1060 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1061 return PT_NEXT_ENTRY;
1063 if(mpctx->playtree_iter->tree == entry ) { // Loop with a single file
1064 if(play_tree_iter_up_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1065 return PT_NEXT_ENTRY;
1068 play_tree_remove(entry,1,1);
1069 return PT_NEXT_SRC;
1071 play_tree_insert_entry(mpctx->playtree_iter->tree,entry);
1072 play_tree_set_params_from(entry,mpctx->playtree_iter->tree);
1073 entry = mpctx->playtree_iter->tree;
1074 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1075 return PT_NEXT_ENTRY;
1077 play_tree_remove(entry,1,1);
1079 return PT_NEXT_SRC;
1082 void add_subtitles(struct MPContext *mpctx, char *filename, float fps, int noerr)
1084 struct MPOpts *opts = &mpctx->opts;
1085 sub_data *subd = NULL;
1086 struct ass_track *asst = NULL;
1087 bool is_native_ass = false;
1089 if (filename == NULL || mpctx->set_of_sub_size >= MAX_SUBTITLE_FILES)
1090 return;
1092 #ifdef CONFIG_ASS
1093 if (opts->ass_enabled) {
1094 #ifdef CONFIG_ICONV
1095 asst = mp_ass_read_stream(ass_library, filename, sub_cp);
1096 #else
1097 asst = mp_ass_read_stream(ass_library, filename, 0);
1098 #endif
1099 is_native_ass = asst;
1100 if (!asst) {
1101 subd = sub_read_file(filename, fps, &mpctx->opts);
1102 if (subd) {
1103 asst = mp_ass_read_subdata(ass_library, subd, fps);
1104 sub_free(subd);
1105 subd = NULL;
1108 } else
1109 #endif
1110 subd = sub_read_file(filename, fps, &mpctx->opts);
1113 if (!asst && !subd) {
1114 mp_tmsg(MSGT_CPLAYER, noerr ? MSGL_WARN : MSGL_ERR,
1115 "Cannot load subtitles: %s\n", filename_recode(filename));
1116 return;
1119 mpctx->set_of_ass_tracks[mpctx->set_of_sub_size] = asst;
1120 mpctx->set_of_subtitles[mpctx->set_of_sub_size] = subd;
1121 mpctx->track_was_native_ass[mpctx->set_of_sub_size] = is_native_ass;
1122 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_ID=%d\n", mpctx->set_of_sub_size);
1123 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_FILENAME=%s\n",
1124 filename_recode(filename));
1125 ++mpctx->set_of_sub_size;
1126 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "SUB: Added subtitle file (%d): %s\n", mpctx->set_of_sub_size,
1127 filename_recode(filename));
1130 void init_vo_spudec(struct MPContext *mpctx)
1132 spudec_free(vo_spudec);
1133 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
1134 vo_spudec = NULL;
1136 // we currently can't work without video stream
1137 if (!mpctx->sh_video)
1138 return;
1140 if (spudec_ifo) {
1141 unsigned int palette[16], width, height;
1142 current_module="spudec_init_vobsub";
1143 if (vobsub_parse_ifo(NULL,spudec_ifo, palette, &width, &height, 1, -1, NULL) >= 0)
1144 vo_spudec=spudec_new_scaled(palette, width, height, NULL, 0);
1147 #ifdef CONFIG_DVDREAD
1148 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVD) {
1149 current_module="spudec_init_dvdread";
1150 vo_spudec=spudec_new_scaled(((dvd_priv_t *)(mpctx->stream->priv))->cur_pgc->palette,
1151 mpctx->sh_video->disp_w, mpctx->sh_video->disp_h,
1152 NULL, 0);
1154 #endif
1156 #ifdef CONFIG_DVDNAV
1157 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVDNAV) {
1158 unsigned int *palette = mp_dvdnav_get_spu_clut(mpctx->stream);
1159 current_module="spudec_init_dvdnav";
1160 vo_spudec=spudec_new_scaled(palette, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, NULL, 0);
1162 #endif
1164 if (vo_spudec==NULL) {
1165 sh_sub_t *sh = mpctx->d_sub->sh;
1166 current_module="spudec_init_normal";
1167 vo_spudec=spudec_new_scaled(NULL, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, sh->extradata, sh->extradata_len);
1168 spudec_set_font_factor(vo_spudec,font_factor);
1171 if (vo_spudec!=NULL) {
1172 mpctx->initialized_flags|=INITIALIZED_SPUDEC;
1173 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
1178 * In Mac OS X the SDL-lib is built upon Cocoa. The easiest way to
1179 * make it all work is to use the builtin SDL-bootstrap code, which
1180 * will be done automatically by replacing our main() if we include SDL.h.
1182 #if defined(__APPLE__) && defined(CONFIG_SDL)
1183 #ifdef CONFIG_SDL_SDL_H
1184 #include <SDL/SDL.h>
1185 #else
1186 #include <SDL.h>
1187 #endif
1188 #endif
1191 * \brief append a formatted string
1192 * \param buf buffer to print into
1193 * \param pos position of terminating 0 in buf
1194 * \param len maximum number of characters in buf, not including terminating 0
1195 * \param format printf format string
1197 static void saddf(char *buf, unsigned *pos, int len, const char *format, ...)
1199 va_list va;
1200 va_start(va, format);
1201 *pos += vsnprintf(&buf[*pos], len - *pos, format, va);
1202 va_end(va);
1203 if (*pos >= len ) {
1204 buf[len] = 0;
1205 *pos = len;
1210 * \brief append time in the hh:mm:ss.f format
1211 * \param buf buffer to print into
1212 * \param pos position of terminating 0 in buf
1213 * \param len maximum number of characters in buf, not including terminating 0
1214 * \param time time value to convert/append
1216 static void sadd_hhmmssf(char *buf, unsigned *pos, int len, float time) {
1217 int64_t tenths = 10 * time;
1218 int f1 = tenths % 10;
1219 int ss = (tenths / 10) % 60;
1220 int mm = (tenths / 600) % 60;
1221 int hh = tenths / 36000;
1222 if (time <= 0) {
1223 saddf(buf, pos, len, "unknown");
1224 return;
1226 if (hh > 0)
1227 saddf(buf, pos, len, "%2d:", hh);
1228 if (hh > 0 || mm > 0)
1229 saddf(buf, pos, len, "%02d:", mm);
1230 saddf(buf, pos, len, "%02d.%1d", ss, f1);
1233 static void print_status(struct MPContext *mpctx, double a_pos, bool at_frame)
1235 struct MPOpts *opts = &mpctx->opts;
1236 sh_video_t * const sh_video = mpctx->sh_video;
1238 if (mpctx->sh_audio && a_pos == MP_NOPTS_VALUE)
1239 a_pos = playing_audio_pts(mpctx);
1240 if (mpctx->sh_audio && sh_video && at_frame) {
1241 mpctx->last_av_difference = a_pos - mpctx->video_pts - audio_delay;
1242 if (mpctx->time_frame > 0)
1243 mpctx->last_av_difference += mpctx->time_frame * opts->playback_speed;
1244 if (mpctx->last_av_difference > 0.5 && drop_frame_cnt > 50
1245 && !mpctx->drop_message_shown) {
1246 mp_tmsg(MSGT_AVSYNC,MSGL_WARN,SystemTooSlow);
1247 mpctx->drop_message_shown = true;
1250 if (opts->quiet)
1251 return;
1254 int width;
1255 char *line;
1256 unsigned pos = 0;
1257 get_screen_size();
1258 if (screen_width > 0)
1259 width = screen_width;
1260 else
1261 width = 80;
1262 #if defined(__MINGW32__) || defined(__CYGWIN__) || defined(__OS2__)
1263 /* Windows command line is broken (MinGW's rxvt works, but we
1264 * should not depend on that). */
1265 width--;
1266 #endif
1267 line = malloc(width + 1); // one additional char for the terminating null
1269 // Audio time
1270 if (mpctx->sh_audio) {
1271 saddf(line, &pos, width, "A:%6.1f ", a_pos);
1272 if (!sh_video) {
1273 float len = get_time_length(mpctx);
1274 saddf(line, &pos, width, "(");
1275 sadd_hhmmssf(line, &pos, width, a_pos);
1276 saddf(line, &pos, width, ") of %.1f (", len);
1277 sadd_hhmmssf(line, &pos, width, len);
1278 saddf(line, &pos, width, ") ");
1282 // Video time
1283 if (sh_video)
1284 saddf(line, &pos, width, "V:%6.1f ", mpctx->video_pts);
1286 // A-V sync
1287 if (mpctx->sh_audio && sh_video)
1288 saddf(line, &pos, width, "A-V:%7.3f ct:%7.3f ",
1289 mpctx->last_av_difference, mpctx->total_avsync_change);
1291 // Video stats
1292 if (sh_video)
1293 saddf(line, &pos, width, "%3d/%3d ",
1294 (int)sh_video->num_frames,
1295 (int)sh_video->num_frames_decoded);
1297 // CPU usage
1298 if (sh_video) {
1299 if (sh_video->timer > 0.5)
1300 saddf(line, &pos, width, "%2d%% %2d%% %4.1f%% ",
1301 (int)(100.0*video_time_usage*opts->playback_speed/(double)sh_video->timer),
1302 (int)(100.0*vout_time_usage*opts->playback_speed/(double)sh_video->timer),
1303 (100.0*audio_time_usage*opts->playback_speed/(double)sh_video->timer));
1304 else
1305 saddf(line, &pos, width, "??%% ??%% ??,?%% ");
1306 } else if (mpctx->sh_audio) {
1307 if (mpctx->delay > 0.5)
1308 saddf(line, &pos, width, "%4.1f%% ",
1309 100.0*audio_time_usage/(double)mpctx->delay);
1310 else
1311 saddf(line, &pos, width, "??,?%% ");
1314 // VO stats
1315 if (sh_video)
1316 saddf(line, &pos, width, "%d %d ", drop_frame_cnt, output_quality);
1318 #ifdef CONFIG_STREAM_CACHE
1319 // cache stats
1320 if (stream_cache_size > 0)
1321 saddf(line, &pos, width, "%d%% ", cache_fill_status(mpctx->stream));
1322 #endif
1324 // other
1325 if (opts->playback_speed != 1)
1326 saddf(line, &pos, width, "%4.2fx ", opts->playback_speed);
1328 // end
1329 if (erase_to_end_of_line) {
1330 line[pos] = 0;
1331 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s%s\r", line, erase_to_end_of_line);
1332 } else {
1333 memset(&line[pos], ' ', width - pos);
1334 line[width] = 0;
1335 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s\r", line);
1337 free(line);
1341 * \brief build a chain of audio filters that converts the input format
1342 * to the ao's format, taking into account the current playback_speed.
1343 * sh_audio describes the requested input format of the chain.
1344 * ao describes the requested output format of the chain.
1346 static int build_afilter_chain(struct MPContext *mpctx)
1348 struct sh_audio *sh_audio = mpctx->sh_audio;
1349 struct ao *ao = mpctx->ao;
1350 struct MPOpts *opts = &mpctx->opts;
1351 int new_srate;
1352 int result;
1353 if (!sh_audio)
1355 mpctx->mixer.afilter = NULL;
1356 return 0;
1358 if(af_control_any_rev(sh_audio->afilter,
1359 AF_CONTROL_PLAYBACK_SPEED | AF_CONTROL_SET,
1360 &opts->playback_speed)) {
1361 new_srate = sh_audio->samplerate;
1362 } else {
1363 new_srate = sh_audio->samplerate * opts->playback_speed;
1364 if (new_srate != ao->samplerate) {
1365 // limits are taken from libaf/af_resample.c
1366 if (new_srate < 8000)
1367 new_srate = 8000;
1368 if (new_srate > 192000)
1369 new_srate = 192000;
1370 opts->playback_speed = (float)new_srate / (float)sh_audio->samplerate;
1373 result = init_audio_filters(sh_audio, new_srate,
1374 &ao->samplerate, &ao->channels, &ao->format);
1375 mpctx->mixer.afilter = sh_audio->afilter;
1376 return result;
1380 typedef struct mp_osd_msg mp_osd_msg_t;
1381 struct mp_osd_msg {
1382 /// Previous message on the stack.
1383 mp_osd_msg_t* prev;
1384 /// Message text.
1385 char msg[128];
1386 int id,level,started;
1387 /// Display duration in ms.
1388 unsigned time;
1391 /// OSD message stack.
1392 static mp_osd_msg_t* osd_msg_stack = NULL;
1395 * \brief Add a message on the OSD message stack
1397 * If a message with the same id is already present in the stack
1398 * it is pulled on top of the stack, otherwise a new message is created.
1401 static void set_osd_msg_va(int id, int level, int time, const char *fmt,
1402 va_list ap)
1404 mp_osd_msg_t *msg,*last=NULL;
1405 int r;
1407 // look if the id is already in the stack
1408 for(msg = osd_msg_stack ; msg && msg->id != id ;
1409 last = msg, msg = msg->prev);
1410 // not found: alloc it
1411 if(!msg) {
1412 msg = calloc(1,sizeof(mp_osd_msg_t));
1413 msg->prev = osd_msg_stack;
1414 osd_msg_stack = msg;
1415 } else if(last) { // found, but it's not on top of the stack
1416 last->prev = msg->prev;
1417 msg->prev = osd_msg_stack;
1418 osd_msg_stack = msg;
1420 // write the msg
1421 r = vsnprintf(msg->msg, 128, fmt, ap);
1422 if(r >= 128) msg->msg[127] = 0;
1423 // set id and time
1424 msg->id = id;
1425 msg->level = level;
1426 msg->time = time;
1430 void set_osd_msg(int id, int level, int time, const char *fmt, ...)
1432 va_list ap;
1433 va_start(ap, fmt);
1434 set_osd_msg_va(id, level, time, fmt, ap);
1435 va_end(ap);
1438 void set_osd_tmsg(int id, int level, int time, const char *fmt, ...)
1440 va_list ap;
1441 va_start(ap, fmt);
1442 set_osd_msg_va(id, level, time, mp_gtext(fmt), ap);
1443 va_end(ap);
1448 * \brief Remove a message from the OSD stack
1450 * This function can be used to get rid of a message right away.
1454 void rm_osd_msg(int id) {
1455 mp_osd_msg_t *msg,*last=NULL;
1457 // Search for the msg
1458 for(msg = osd_msg_stack ; msg && msg->id != id ;
1459 last = msg, msg = msg->prev);
1460 if(!msg) return;
1462 // Detach it from the stack and free it
1463 if(last)
1464 last->prev = msg->prev;
1465 else
1466 osd_msg_stack = msg->prev;
1467 free(msg);
1471 * \brief Remove all messages from the OSD stack
1475 static void clear_osd_msgs(void) {
1476 mp_osd_msg_t* msg = osd_msg_stack, *prev = NULL;
1477 while(msg) {
1478 prev = msg->prev;
1479 free(msg);
1480 msg = prev;
1482 osd_msg_stack = NULL;
1486 * \brief Get the current message from the OSD stack.
1488 * This function decrements the message timer and destroys the old ones.
1489 * The message that should be displayed is returned (if any).
1493 static mp_osd_msg_t* get_osd_msg(struct MPContext *mpctx)
1495 struct MPOpts *opts = &mpctx->opts;
1496 mp_osd_msg_t *msg,*prev,*last = NULL;
1497 static unsigned last_update = 0;
1498 unsigned now = GetTimerMS();
1499 unsigned diff;
1500 char hidden_dec_done = 0;
1502 if (mpctx->osd_visible) {
1503 // 36000000 means max timed visibility is 1 hour into the future, if
1504 // the difference is greater assume it's wrapped around from below 0
1505 if (mpctx->osd_visible - now > 36000000) {
1506 mpctx->osd_visible = 0;
1507 vo_osd_progbar_type = -1; // disable
1508 vo_osd_changed(OSDTYPE_PROGBAR);
1509 mpctx->osd_function = mpctx->paused ? OSD_PAUSE : OSD_PLAY;
1512 if (mpctx->osd_show_percentage_until - now > 36000000)
1513 mpctx->osd_show_percentage_until = 0;
1515 if(!last_update) last_update = now;
1516 diff = now >= last_update ? now - last_update : 0;
1518 last_update = now;
1520 // Look for the first message in the stack with high enough level.
1521 for(msg = osd_msg_stack ; msg ; last = msg, msg = prev) {
1522 prev = msg->prev;
1523 if (msg->level > opts->osd_level && hidden_dec_done)
1524 continue;
1525 // The message has a high enough level or it is the first hidden one
1526 // in both cases we decrement the timer or kill it.
1527 if(!msg->started || msg->time > diff) {
1528 if(msg->started) msg->time -= diff;
1529 else msg->started = 1;
1530 // display it
1531 if (msg->level <= opts->osd_level)
1532 return msg;
1533 hidden_dec_done = 1;
1534 continue;
1536 // kill the message
1537 free(msg);
1538 if(last) {
1539 last->prev = prev;
1540 msg = last;
1541 } else {
1542 osd_msg_stack = prev;
1543 msg = NULL;
1546 // Nothing found
1547 return NULL;
1551 * \brief Display the OSD bar.
1553 * Display the OSD bar or fall back on a simple message.
1557 void set_osd_bar(struct MPContext *mpctx, int type,const char* name,double min,double max,double val) {
1558 struct MPOpts *opts = &mpctx->opts;
1559 if (opts->osd_level < 1)
1560 return;
1562 if(mpctx->sh_video) {
1563 mpctx->osd_visible = (GetTimerMS() + 1000) | 1;
1564 vo_osd_progbar_type = type;
1565 vo_osd_progbar_value = 256*(val-min)/(max-min);
1566 vo_osd_changed(OSDTYPE_PROGBAR);
1567 return;
1570 set_osd_msg(OSD_MSG_BAR, 1, opts->osd_duration, "%s: %d %%",
1571 name, ROUND(100*(val-min)/(max-min)));
1575 * \brief Display text subtitles on the OSD
1577 void set_osd_subtitle(struct MPContext *mpctx, subtitle *subs)
1579 int i;
1580 vo_sub = subs;
1581 vo_osd_changed(OSDTYPE_SUBTITLE);
1582 if (!mpctx->sh_video) {
1583 // reverse order, since newest set_osd_msg is displayed first
1584 for (i = SUB_MAX_TEXT - 1; i >= 0; i--) {
1585 if (!subs || i >= subs->lines || !subs->text[i])
1586 rm_osd_msg(OSD_MSG_SUB_BASE + i);
1587 else {
1588 // HACK: currently display time for each sub line except the last is set to 2 seconds.
1589 int display_time = i == subs->lines - 1 ? 180000 : 2000;
1590 set_osd_msg(OSD_MSG_SUB_BASE + i, 1, display_time, "%s", subs->text[i]);
1597 * \brief Update the OSD message line.
1599 * This function displays the current message on the vo OSD or on the term.
1600 * If the stack is empty and the OSD level is high enough the timer
1601 * is displayed (only on the vo OSD).
1605 static void update_osd_msg(struct MPContext *mpctx)
1607 struct MPOpts *opts = &mpctx->opts;
1608 mp_osd_msg_t *msg;
1609 struct osd_state *osd = mpctx->osd;
1610 char osd_text_timer[128];
1612 if (mpctx->add_osd_seek_info) {
1613 double percentage = get_percent_pos(mpctx);
1614 set_osd_bar(mpctx, 0, "Position", 0, 100, percentage);
1615 if (mpctx->sh_video)
1616 mpctx->osd_show_percentage_until = (GetTimerMS() + 1000) | 1;
1617 mpctx->add_osd_seek_info = false;
1620 // Look if we have a msg
1621 if((msg = get_osd_msg(mpctx))) {
1622 if (strcmp(osd->osd_text, msg->msg)) {
1623 strncpy(osd->osd_text, msg->msg, 127);
1624 if(mpctx->sh_video) vo_osd_changed(OSDTYPE_OSD); else
1625 if(opts->term_osd)
1626 mp_msg(MSGT_CPLAYER,MSGL_STATUS, "%s%s\n", opts->term_osd_esc,
1627 msg->msg);
1629 return;
1632 if(mpctx->sh_video) {
1633 // fallback on the timer
1634 if (opts->osd_level >= 2) {
1635 int len = get_time_length(mpctx);
1636 int percentage = -1;
1637 char percentage_text[10];
1638 char fractions_text[4];
1639 double fpts = get_current_time(mpctx);
1640 int pts = fpts;
1642 if (mpctx->osd_show_percentage_until)
1643 percentage = get_percent_pos(mpctx);
1645 if (percentage >= 0)
1646 snprintf(percentage_text, 9, " (%d%%)", percentage);
1647 else
1648 percentage_text[0] = 0;
1650 if (opts->osd_fractions == 1) {
1651 //print fractions as sub-second timestamp
1652 snprintf(fractions_text, sizeof(fractions_text), ".%02d",
1653 (int)((fpts - pts) * 100));
1654 } else if (opts->osd_fractions == 2) {
1655 /* Print fractions by estimating the frame count within the
1656 * second.
1658 * Rounding or cutting off numbers after the decimal point
1659 * causes problems because of float's precision and movies
1660 * whose first frame is not exactly at timestamp 0. Therefore,
1661 * we add 0.2 and cut off at the decimal point, which proved
1662 * to be good heuristic.
1664 double fps = mpctx->sh_video->fps;
1665 if (fps <= 1 || fps > 99)
1666 strcpy(fractions_text, ".??");
1667 else
1668 snprintf(fractions_text, sizeof(fractions_text), ".%02d",
1669 (int) ( (fpts - pts) * fps + 0.2 ) );
1670 } else {
1671 //do not print fractions
1672 fractions_text[0] = 0;
1675 if (opts->osd_level == 3)
1676 snprintf(osd_text_timer, 63,
1677 "%c %02d:%02d:%02d%s / %02d:%02d:%02d%s",
1678 mpctx->osd_function,pts/3600,(pts/60)%60,pts%60,
1679 fractions_text, len/3600, (len/60)%60, len%60,
1680 percentage_text);
1681 else
1682 snprintf(osd_text_timer, 63, "%c %02d:%02d:%02d%s%s",
1683 mpctx->osd_function,pts/3600,(pts/60)%60,
1684 pts%60, fractions_text, percentage_text);
1685 } else
1686 osd_text_timer[0]=0;
1688 if (strcmp(osd->osd_text, osd_text_timer)) {
1689 strncpy(osd->osd_text, osd_text_timer, 63);
1690 vo_osd_changed(OSDTYPE_OSD);
1692 return;
1695 // Clear the term osd line
1696 if (opts->term_osd && osd->osd_text[0]) {
1697 osd->osd_text[0] = 0;
1698 printf("%s\n", opts->term_osd_esc);
1702 ///@}
1703 // OSDMsgStack
1706 void reinit_audio_chain(struct MPContext *mpctx)
1708 struct MPOpts *opts = &mpctx->opts;
1709 struct ao *ao;
1710 if (!mpctx->sh_audio)
1711 return;
1712 if (!(mpctx->initialized_flags & INITIALIZED_ACODEC)) {
1713 current_module="init_audio_codec";
1714 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1715 if(!init_best_audio_codec(mpctx->sh_audio,audio_codec_list,audio_fm_list)){
1716 goto init_error;
1718 mpctx->initialized_flags|=INITIALIZED_ACODEC;
1719 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1723 current_module="af_preinit";
1724 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1725 mpctx->initialized_flags |= INITIALIZED_AO;
1726 mpctx->ao = ao_create();
1727 mpctx->ao->samplerate = force_srate;
1728 mpctx->ao->format = opts->audio_output_format;
1730 ao = mpctx->ao;
1732 // first init to detect best values
1733 if(!init_audio_filters(mpctx->sh_audio, // preliminary init
1734 // input:
1735 mpctx->sh_audio->samplerate,
1736 // output:
1737 &ao->samplerate, &ao->channels, &ao->format)) {
1738 mp_tmsg(MSGT_CPLAYER,MSGL_ERR, "Error at audio filter chain "
1739 "pre-init!\n");
1740 exit_player(mpctx, EXIT_ERROR);
1742 if (!ao->initialized) {
1743 current_module="ao2_init";
1744 ao->buffersize = opts->ao_buffersize;
1745 ao_init(ao, opts->audio_driver_list);
1746 if (!ao->initialized) {
1747 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Could not open/initialize audio device -> no sound.\n");
1748 goto init_error;
1750 mp_msg(MSGT_CPLAYER,MSGL_INFO,"AO: [%s] %dHz %dch %s (%d bytes per sample)\n",
1751 ao->driver->info->short_name,
1752 ao->samplerate, ao->channels,
1753 af_fmt2str_short(ao->format),
1754 af_fmt2bits(ao->format)/8 );
1755 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Description: %s\nAO: Author: %s\n",
1756 ao->driver->info->name, ao->driver->info->author);
1757 if (strlen(ao->driver->info->comment) > 0)
1758 mp_msg(MSGT_CPLAYER, MSGL_V, "AO: Comment: %s\n",
1759 ao->driver->info->comment);
1762 // init audio filters:
1763 current_module="af_init";
1764 if (!build_afilter_chain(mpctx)) {
1765 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Couldn't find matching filter/ao format!\n");
1766 goto init_error;
1768 mpctx->mixer.ao = ao;
1769 mpctx->mixer.volstep = volstep;
1770 mpctx->syncing_audio = true;
1771 return;
1773 init_error:
1774 uninit_player(mpctx, INITIALIZED_ACODEC|INITIALIZED_AO); // close codec and possibly AO
1775 mpctx->sh_audio=mpctx->d_audio->sh=NULL; // -> nosound
1776 mpctx->d_audio->id = -2;
1780 ///@}
1781 // Command2Property
1784 // Return pts value corresponding to the end point of audio written to the
1785 // ao so far.
1786 static double written_audio_pts(struct MPContext *mpctx)
1788 sh_audio_t *sh_audio = mpctx->sh_audio;
1789 demux_stream_t *d_audio = mpctx->d_audio;
1790 double buffered_output;
1791 // first calculate the end pts of audio that has been output by decoder
1792 double a_pts = sh_audio->pts;
1793 if (a_pts != MP_NOPTS_VALUE)
1794 // Good, decoder supports new way of calculating audio pts.
1795 // sh_audio->pts is the timestamp of the latest input packet with
1796 // known pts that the decoder has decoded. sh_audio->pts_bytes is
1797 // the amount of bytes the decoder has written after that timestamp.
1798 a_pts += sh_audio->pts_bytes / (double) sh_audio->o_bps;
1799 else {
1800 // Decoder doesn't support new way of calculating pts (or we're
1801 // being called before it has decoded anything with known timestamp).
1802 // Use the old method of audio pts calculation: take the timestamp
1803 // of last packet with known pts the decoder has read data from,
1804 // and add amount of bytes read after the beginning of that packet
1805 // divided by input bps. This will be inaccurate if the input/output
1806 // ratio is not constant for every audio packet or if it is constant
1807 // but not accurately known in sh_audio->i_bps.
1809 a_pts = d_audio->pts;
1810 // ds_tell_pts returns bytes read after last timestamp from
1811 // demuxing layer, decoder might use sh_audio->a_in_buffer for bytes
1812 // it has read but not decoded
1813 if (sh_audio->i_bps)
1814 a_pts += (ds_tell_pts(d_audio) - sh_audio->a_in_buffer_len) /
1815 (double)sh_audio->i_bps;
1817 // Now a_pts hopefully holds the pts for end of audio from decoder.
1818 // Substract data in buffers between decoder and audio out.
1820 // Decoded but not filtered
1821 a_pts -= sh_audio->a_buffer_len / (double)sh_audio->o_bps;
1823 // Data buffered in audio filters, measured in bytes of "missing" output
1824 buffered_output = af_calc_delay(sh_audio->afilter);
1826 // Data that was ready for ao but was buffered because ao didn't fully
1827 // accept everything to internal buffers yet
1828 buffered_output += sh_audio->a_out_buffer_len;
1830 // Filters divide audio length by playback_speed, so multiply by it
1831 // to get the length in original units without speedup or slowdown
1832 a_pts -= buffered_output * mpctx->opts.playback_speed / mpctx->ao->bps;
1834 return a_pts + mpctx->video_offset;
1837 // Return pts value corresponding to currently playing audio.
1838 double playing_audio_pts(struct MPContext *mpctx)
1840 return written_audio_pts(mpctx) - mpctx->opts.playback_speed *
1841 ao_get_delay(mpctx->ao);
1844 static bool is_av_sub(int type)
1846 return type == 'b' || type == 'p' || type == 'x';
1849 void update_subtitles(struct MPContext *mpctx, double refpts,
1850 double sub_offset, bool reset)
1852 struct MPOpts *opts = &mpctx->opts;
1853 struct sh_video *sh_video = mpctx->sh_video;
1854 struct demux_stream *d_sub = mpctx->d_sub;
1855 double curpts = refpts + sub_delay;
1856 unsigned char *packet=NULL;
1857 int len;
1858 struct sh_sub *sh_sub = d_sub->sh;
1859 int type = sh_sub ? sh_sub->type : 'v';
1860 static subtitle subs;
1861 if (reset) {
1862 if (sh_sub)
1863 sub_reset(sh_sub, mpctx->osd);
1864 sub_clear_text(&subs, MP_NOPTS_VALUE);
1865 if (vo_sub)
1866 set_osd_subtitle(mpctx, NULL);
1867 if (vo_spudec) {
1868 spudec_reset(vo_spudec);
1869 vo_osd_changed(OSDTYPE_SPU);
1871 #ifdef CONFIG_FFMPEG
1872 if (is_av_sub(type))
1873 reset_avsub(sh_sub);
1874 #endif
1875 return;
1877 // find sub
1878 if (mpctx->subdata) {
1879 if (sub_fps==0) sub_fps = sh_video ? sh_video->fps : 25;
1880 current_module = "find_sub";
1881 find_sub(mpctx, mpctx->subdata, curpts *
1882 (mpctx->subdata->sub_uses_time ? 100. : sub_fps));
1883 if (vo_sub)
1884 mpctx->vo_sub_last = vo_sub;
1887 // DVD sub:
1888 if (vobsub_id >= 0 || type == 'v') {
1889 int timestamp;
1890 current_module = "spudec";
1891 /* Get a sub packet from the DVD or a vobsub */
1892 while(1) {
1893 // Vobsub
1894 len = 0;
1895 if (vo_vobsub) {
1896 if (curpts >= 0) {
1897 len = vobsub_get_packet(vo_vobsub, curpts,
1898 (void**)&packet, &timestamp);
1899 if (len > 0) {
1900 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);
1903 } else {
1904 // DVD sub
1905 len = ds_get_packet_sub(d_sub, (unsigned char**)&packet);
1906 if (len > 0) {
1907 // XXX This is wrong, sh_video->pts can be arbitrarily
1908 // much behind demuxing position. Unfortunately using
1909 // d_video->pts which would have been the simplest
1910 // improvement doesn't work because mpeg specific hacks
1911 // in video.c set d_video->pts to 0.
1912 float x = d_sub->pts - refpts;
1913 if (x > -20 && x < 20) // prevent missing subs on pts reset
1914 timestamp = 90000*d_sub->pts;
1915 else timestamp = 90000*curpts;
1916 mp_dbg(MSGT_CPLAYER, MSGL_V, "\rDVD sub: len=%d "
1917 "v_pts=%5.3f s_pts=%5.3f ts=%d \n", len,
1918 refpts, d_sub->pts, timestamp);
1921 if (len<=0 || !packet) break;
1922 // create it only here, since with some broken demuxers we might
1923 // type = v but no DVD sub and we currently do not change the
1924 // "original frame size" ever after init, leading to wrong-sized
1925 // PGS subtitles.
1926 if (!vo_spudec)
1927 vo_spudec = spudec_new(NULL);
1928 if (vo_vobsub || timestamp >= 0)
1929 spudec_assemble(vo_spudec, packet, len, timestamp);
1931 } else if (is_text_sub(type) || is_av_sub(type) || type == 'd') {
1932 if (type == 'd' && !d_sub->demuxer->teletext) {
1933 tt_stream_props tsp = {0};
1934 void *ptr = &tsp;
1935 if (teletext_control(NULL, TV_VBI_CONTROL_START, &ptr) == VBI_CONTROL_TRUE)
1936 d_sub->demuxer->teletext = ptr;
1938 if (d_sub->non_interleaved)
1939 ds_get_next_pts(d_sub);
1941 while (d_sub->first) {
1942 double subpts = ds_get_next_pts(d_sub) + sub_offset;
1943 if (subpts > curpts) {
1944 // Libass handled subs can be fed to it in advance
1945 if (!opts->ass_enabled || !is_text_sub(type))
1946 break;
1947 // Try to avoid demuxing whole file at once
1948 if (d_sub->non_interleaved && subpts > curpts + 1)
1949 break;
1951 double duration = d_sub->first->duration;
1952 len = ds_get_packet_sub(d_sub, &packet);
1953 if (is_av_sub(type)) {
1954 #ifdef CONFIG_FFMPEG
1955 int ret = decode_avsub(sh_sub, packet, len, subpts, duration);
1956 if (ret < 0)
1957 mp_msg(MSGT_SPUDEC, MSGL_WARN, "lavc failed decoding "
1958 "subtitle\n");
1959 #endif
1960 continue;
1962 if (type == 'm') {
1963 if (len < 2) continue;
1964 len = FFMIN(len - 2, AV_RB16(packet));
1965 packet += 2;
1967 if (type == 'd') {
1968 if (d_sub->demuxer->teletext) {
1969 uint8_t *p = packet;
1970 p++;
1971 len--;
1972 while (len >= 46) {
1973 int sublen = p[1];
1974 if (p[0] == 2 || p[0] == 3)
1975 teletext_control(d_sub->demuxer->teletext,
1976 TV_VBI_CONTROL_DECODE_DVB, p + 2);
1977 p += sublen + 2;
1978 len -= sublen + 2;
1981 continue;
1983 if (sh_sub && sh_sub->active) {
1984 sub_decode(sh_sub, mpctx->osd, packet, len, subpts, duration);
1985 continue;
1987 if (subpts != MP_NOPTS_VALUE) {
1988 if (duration < 0)
1989 sub_clear_text(&subs, MP_NOPTS_VALUE);
1990 if (type == 'a') { // ssa/ass subs without libass => convert to plaintext
1991 int i;
1992 unsigned char* p = packet;
1993 for (i=0; i < 8 && *p != '\0'; p++)
1994 if (*p == ',')
1995 i++;
1996 if (*p == '\0') /* Broken line? */
1997 continue;
1998 len -= p - packet;
1999 packet = p;
2001 double endpts = MP_NOPTS_VALUE;
2002 if (subpts != MP_NOPTS_VALUE && duration >= 0)
2003 endpts = subpts + duration;
2004 sub_add_text(&subs, packet, len, endpts);
2005 set_osd_subtitle(mpctx, &subs);
2007 if (d_sub->non_interleaved)
2008 ds_get_next_pts(d_sub);
2010 if (!opts->ass_enabled)
2011 if (sub_clear_text(&subs, curpts))
2012 set_osd_subtitle(mpctx, &subs);
2014 if (vo_spudec) {
2015 spudec_heartbeat(vo_spudec, 90000*curpts);
2016 if (spudec_changed(vo_spudec))
2017 vo_osd_changed(OSDTYPE_SPU);
2020 current_module=NULL;
2023 static void update_teletext(sh_video_t *sh_video, demuxer_t *demuxer, int reset)
2025 int page_changed;
2027 if (!demuxer->teletext)
2028 return;
2030 //Also forcing page update when such ioctl is not supported or call error occured
2031 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_IS_CHANGED,&page_changed)!=VBI_CONTROL_TRUE)
2032 page_changed=1;
2034 if(!page_changed)
2035 return;
2037 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_GET_VBIPAGE,&vo_osd_teletext_page)!=VBI_CONTROL_TRUE)
2038 vo_osd_teletext_page=NULL;
2039 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_GET_HALF_PAGE,&vo_osd_teletext_half)!=VBI_CONTROL_TRUE)
2040 vo_osd_teletext_half=0;
2041 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_GET_MODE,&vo_osd_teletext_mode)!=VBI_CONTROL_TRUE)
2042 vo_osd_teletext_mode=0;
2043 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_GET_FORMAT,&vo_osd_teletext_format)!=VBI_CONTROL_TRUE)
2044 vo_osd_teletext_format=0;
2045 vo_osd_changed(OSDTYPE_TELETEXT);
2047 teletext_control(demuxer->teletext,TV_VBI_CONTROL_MARK_UNCHANGED,NULL);
2050 static int check_framedrop(struct MPContext *mpctx, double frame_time) {
2051 struct MPOpts *opts = &mpctx->opts;
2052 // check for frame-drop:
2053 current_module = "check_framedrop";
2054 if (mpctx->sh_audio && !mpctx->ao->untimed && !mpctx->d_audio->eof) {
2055 static int dropped_frames;
2056 float delay = opts->playback_speed * ao_get_delay(mpctx->ao);
2057 float d = delay-mpctx->delay;
2058 ++total_frame_cnt;
2059 // we should avoid dropping too many frames in sequence unless we
2060 // are too late. and we allow 100ms A-V delay here:
2061 if (d < -dropped_frames*frame_time-0.100 && !mpctx->paused
2062 && !mpctx->restart_playback) {
2063 ++drop_frame_cnt;
2064 ++dropped_frames;
2065 return frame_dropping;
2066 } else
2067 dropped_frames = 0;
2069 return 0;
2073 #ifdef HAVE_RTC
2074 int rtc_fd = -1;
2075 #endif
2077 static float timing_sleep(struct MPContext *mpctx, float time_frame)
2079 #ifdef HAVE_RTC
2080 if (rtc_fd >= 0){
2081 // -------- RTC -----------
2082 current_module="sleep_rtc";
2083 while (time_frame > 0.000) {
2084 unsigned long rtc_ts;
2085 if (read(rtc_fd, &rtc_ts, sizeof(rtc_ts)) <= 0)
2086 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC read error: %s\n", strerror(errno));
2087 time_frame -= get_relative_time(mpctx);
2089 } else
2090 #endif
2092 // assume kernel HZ=100 for softsleep, works with larger HZ but with
2093 // unnecessarily high CPU usage
2094 struct MPOpts *opts = &mpctx->opts;
2095 float margin = opts->softsleep ? 0.011 : 0;
2096 current_module = "sleep_timer";
2097 while (time_frame > margin) {
2098 usec_sleep(1000000 * (time_frame - margin));
2099 time_frame -= get_relative_time(mpctx);
2101 if (opts->softsleep){
2102 current_module = "sleep_soft";
2103 if (time_frame < 0)
2104 mp_tmsg(MSGT_AVSYNC, MSGL_WARN, "Warning! Softsleep underflow!\n");
2105 while (time_frame > 0)
2106 time_frame -= get_relative_time(mpctx); // burn the CPU
2109 return time_frame;
2112 static int select_subtitle(MPContext *mpctx)
2114 struct MPOpts *opts = &mpctx->opts;
2115 // find the best sub to use
2116 int id;
2117 int found = 0;
2118 mpctx->global_sub_pos = -1; // no subs by default
2119 if (vobsub_id >= 0) {
2120 // if user asks for a vobsub id, use that first.
2121 id = vobsub_id;
2122 found = mp_property_do("sub_vob", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
2125 if (!found && opts->sub_id >= 0) {
2126 // if user asks for a dvd sub id, use that next.
2127 id = opts->sub_id;
2128 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
2131 if (!found) {
2132 // if there are text subs to use, use those. (autosubs come last here)
2133 id = 0;
2134 found = mp_property_do("sub_file", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
2137 if (!found && opts->sub_id == -1) {
2138 // finally select subs by language and container hints
2139 if (opts->sub_id == -1)
2140 opts->sub_id =
2141 demuxer_sub_track_by_lang_and_default(mpctx->d_sub->demuxer,
2142 opts->sub_lang);
2143 if (opts->sub_id >= 0) {
2144 id = opts->sub_id;
2145 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
2148 return found;
2151 #ifdef CONFIG_DVDNAV
2152 #ifndef FF_B_TYPE
2153 #define FF_B_TYPE 3
2154 #endif
2155 /// store decoded video image
2156 static mp_image_t * mp_dvdnav_copy_mpi(mp_image_t *to_mpi,
2157 mp_image_t *from_mpi) {
2158 mp_image_t *mpi;
2160 /// Do not store B-frames
2161 if (from_mpi->pict_type == FF_B_TYPE)
2162 return to_mpi;
2164 if (to_mpi &&
2165 to_mpi->w == from_mpi->w &&
2166 to_mpi->h == from_mpi->h &&
2167 to_mpi->imgfmt == from_mpi->imgfmt)
2168 mpi = to_mpi;
2169 else {
2170 if (to_mpi)
2171 free_mp_image(to_mpi);
2172 if (from_mpi->w == 0 || from_mpi->h == 0)
2173 return NULL;
2174 mpi = alloc_mpi(from_mpi->w,from_mpi->h,from_mpi->imgfmt);
2177 copy_mpi(mpi,from_mpi);
2178 return mpi;
2181 static void mp_dvdnav_reset_stream (MPContext *ctx) {
2182 struct MPOpts *opts = &ctx->opts;
2183 if (ctx->sh_video) {
2184 /// clear video pts
2185 ctx->d_video->pts = 0.0f;
2186 ctx->sh_video->pts = 0.0f;
2187 ctx->sh_video->i_pts = 0.0f;
2188 ctx->sh_video->last_pts = 0.0f;
2189 ctx->sh_video->num_buffered_pts = 0;
2190 ctx->sh_video->num_frames = 0;
2191 ctx->sh_video->num_frames_decoded = 0;
2192 ctx->sh_video->timer = 0.0f;
2193 ctx->sh_video->stream_delay = 0.0f;
2194 ctx->sh_video->timer = 0;
2195 ctx->demuxer->stream_pts = MP_NOPTS_VALUE;
2198 if (ctx->sh_audio) {
2199 /// free audio packets and reset
2200 ds_free_packs(ctx->d_audio);
2201 audio_delay -= ctx->sh_audio->stream_delay;
2202 ctx->delay =- audio_delay;
2203 ao_reset(ctx->ao);
2204 resync_audio_stream(ctx->sh_audio);
2207 audio_delay = 0.0f;
2208 ctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(ctx->stream);
2209 if (opts->sub_lang && opts->sub_id == dvdsub_lang_id) {
2210 dvdsub_lang_id = mp_dvdnav_sid_from_lang(ctx->stream, opts->sub_lang);
2211 if (dvdsub_lang_id != opts->sub_id) {
2212 opts->sub_id = dvdsub_lang_id;
2213 select_subtitle(ctx);
2217 /// clear all EOF related flags
2218 ctx->d_video->eof = ctx->d_audio->eof = ctx->stream->eof = 0;
2221 /// Restore last decoded DVDNAV (still frame)
2222 static mp_image_t *mp_dvdnav_restore_smpi(struct MPContext *mpctx,
2223 int *in_size,
2224 unsigned char **start,
2225 mp_image_t *decoded_frame)
2227 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2228 return decoded_frame;
2230 /// a change occured in dvdnav stream
2231 if (mp_dvdnav_cell_has_changed(mpctx->stream,0)) {
2232 mp_dvdnav_read_wait(mpctx->stream, 1, 1);
2233 mp_dvdnav_context_free(mpctx);
2234 mp_dvdnav_reset_stream(mpctx);
2235 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
2236 mp_dvdnav_cell_has_changed(mpctx->stream,1);
2239 if (*in_size < 0) {
2240 float len;
2242 /// Display still frame, if any
2243 if (mpctx->nav_smpi && !mpctx->nav_buffer)
2244 decoded_frame = mpctx->nav_smpi;
2246 /// increment video frame : continue playing after still frame
2247 len = get_time_length(mpctx);
2248 if (mpctx->sh_video->pts >= len &&
2249 mpctx->sh_video->pts > 0.0 && len > 0.0) {
2250 mp_dvdnav_skip_still(mpctx->stream);
2251 mp_dvdnav_skip_wait(mpctx->stream);
2253 mpctx->sh_video->pts += 1 / mpctx->sh_video->fps;
2255 if (mpctx->nav_buffer) {
2256 *start = mpctx->nav_start;
2257 *in_size = mpctx->nav_in_size;
2258 if (mpctx->nav_start)
2259 memcpy(*start,mpctx->nav_buffer,mpctx->nav_in_size);
2263 return decoded_frame;
2266 /// Save last decoded DVDNAV (still frame)
2267 static void mp_dvdnav_save_smpi(struct MPContext *mpctx, int in_size,
2268 unsigned char *start,
2269 mp_image_t *decoded_frame)
2271 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2272 return;
2274 free(mpctx->nav_buffer);
2276 mpctx->nav_buffer = malloc(in_size);
2277 mpctx->nav_start = start;
2278 mpctx->nav_in_size = mpctx->nav_buffer ? in_size : -1;
2279 if (mpctx->nav_buffer)
2280 memcpy(mpctx->nav_buffer,start,in_size);
2282 if (decoded_frame && mpctx->nav_smpi != decoded_frame)
2283 mpctx->nav_smpi = mp_dvdnav_copy_mpi(mpctx->nav_smpi,decoded_frame);
2285 #endif /* CONFIG_DVDNAV */
2287 /* Modify video timing to match the audio timeline. There are two main
2288 * reasons this is needed. First, video and audio can start from different
2289 * positions at beginning of file or after a seek (MPlayer starts both
2290 * immediately even if they have different pts). Second, the file can have
2291 * audio timestamps that are inconsistent with the duration of the audio
2292 * packets, for example two consecutive timestamp values differing by
2293 * one second but only a packet with enough samples for half a second
2294 * of playback between them.
2296 static void adjust_sync(struct MPContext *mpctx, double frame_time)
2298 current_module = "av_sync";
2300 if (!mpctx->sh_audio || mpctx->syncing_audio)
2301 return;
2303 double a_pts = written_audio_pts(mpctx) - mpctx->delay;
2304 double v_pts = mpctx->sh_video->pts;
2305 double av_delay = a_pts - v_pts;
2306 // Try to sync vo_flip() so it will *finish* at given time
2307 av_delay += mpctx->last_vo_flip_duration;
2308 av_delay -= audio_delay; // This much pts difference is desired
2310 double change = av_delay * 0.1;
2311 double max_change = default_max_pts_correction >= 0 ?
2312 default_max_pts_correction : frame_time * 0.1;
2313 if (change < -max_change)
2314 change = -max_change;
2315 else if (change > max_change)
2316 change = max_change;
2317 mpctx->delay += change;
2318 mpctx->total_avsync_change += change;
2321 #define ASYNC_PLAY_DONE -3
2322 static int audio_start_sync(struct MPContext *mpctx, int playsize)
2324 struct ao *ao = mpctx->ao;
2325 struct MPOpts *opts = &mpctx->opts;
2326 sh_audio_t * const sh_audio = mpctx->sh_audio;
2327 int res;
2329 // Timing info may not be set without
2330 res = decode_audio(sh_audio, 1);
2331 if (res < 0)
2332 return res;
2334 int bytes;
2335 bool did_retry = false;
2336 while (1) {
2337 double written_pts = written_audio_pts(mpctx);
2338 double ptsdiff = written_pts - mpctx->video_pts - mpctx->delay
2339 - audio_delay;
2340 bytes = ptsdiff * ao->bps / mpctx->opts.playback_speed;
2341 bytes -= bytes % (ao->channels * af_fmt2bits(ao->format) / 8);
2343 // ogg demuxers give packets without timing
2344 if (written_pts <= 1 && sh_audio->pts == MP_NOPTS_VALUE) {
2345 if (!did_retry) {
2346 // Try to read more data to see packets that have pts
2347 int res = decode_audio(sh_audio, ao->bps);
2348 if (res < 0)
2349 return res;
2350 did_retry = true;
2351 continue;
2353 bytes = 0;
2356 if (fabs(ptsdiff) > 300) // pts reset or just broken?
2357 bytes = 0;
2359 if (bytes > 0)
2360 break;
2362 mpctx->syncing_audio = false;
2363 int a = FFMIN(-bytes, FFMAX(playsize, 20000));
2364 int res = decode_audio(sh_audio, a);
2365 bytes += sh_audio->a_out_buffer_len;
2366 if (bytes >= 0) {
2367 memmove(sh_audio->a_out_buffer,
2368 sh_audio->a_out_buffer +
2369 sh_audio->a_out_buffer_len - bytes,
2370 bytes);
2371 sh_audio->a_out_buffer_len = bytes;
2372 if (res < 0)
2373 return res;
2374 return decode_audio(sh_audio, playsize);
2376 sh_audio->a_out_buffer_len = 0;
2377 if (res < 0)
2378 return res;
2380 int fillbyte = 0;
2381 if ((ao->format & AF_FORMAT_SIGN_MASK) == AF_FORMAT_US)
2382 fillbyte = 0x80;
2383 if (bytes >= playsize) {
2384 /* This case could fall back to the one below with
2385 * bytes = playsize, but then silence would keep accumulating
2386 * in a_out_buffer if the AO accepts less data than it asks for
2387 * in playsize. */
2388 char *p = malloc(playsize);
2389 memset(p, fillbyte, playsize);
2390 playsize = ao_play(ao, p, playsize, 0);
2391 free(p);
2392 mpctx->delay += opts->playback_speed*playsize/(double)ao->bps;
2393 return ASYNC_PLAY_DONE;
2395 mpctx->syncing_audio = false;
2396 decode_audio_prepend_bytes(sh_audio, bytes, fillbyte);
2397 return decode_audio(sh_audio, playsize);
2400 static int fill_audio_out_buffers(struct MPContext *mpctx)
2402 struct MPOpts *opts = &mpctx->opts;
2403 struct ao *ao = mpctx->ao;
2404 unsigned int t;
2405 double tt;
2406 int playsize;
2407 int playflags=0;
2408 bool audio_eof = false;
2409 bool partial_fill = false;
2410 bool format_change = false;
2411 sh_audio_t * const sh_audio = mpctx->sh_audio;
2412 bool modifiable_audio_format = !(ao->format & AF_FORMAT_SPECIAL_MASK);
2413 int unitsize = ao->channels * af_fmt2bits(ao->format) / 8;
2415 current_module="play_audio";
2417 if (ao->untimed && mpctx->sh_video && mpctx->delay > 0)
2418 return 0;
2420 // all the current uses of ao->pts seem to be in aos that handle
2421 // sync completely wrong; there should be no need to use ao->pts
2422 // in get_space()
2423 ao->pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2424 playsize = ao_get_space(ao);
2426 // Fill buffer if needed:
2427 current_module="decode_audio";
2428 t = GetTimer();
2430 if (!opts->initial_audio_sync || !modifiable_audio_format)
2431 mpctx->syncing_audio = false;
2433 int res;
2434 if (mpctx->syncing_audio && mpctx->sh_video)
2435 res = audio_start_sync(mpctx, playsize);
2436 else
2437 res = decode_audio(sh_audio, playsize);
2438 if (res < 0) { // EOF, error or format change
2439 if (res == -2)
2440 format_change = true;
2441 else if (res == ASYNC_PLAY_DONE)
2442 return 0;
2443 else if (mpctx->d_audio->eof)
2444 audio_eof = true;
2446 t = GetTimer() - t;
2447 tt = t*0.000001f; audio_time_usage+=tt;
2448 if (mpctx->timeline && modifiable_audio_format) {
2449 double endpts = mpctx->timeline[mpctx->timeline_part + 1].start;
2450 double bytes = (endpts - written_audio_pts(mpctx) + audio_delay)
2451 * ao->bps / opts->playback_speed;
2452 if (playsize > bytes) {
2453 playsize = FFMAX(bytes, 0);
2454 playflags |= AOPLAY_FINAL_CHUNK;
2455 audio_eof = true;
2456 partial_fill = true;
2460 assert(sh_audio->a_out_buffer_len % unitsize == 0);
2461 if (playsize > sh_audio->a_out_buffer_len) {
2462 partial_fill = true;
2463 playsize = sh_audio->a_out_buffer_len;
2464 if (audio_eof)
2465 playflags |= AOPLAY_FINAL_CHUNK;
2467 playsize -= playsize % unitsize;
2468 if (!playsize)
2469 return partial_fill && audio_eof ? -2 : -partial_fill;
2471 // play audio:
2472 current_module="play_audio";
2474 // Is this pts value actually useful for the aos that access it?
2475 // They're obviously badly broken in the way they handle av sync;
2476 // would not having access to this make them more broken?
2477 ao->pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2478 playsize = ao_play(ao, sh_audio->a_out_buffer, playsize, playflags);
2479 assert(playsize % unitsize == 0);
2481 if (playsize > 0) {
2482 sh_audio->a_out_buffer_len -= playsize;
2483 memmove(sh_audio->a_out_buffer, &sh_audio->a_out_buffer[playsize],
2484 sh_audio->a_out_buffer_len);
2485 mpctx->delay += opts->playback_speed*playsize/(double)ao->bps;
2486 } else if (audio_eof && ao_get_delay(ao) < .04) {
2487 // Sanity check to avoid hanging in case current ao doesn't output
2488 // partial chunks and doesn't check for AOPLAY_FINAL_CHUNK
2489 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Audio output truncated at end.\n");
2490 sh_audio->a_out_buffer_len = 0;
2493 /* The format change isn't handled too gracefully. A more precise
2494 * implementation would require draining buffered old-format audio
2495 * while displaying video, then doing the output format switch.
2497 if (format_change) {
2498 uninit_player(mpctx, INITIALIZED_AO);
2499 reinit_audio_chain(mpctx);
2500 return -1;
2503 return -partial_fill;
2506 static int sleep_until_near_frame(struct MPContext *mpctx, float *time_frame,
2507 bool sync_to_audio, float *aq_sleep_time)
2509 struct MPOpts *opts = &mpctx->opts;
2510 double audio_limit = 2;
2511 current_module="calc_sleep_time";
2513 if (mpctx->restart_playback)
2514 return 0;
2516 *time_frame -= get_relative_time(mpctx); // reset timer
2518 if (sync_to_audio) {
2519 float delay = ao_get_delay(mpctx->ao);
2520 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "delay=%f\n", delay);
2522 if (opts->autosync) {
2524 * Adjust this raw delay value by calculating the expected
2525 * delay for this frame and generating a new value which is
2526 * weighted between the two. The higher autosync is, the
2527 * closer to the delay value gets to that which "-nosound"
2528 * would have used, and the longer it will take for A/V
2529 * sync to settle at the right value (but it eventually will.)
2530 * This settling time is very short for values below 100.
2532 float predicted = mpctx->delay / opts->playback_speed + *time_frame;
2533 float difference = delay - predicted;
2534 delay = predicted + difference / (float)opts->autosync;
2537 *time_frame = delay - mpctx->delay / opts->playback_speed;
2539 // delay = amount of audio buffered in soundcard/driver
2540 delay = FFMIN(delay, 0.5);
2541 delay = FFMAX(delay, 0.1);
2542 audio_limit = delay;
2543 } else {
2544 // If we're lagging more than 200 ms behind the right playback rate,
2545 // don't try to "catch up".
2546 // If benchmark is set always output frames as fast as possible
2547 // without sleeping.
2548 if (*time_frame < -0.2 || opts->benchmark)
2549 *time_frame = 0;
2552 double t = *time_frame - mpctx->video_out->flip_queue_offset;
2554 if (t <= 0.05)
2555 return 0;
2557 t -= 0.05;
2558 if (t > audio_limit * 0.6)
2559 t = audio_limit * 0.5;
2560 *aq_sleep_time += t;
2561 mp_input_get_cmd(mpctx->input, t * 1000 + 1, 1);
2562 return 1;
2565 int reinit_video_chain(struct MPContext *mpctx)
2567 struct MPOpts *opts = &mpctx->opts;
2568 sh_video_t * const sh_video = mpctx->sh_video;
2569 if (!sh_video)
2570 return 0;
2571 double ar=-1.0;
2572 //================== Init VIDEO (codec & libvo) ==========================
2573 if (!opts->fixed_vo || !(mpctx->initialized_flags & INITIALIZED_VO)) {
2574 current_module="preinit_libvo";
2576 //shouldn't we set dvideo->id=-2 when we fail?
2577 //if((mpctx->video_out->preinit(vo_subdevice))!=0){
2578 if(!(mpctx->video_out=init_best_video_out(opts, mpctx->x11_state, mpctx->key_fifo, mpctx->input))){
2579 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Error opening/initializing the selected video_out (-vo) device.\n");
2580 goto err_out;
2582 mpctx->initialized_flags|=INITIALIZED_VO;
2585 if(stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_ASPECT_RATIO, &ar) != STREAM_UNSUPPORTED)
2586 mpctx->sh_video->stream_aspect = ar;
2587 current_module="init_video_filters";
2589 char* vf_arg[] = { "_oldargs_", (char*)mpctx->video_out , NULL };
2590 sh_video->vfilter = vf_open_filter(opts, NULL,"vo",vf_arg);
2592 #ifdef CONFIG_MENU
2593 if(use_menu) {
2594 char* vf_arg[] = { "_oldargs_", menu_root, NULL };
2595 vf_menu = vf_open_plugin(opts,libmenu_vfs,sh_video->vfilter,"menu",vf_arg);
2596 if(!vf_menu) {
2597 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Can't open libmenu video filter with root menu %s.\n",menu_root);
2598 use_menu = 0;
2601 if(vf_menu)
2602 sh_video->vfilter = vf_menu;
2603 #endif
2605 #ifdef CONFIG_ASS
2606 if(opts->ass_enabled) {
2607 int i;
2608 int insert = 1;
2609 if (opts->vf_settings)
2610 for (i = 0; opts->vf_settings[i].name; ++i)
2611 if (strcmp(opts->vf_settings[i].name, "ass") == 0) {
2612 insert = 0;
2613 break;
2615 if (insert) {
2616 extern vf_info_t vf_info_ass;
2617 const vf_info_t* libass_vfs[] = {&vf_info_ass, NULL};
2618 char* vf_arg[] = {"auto", "1", NULL};
2619 int retcode = 0;
2620 struct vf_instance *vf_ass = vf_open_plugin_noerr(opts, libass_vfs,
2621 sh_video->vfilter,
2622 "ass", vf_arg,
2623 &retcode);
2624 if (vf_ass)
2625 sh_video->vfilter = vf_ass;
2626 else if (retcode == -1) // vf_ass open() returns -1 if there's VO EOSD
2627 mp_msg(MSGT_CPLAYER, MSGL_V, "[ass] vf_ass not needed\n");
2628 else
2629 mp_msg(MSGT_CPLAYER,MSGL_ERR, "ASS: cannot add video filter\n");
2632 #endif
2634 sh_video->vfilter = append_filters(sh_video->vfilter, opts->vf_settings);
2636 #ifdef CONFIG_ASS
2637 if (opts->ass_enabled)
2638 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_INIT_EOSD, ass_library);
2639 #endif
2641 current_module="init_video_codec";
2643 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2644 init_best_video_codec(sh_video,video_codec_list,video_fm_list);
2645 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2647 if(!sh_video->initialized){
2648 if(!opts->fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
2649 goto err_out;
2652 mpctx->initialized_flags|=INITIALIZED_VCODEC;
2654 if (sh_video->codec)
2655 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODEC=%s\n", sh_video->codec->name);
2657 sh_video->last_pts = MP_NOPTS_VALUE;
2658 sh_video->num_buffered_pts = 0;
2659 sh_video->next_frame_time = 0;
2661 if (opts->auto_quality > 0) {
2662 // Auto quality option enabled
2663 output_quality=get_video_quality_max(sh_video);
2664 if (opts->auto_quality > output_quality)
2665 opts->auto_quality = output_quality;
2666 else
2667 output_quality = opts->auto_quality;
2668 mp_msg(MSGT_CPLAYER,MSGL_V,"AutoQ: setting quality to %d.\n",output_quality);
2669 set_video_quality(sh_video,output_quality);
2672 // ========== Init display (sh_video->disp_w*sh_video->disp_h/out_fmt) ============
2674 current_module="init_vo";
2676 return 1;
2678 err_out:
2679 mpctx->sh_video = mpctx->d_video->sh = NULL;
2680 return 0;
2683 static double update_video_nocorrect_pts(struct MPContext *mpctx)
2685 struct sh_video *sh_video = mpctx->sh_video;
2686 double frame_time = 0;
2687 struct vo *video_out = mpctx->video_out;
2688 while (1) {
2689 current_module = "filter_video";
2690 // In nocorrect-pts mode there is no way to properly time these frames
2691 if (vo_get_buffered_frame(video_out, 0) >= 0)
2692 break;
2693 if (vf_output_queued_frame(sh_video->vfilter))
2694 break;
2695 unsigned char *packet = NULL;
2696 frame_time = sh_video->next_frame_time;
2697 if (mpctx->restart_playback)
2698 frame_time = 0;
2699 int in_size = video_read_frame(sh_video, &sh_video->next_frame_time,
2700 &packet, force_fps);
2701 if (in_size < 0) {
2702 #ifdef CONFIG_DVDNAV
2703 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
2704 if (mp_dvdnav_is_eof(mpctx->stream))
2705 return -1;
2706 if (mpctx->d_video)
2707 mpctx->d_video->eof = 0;
2708 if (mpctx->d_audio)
2709 mpctx->d_audio->eof = 0;
2710 mpctx->stream->eof = 0;
2711 } else
2712 #endif
2713 return -1;
2715 if (in_size > max_framesize)
2716 max_framesize = in_size;
2717 sh_video->timer += frame_time;
2718 if (mpctx->sh_audio)
2719 mpctx->delay -= frame_time;
2720 // video_read_frame can change fps (e.g. for ASF video)
2721 vo_fps = sh_video->fps;
2722 int framedrop_type = check_framedrop(mpctx, frame_time);
2723 current_module = "decode video";
2725 void *decoded_frame;
2726 #ifdef CONFIG_DVDNAV
2727 decoded_frame = mp_dvdnav_restore_smpi(mpctx, &in_size, &packet, NULL);
2728 if (in_size >= 0 && !decoded_frame)
2729 #endif
2730 decoded_frame = decode_video(sh_video, packet, in_size, framedrop_type,
2731 sh_video->pts);
2732 #ifdef CONFIG_DVDNAV
2733 // Save last still frame for future display
2734 mp_dvdnav_save_smpi(mpctx, in_size, packet, decoded_frame);
2735 #endif
2736 if (decoded_frame) {
2737 current_module = "filter video";
2738 filter_video(sh_video, decoded_frame, sh_video->pts);
2740 break;
2742 return frame_time;
2745 static void determine_frame_pts(struct MPContext *mpctx)
2747 struct sh_video *sh_video = mpctx->sh_video;
2748 struct MPOpts *opts = &mpctx->opts;
2750 if (opts->user_pts_assoc_mode) {
2751 sh_video->pts_assoc_mode = opts->user_pts_assoc_mode;
2752 } else if (sh_video->pts_assoc_mode == 0) {
2753 if (mpctx->d_video->demuxer->timestamp_type == TIMESTAMP_TYPE_PTS
2754 && sh_video->codec_reordered_pts != MP_NOPTS_VALUE)
2755 sh_video->pts_assoc_mode = 1;
2756 else
2757 sh_video->pts_assoc_mode = 2;
2758 } else {
2759 int probcount1 = sh_video->num_reordered_pts_problems;
2760 int probcount2 = sh_video->num_sorted_pts_problems;
2761 if (sh_video->pts_assoc_mode == 2) {
2762 int tmp = probcount1;
2763 probcount1 = probcount2;
2764 probcount2 = tmp;
2766 if (probcount1 >= probcount2 * 1.5 + 2) {
2767 sh_video->pts_assoc_mode = 3 - sh_video->pts_assoc_mode;
2768 mp_msg(MSGT_CPLAYER, MSGL_V, "Switching to pts association mode "
2769 "%d.\n", sh_video->pts_assoc_mode);
2772 sh_video->pts = sh_video->pts_assoc_mode == 1 ?
2773 sh_video->codec_reordered_pts : sh_video->sorted_pts;
2776 static double update_video(struct MPContext *mpctx)
2778 struct sh_video *sh_video = mpctx->sh_video;
2779 struct vo *video_out = mpctx->video_out;
2780 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_SET_OSD_OBJ,
2781 mpctx->osd); // hack for vf_expand
2782 if (!mpctx->opts.correct_pts)
2783 return update_video_nocorrect_pts(mpctx);
2785 double pts;
2787 while (1) {
2788 current_module = "filter_video";
2789 if (!mpctx->hrseek_active
2790 && vo_get_buffered_frame(video_out, false) >= 0)
2791 break;
2792 // XXX Time used in this call is not counted in any performance
2793 // timer now
2794 if (vf_output_queued_frame(sh_video->vfilter))
2795 break;
2796 unsigned char *packet = NULL;
2797 int in_size = ds_get_packet_pts(mpctx->d_video, &packet, &pts);
2798 if (pts != MP_NOPTS_VALUE)
2799 pts += mpctx->video_offset;
2800 bool hit_eof = false;
2801 if (in_size < 0) {
2802 // try to extract last frames in case of decoder lag
2803 in_size = 0;
2804 pts = MP_NOPTS_VALUE;
2805 hit_eof = true;
2807 if (in_size > max_framesize)
2808 max_framesize = in_size;
2809 current_module = "decode video";
2810 if (pts >= mpctx->hrseek_pts - .005)
2811 mpctx->hrseek_framedrop = false;
2812 int framedrop_type = mpctx->hrseek_framedrop ? 1 :
2813 check_framedrop(mpctx, sh_video->frametime);
2814 void *decoded_frame = decode_video(sh_video, packet, in_size,
2815 framedrop_type, pts);
2816 if (decoded_frame) {
2817 determine_frame_pts(mpctx);
2818 current_module = "filter video";
2819 filter_video(sh_video, decoded_frame, sh_video->pts);
2820 } else if (hit_eof) {
2821 if (vo_get_buffered_frame(video_out, true) < 0)
2822 return -1;
2824 break;
2827 if (!video_out->frame_loaded)
2828 return 0;
2830 pts = video_out->next_pts;
2831 if (pts == MP_NOPTS_VALUE) {
2832 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Video pts after filters MISSING\n");
2833 // Try to use decoder pts from before filters
2834 pts = sh_video->pts;
2835 if (pts == MP_NOPTS_VALUE)
2836 pts = sh_video->last_pts;
2838 if (mpctx->hrseek_active && pts < mpctx->hrseek_pts - .005) {
2839 vo_skip_frame(video_out);
2840 return 0;
2842 mpctx->hrseek_active = false;
2843 sh_video->pts = pts;
2844 if (sh_video->last_pts == MP_NOPTS_VALUE)
2845 sh_video->last_pts = sh_video->pts;
2846 else if (sh_video->last_pts > sh_video->pts) {
2847 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Decreasing video pts: %f < %f\n",
2848 sh_video->pts, sh_video->last_pts);
2849 /* If the difference in pts is small treat it as jitter around the
2850 * right value (possibly caused by incorrect timestamp ordering) and
2851 * just show this frame immediately after the last one.
2852 * Treat bigger differences as timestamp resets and start counting
2853 * timing of later frames from the position of this one. */
2854 if (sh_video->last_pts - sh_video->pts > 0.5)
2855 sh_video->last_pts = sh_video->pts;
2856 else
2857 sh_video->pts = sh_video->last_pts;
2859 double frame_time = sh_video->pts - sh_video->last_pts;
2860 sh_video->last_pts = sh_video->pts;
2861 sh_video->timer += frame_time;
2862 if (mpctx->sh_audio)
2863 mpctx->delay -= frame_time;
2864 return frame_time;
2867 void pause_player(struct MPContext *mpctx)
2869 if (mpctx->paused)
2870 return;
2871 mpctx->paused = 1;
2872 mpctx->step_frames = 0;
2873 mpctx->time_frame -= get_relative_time(mpctx);
2875 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2876 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2878 if (mpctx->ao && mpctx->sh_audio)
2879 ao_pause(mpctx->ao); // pause audio, keep data if possible
2882 void unpause_player(struct MPContext *mpctx)
2884 if (!mpctx->paused)
2885 return;
2886 mpctx->paused = 0;
2888 if (mpctx->ao && mpctx->sh_audio)
2889 ao_resume(mpctx->ao);
2890 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok
2891 && !mpctx->step_frames)
2892 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL); // resume video
2893 (void)get_relative_time(mpctx); // ignore time that passed during pause
2896 void add_step_frame(struct MPContext *mpctx)
2898 mpctx->step_frames++;
2899 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2900 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2901 unpause_player(mpctx);
2904 static void pause_loop(struct MPContext *mpctx)
2906 struct MPOpts *opts = &mpctx->opts;
2907 mp_cmd_t* cmd;
2908 #ifdef CONFIG_STREAM_CACHE
2909 int old_cache_fill = stream_cache_size > 0 ?
2910 cache_fill_status(mpctx->stream) : 0;
2911 #endif
2912 if (!opts->quiet) {
2913 if (opts->term_osd && !mpctx->sh_video) {
2914 set_osd_tmsg(OSD_MSG_PAUSE, 1, 0, " ===== PAUSE =====");
2915 update_osd_msg(mpctx);
2916 } else
2917 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "\n%s\r",
2918 mp_gtext(" ===== PAUSE ====="));
2919 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_PAUSED\n");
2922 while ( (cmd = mp_input_get_cmd(mpctx->input, 20, 1)) == NULL
2923 || cmd->id == MP_CMD_SET_MOUSE_POS || cmd->pausing == 4) {
2924 if (cmd) {
2925 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
2926 run_command(mpctx, cmd);
2927 mp_cmd_free(cmd);
2928 continue;
2930 if (mpctx->sh_video && mpctx->video_out)
2931 vo_check_events(mpctx->video_out);
2932 #ifdef CONFIG_MENU
2933 if (vf_menu)
2934 vf_menu_pause_update(vf_menu);
2935 #endif
2936 usec_sleep(20000);
2937 update_osd_msg(mpctx);
2938 int hack = vo_osd_changed(0);
2939 vo_osd_changed(hack);
2940 if (hack)
2941 break;
2942 #ifdef CONFIG_STREAM_CACHE
2943 if (!opts->quiet && stream_cache_size > 0) {
2944 int new_cache_fill = cache_fill_status(mpctx->stream);
2945 if (new_cache_fill != old_cache_fill) {
2946 if (opts->term_osd && !mpctx->sh_video) {
2947 set_osd_tmsg(OSD_MSG_PAUSE, 1, 0, "%s %d%%",
2948 mp_gtext(" ===== PAUSE ====="),
2949 new_cache_fill);
2950 update_osd_msg(mpctx);
2951 } else
2952 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "%s %d%%\r",
2953 mp_gtext(" ===== PAUSE ====="),
2954 new_cache_fill);
2955 old_cache_fill = new_cache_fill;
2958 #endif
2963 // Find the right mute status and record position for new file position
2964 static void edl_seek_reset(MPContext *mpctx)
2966 mpctx->edl_muted = 0;
2967 next_edl_record = edl_records;
2969 while (next_edl_record) {
2970 if (next_edl_record->start_sec >= get_current_time(mpctx))
2971 break;
2973 if (next_edl_record->action == EDL_MUTE)
2974 mpctx->edl_muted = !mpctx->edl_muted;
2975 next_edl_record = next_edl_record->next;
2977 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2978 mixer_mute(&mpctx->mixer);
2982 // Execute EDL command for the current position if one exists
2983 static void edl_update(MPContext *mpctx)
2985 if (!next_edl_record)
2986 return;
2988 if (!mpctx->sh_video) {
2989 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot use EDL without video, disabling.\n");
2990 free_edl(edl_records);
2991 next_edl_record = NULL;
2992 edl_records = NULL;
2993 return;
2996 if (get_current_time(mpctx) >= next_edl_record->start_sec) {
2997 if (next_edl_record->action == EDL_SKIP) {
2998 mpctx->osd_function = OSD_FFW;
2999 queue_seek(mpctx, MPSEEK_RELATIVE, next_edl_record->length_sec, 0);
3000 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_SKIP: start [%f], stop "
3001 "[%f], length [%f]\n", next_edl_record->start_sec,
3002 next_edl_record->stop_sec, next_edl_record->length_sec);
3004 else if (next_edl_record->action == EDL_MUTE) {
3005 mpctx->edl_muted = !mpctx->edl_muted;
3006 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
3007 mixer_mute(&mpctx->mixer);
3008 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_MUTE: [%f]\n",
3009 next_edl_record->start_sec );
3011 next_edl_record = next_edl_record->next;
3015 static void reinit_decoders(struct MPContext *mpctx)
3017 reinit_video_chain(mpctx);
3018 reinit_audio_chain(mpctx);
3019 mp_property_do("sub", M_PROPERTY_SET, &(int){mpctx->global_sub_pos}, mpctx);
3022 static void seek_reset(struct MPContext *mpctx, bool reset_ao)
3024 if (mpctx->sh_video) {
3025 current_module = "seek_video_reset";
3026 resync_video_stream(mpctx->sh_video);
3027 mpctx->sh_video->timer = 0;
3028 vo_seek_reset(mpctx->video_out);
3029 mpctx->sh_video->timer = 0;
3030 mpctx->sh_video->num_buffered_pts = 0;
3031 mpctx->sh_video->last_pts = MP_NOPTS_VALUE;
3032 mpctx->delay = 0;
3033 mpctx->time_frame = 0;
3034 mpctx->restart_playback = true;
3035 // Not all demuxers set d_video->pts during seek, so this value
3036 // (which is used by at least vobsub and edl code below) may
3037 // be completely wrong (probably 0).
3038 mpctx->sh_video->pts = mpctx->d_video->pts + mpctx->video_offset;
3039 mpctx->video_pts = mpctx->sh_video->pts;
3040 update_subtitles(mpctx, mpctx->sh_video->pts, mpctx->video_offset,
3041 true);
3042 update_teletext(mpctx->sh_video, mpctx->demuxer, 1);
3045 if (mpctx->sh_audio) {
3046 current_module = "seek_audio_reset";
3047 resync_audio_stream(mpctx->sh_audio);
3048 if (reset_ao)
3049 // stop audio, throwing away buffered data
3050 ao_reset(mpctx->ao);
3051 mpctx->sh_audio->a_buffer_len = 0;
3052 mpctx->sh_audio->a_out_buffer_len = 0;
3053 if (!mpctx->sh_video)
3054 update_subtitles(mpctx, mpctx->sh_audio->pts,
3055 mpctx->video_offset, true);
3058 if (vo_vobsub && mpctx->sh_video) {
3059 current_module = "seek_vobsub_reset";
3060 vobsub_seek(vo_vobsub, mpctx->sh_video->pts);
3063 edl_seek_reset(mpctx);
3065 mpctx->hrseek_active = false;
3066 mpctx->hrseek_framedrop = false;
3067 mpctx->total_avsync_change = 0;
3068 audio_time_usage = 0; video_time_usage = 0; vout_time_usage = 0;
3069 drop_frame_cnt = 0;
3071 current_module = NULL;
3074 static bool timeline_set_part(struct MPContext *mpctx, int i)
3076 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
3077 struct timeline_part *n = mpctx->timeline + i;
3078 mpctx->timeline_part = i;
3079 mpctx->video_offset = n->start - n->source_start;
3080 if (n->source == p->source)
3081 return false;
3082 enum stop_play_reason orig_stop_play = mpctx->stop_play;
3083 if (!mpctx->sh_video && mpctx->stop_play == KEEP_PLAYING)
3084 mpctx->stop_play = AT_END_OF_FILE; // let audio uninit drain data
3085 uninit_player(mpctx, INITIALIZED_VCODEC | (mpctx->opts.fixed_vo ? 0 : INITIALIZED_VO) | (mpctx->opts.gapless_audio ? 0 : INITIALIZED_AO) | INITIALIZED_ACODEC | INITIALIZED_SUB);
3086 mpctx->stop_play = orig_stop_play;
3087 mpctx->demuxer = n->source->demuxer;
3088 mpctx->d_video = mpctx->demuxer->video;
3089 mpctx->d_audio = mpctx->demuxer->audio;
3090 mpctx->d_sub = mpctx->demuxer->sub;
3091 mpctx->sh_video = mpctx->d_video->sh;
3092 mpctx->sh_audio = mpctx->d_audio->sh;
3093 return true;
3096 // Given pts, switch playback to the corresponding part.
3097 // Return offset within that part.
3098 static double timeline_set_from_time(struct MPContext *mpctx, double pts,
3099 bool *need_reset)
3101 if (pts < 0)
3102 pts = 0;
3103 for (int i = 0; i < mpctx->num_timeline_parts; i++) {
3104 struct timeline_part *p = mpctx->timeline + i;
3105 if (pts < (p+1)->start) {
3106 *need_reset = timeline_set_part(mpctx, i);
3107 return pts - p->start + p->source_start;
3110 return -1;
3114 // return -1 if seek failed (non-seekable stream?), 0 otherwise
3115 static int seek(MPContext *mpctx, struct seek_params seek,
3116 bool timeline_fallthrough)
3118 struct MPOpts *opts = &mpctx->opts;
3120 current_module = "seek";
3121 if (mpctx->stop_play == AT_END_OF_FILE)
3122 mpctx->stop_play = KEEP_PLAYING;
3123 bool hr_seek = mpctx->demuxer->accurate_seek && opts->correct_pts;
3124 hr_seek &= seek.exact >= 0 && seek.type != MPSEEK_FACTOR;
3125 hr_seek &= opts->hr_seek == 0 && seek.type == MPSEEK_ABSOLUTE
3126 || opts->hr_seek > 0 || seek.exact > 0;
3127 if (seek.type == MPSEEK_FACTOR
3128 || seek.type == MPSEEK_ABSOLUTE
3129 && seek.amount < mpctx->last_chapter_pts
3130 || seek.amount < 0)
3131 mpctx->last_chapter_seek = -1;
3132 if (mpctx->timeline && seek.type == MPSEEK_FACTOR) {
3133 seek.amount *= mpctx->timeline[mpctx->num_timeline_parts].start;
3134 seek.type = MPSEEK_ABSOLUTE;
3136 if ((mpctx->demuxer->accurate_seek || mpctx->timeline)
3137 && seek.type == MPSEEK_RELATIVE) {
3138 seek.type = MPSEEK_ABSOLUTE;
3139 seek.direction = seek.amount > 0 ? 1 : -1;
3140 seek.amount += get_current_time(mpctx);
3143 /* At least the liba52 decoder wants to read from the input stream
3144 * during initialization, so reinit must be done after the demux_seek()
3145 * call that clears possible stream EOF. */
3146 bool need_reset = false;
3147 double demuxer_amount = seek.amount;
3148 if (mpctx->timeline) {
3149 demuxer_amount = timeline_set_from_time(mpctx, seek.amount,
3150 &need_reset);
3151 if (demuxer_amount == -1) {
3152 mpctx->stop_play = AT_END_OF_FILE;
3153 // Clear audio from current position
3154 if (mpctx->sh_audio) {
3155 ao_reset(mpctx->ao);
3156 mpctx->sh_audio->a_buffer_len = 0;
3157 mpctx->sh_audio->a_out_buffer_len = 0;
3159 return -1;
3162 int demuxer_style = 0;
3163 switch (seek.type) {
3164 case MPSEEK_FACTOR:
3165 demuxer_style |= SEEK_FACTOR; // fallthrough
3166 case MPSEEK_ABSOLUTE:
3167 demuxer_style |= SEEK_ABSOLUTE;
3169 if (hr_seek || seek.direction < 0)
3170 demuxer_style |= SEEK_BACKWARD;
3171 else if (seek.direction > 0)
3172 demuxer_style |= SEEK_FORWARD;
3174 int seekresult = demux_seek(mpctx->demuxer, demuxer_amount, audio_delay,
3175 demuxer_style);
3176 if (need_reset)
3177 reinit_decoders(mpctx);
3178 if (seekresult == 0)
3179 return -1;
3181 seek_reset(mpctx, !timeline_fallthrough);
3183 /* Use the target time as "current position" for further relative
3184 * seeks etc until a new video frame has been decoded */
3185 if (seek.type == MPSEEK_ABSOLUTE)
3186 mpctx->video_pts = seek.amount;
3188 if (hr_seek) {
3189 mpctx->hrseek_active = true;
3190 mpctx->hrseek_framedrop = true;
3191 mpctx->hrseek_pts = seek.amount;
3194 mpctx->start_timestamp = GetTimerMS();
3196 return 0;
3199 void queue_seek(struct MPContext *mpctx, enum seek_type type, double amount,
3200 int exact)
3202 struct seek_params *seek = &mpctx->seek;
3203 switch (type) {
3204 case MPSEEK_RELATIVE:
3205 if (seek->type == MPSEEK_FACTOR)
3206 return; // Well... not common enough to bother doing better
3207 seek->amount += amount;
3208 seek->exact = FFMAX(seek->exact, exact);
3209 if (seek->type == MPSEEK_NONE)
3210 seek->exact = exact;
3211 if (seek->type == MPSEEK_ABSOLUTE)
3212 return;
3213 if (seek->amount == 0) {
3214 *seek = (struct seek_params){0};
3215 return;
3217 seek->type = MPSEEK_RELATIVE;
3218 return;
3219 case MPSEEK_ABSOLUTE:
3220 case MPSEEK_FACTOR:
3221 *seek = (struct seek_params) {
3222 .type = type,
3223 .amount = amount,
3224 .exact = exact,
3226 return;
3227 case MPSEEK_NONE:
3228 *seek = (struct seek_params){0};
3229 return;
3231 abort();
3235 double get_time_length(struct MPContext *mpctx)
3237 if (mpctx->timeline)
3238 return mpctx->timeline[mpctx->num_timeline_parts].start;
3240 struct demuxer *demuxer = mpctx->demuxer;
3241 double get_time_ans;
3242 // <= 0 means DEMUXER_CTRL_NOTIMPL or DEMUXER_CTRL_DONTKNOW
3243 if (demux_control(demuxer, DEMUXER_CTRL_GET_TIME_LENGTH,
3244 (void *) &get_time_ans) > 0)
3245 return get_time_ans;
3247 struct sh_video *sh_video = mpctx->d_video->sh;
3248 struct sh_audio *sh_audio = mpctx->d_audio->sh;
3249 if (sh_video && sh_video->i_bps && sh_audio && sh_audio->i_bps)
3250 return (double) (demuxer->movi_end - demuxer->movi_start) /
3251 (sh_video->i_bps + sh_audio->i_bps);
3252 if (sh_video && sh_video->i_bps)
3253 return (double) (demuxer->movi_end - demuxer->movi_start) /
3254 sh_video->i_bps;
3255 if (sh_audio && sh_audio->i_bps)
3256 return (double) (demuxer->movi_end - demuxer->movi_start) /
3257 sh_audio->i_bps;
3258 return 0;
3261 /* If there are timestamps from stream level then use those (for example
3262 * DVDs can have consistent times there while the MPEG-level timestamps
3263 * reset). */
3264 double get_current_time(struct MPContext *mpctx)
3266 struct demuxer *demuxer = mpctx->demuxer;
3267 if (demuxer->stream_pts != MP_NOPTS_VALUE)
3268 return demuxer->stream_pts;
3269 struct sh_video *sh_video = demuxer->video->sh;
3270 if (sh_video)
3271 return mpctx->video_pts;
3272 return playing_audio_pts(mpctx);
3275 int get_percent_pos(struct MPContext *mpctx)
3277 struct demuxer *demuxer = mpctx->demuxer;
3278 int ans = 0;
3279 if (mpctx->timeline)
3280 ans = get_current_time(mpctx) * 100 /
3281 mpctx->timeline[mpctx->num_timeline_parts].start;
3282 else if (demux_control(demuxer, DEMUXER_CTRL_GET_PERCENT_POS, &ans) > 0)
3284 else {
3285 int len = (demuxer->movi_end - demuxer->movi_start) / 100;
3286 off_t pos = demuxer->filepos > 0 ?
3287 demuxer->filepos : stream_tell(demuxer->stream);
3288 if (len > 0)
3289 ans = (pos - demuxer->movi_start) / len;
3290 else
3291 ans = 0;
3293 if (ans < 0)
3294 ans = 0;
3295 if (ans > 100)
3296 ans = 100;
3297 return ans;
3300 // -2 is no chapters, -1 is before first chapter
3301 int get_current_chapter(struct MPContext *mpctx)
3303 double current_pts = get_current_time(mpctx);
3304 if (!mpctx->chapters)
3305 return FFMAX(mpctx->last_chapter_seek,
3306 demuxer_get_current_chapter(mpctx->demuxer, current_pts));
3308 int i;
3309 for (i = 1; i < mpctx->num_chapters; i++)
3310 if (current_pts < mpctx->chapters[i].start)
3311 break;
3312 return FFMAX(mpctx->last_chapter_seek, i - 1);
3315 // currently returns a string allocated with malloc, not talloc
3316 char *chapter_display_name(struct MPContext *mpctx, int chapter)
3318 if (!mpctx->chapters || !mpctx->sh_video)
3319 return demuxer_chapter_display_name(mpctx->demuxer, chapter);
3320 return strdup(mpctx->chapters[chapter].name);
3323 int seek_chapter(struct MPContext *mpctx, int chapter, double *seek_pts,
3324 char **chapter_name)
3326 mpctx->last_chapter_seek = -1;
3327 if (!mpctx->chapters || !mpctx->sh_video) {
3328 int res = demuxer_seek_chapter(mpctx->demuxer, chapter, seek_pts,
3329 chapter_name);
3330 if (res >= 0) {
3331 if (*seek_pts == -1)
3332 seek_reset(mpctx, true);
3333 else {
3334 mpctx->last_chapter_seek = res;
3335 mpctx->last_chapter_pts = *seek_pts;
3338 return res;
3341 if (chapter >= mpctx->num_chapters)
3342 return -1;
3343 if (chapter < 0)
3344 chapter = 0;
3345 *seek_pts = mpctx->chapters[chapter].start;
3346 mpctx->last_chapter_seek = chapter;
3347 mpctx->last_chapter_pts = *seek_pts;
3348 if (chapter_name)
3349 *chapter_name = talloc_strdup(NULL, mpctx->chapters[chapter].name);
3350 return chapter;
3354 static void run_playloop(struct MPContext *mpctx)
3356 struct MPOpts *opts = &mpctx->opts;
3357 float aq_sleep_time = 0;
3358 bool full_audio_buffers = false;
3360 if (opts->chapterrange[1] > 0) {
3361 int cur_chapter = get_current_chapter(mpctx);
3362 if (cur_chapter!=-1 && cur_chapter + 1 > opts->chapterrange[1])
3363 mpctx->stop_play = PT_NEXT_ENTRY;
3366 if (!mpctx->sh_audio && mpctx->d_audio->sh) {
3367 mpctx->sh_audio = mpctx->d_audio->sh;
3368 mpctx->sh_audio->ds = mpctx->d_audio;
3369 reinit_audio_chain(mpctx);
3372 /*========================== PLAY AUDIO ============================*/
3374 if (mpctx->sh_audio && !mpctx->paused
3375 && (!mpctx->restart_playback || !mpctx->sh_video)) {
3376 int status = fill_audio_out_buffers(mpctx);
3377 full_audio_buffers = status >= 0 && !mpctx->ao->untimed;
3378 if (status == -2)
3379 // at eof, all audio at least written to ao
3380 if (!mpctx->sh_video)
3381 mpctx->stop_play = AT_END_OF_FILE;
3385 if (!mpctx->sh_video) {
3386 mpctx->restart_playback = false;
3387 if (mpctx->step_frames) {
3388 mpctx->step_frames = 0;
3389 pause_player(mpctx);
3391 // handle audio-only case:
3392 double a_pos = 0, a_buf = 0;
3393 // sh_audio can be NULL due to video stream switching
3394 // TODO: handle this better
3395 if (mpctx->sh_audio) {
3396 a_buf = ao_get_delay(mpctx->ao);
3397 a_pos = written_audio_pts(mpctx) - mpctx->opts.playback_speed *
3398 a_buf;
3401 print_status(mpctx, a_pos, false);
3403 update_subtitles(mpctx, a_pos, mpctx->video_offset, false);
3404 update_osd_msg(mpctx);
3405 if (end_at.type == END_AT_TIME && end_at.pos < a_pos) {
3406 mpctx->stop_play = AT_END_OF_FILE;
3407 } else if (mpctx->timeline && mpctx->stop_play == AT_END_OF_FILE
3408 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts
3409 && mpctx->sh_audio) {
3410 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
3411 if (!opts->gapless_audio && p->source != (p+1)->source
3412 && a_buf > 0.05) {
3413 mpctx->stop_play = KEEP_PLAYING;
3414 mp_input_get_cmd(mpctx->input, (a_buf-.05) * 1000, true);
3415 } else {
3416 seek(mpctx, (struct seek_params){ .type = MPSEEK_ABSOLUTE,
3417 .amount = (p+1)->start },
3418 true);
3420 } else if (!mpctx->stop_play) {
3421 int sleep_time = 100;
3422 if (mpctx->sh_audio) {
3423 if (mpctx->ao->untimed)
3424 sleep_time = 0;
3425 else if (full_audio_buffers)
3426 sleep_time = FFMAX(20, a_buf * 1000 - 50);
3427 else
3428 sleep_time = 20;
3429 sleep_time = FFMIN(sleep_time, 100);
3431 mp_input_get_cmd(mpctx->input, sleep_time, true);
3433 } else {
3435 /*========================== PLAY VIDEO ============================*/
3437 vo_pts = mpctx->sh_video->timer * 90000.0;
3438 vo_fps = mpctx->sh_video->fps;
3440 bool blit_frame = mpctx->video_out->frame_loaded;
3441 if (!blit_frame || mpctx->hrseek_active) {
3442 double frame_time = update_video(mpctx);
3443 blit_frame = mpctx->video_out->frame_loaded;
3444 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "*** ftime=%5.3f ***\n", frame_time);
3445 if (mpctx->sh_video->vf_initialized < 0) {
3446 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
3447 "\nFATAL: Could not initialize video filters (-vf) "
3448 "or video output (-vo).\n");
3449 mpctx->stop_play = PT_NEXT_ENTRY;
3450 return;
3452 if (frame_time < 0)
3453 mpctx->stop_play = AT_END_OF_FILE;
3454 else if (!mpctx->restart_playback) {
3455 mpctx->time_frame += frame_time / opts->playback_speed;
3456 adjust_sync(mpctx, frame_time);
3459 if (mpctx->timeline) {
3460 struct timeline_part *next =
3461 mpctx->timeline + mpctx->timeline_part + 1;
3462 if (mpctx->sh_video->pts >= next->start
3463 || mpctx->stop_play == AT_END_OF_FILE
3464 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts) {
3465 seek(mpctx, (struct seek_params){ .type = MPSEEK_ABSOLUTE,
3466 .amount = next->start },
3467 true);
3468 return;
3472 // ==========================================================================
3474 current_module = "vo_check_events";
3475 vo_check_events(mpctx->video_out);
3477 #ifdef CONFIG_X11
3478 if (stop_xscreensaver) {
3479 current_module = "stop_xscreensaver";
3480 xscreensaver_heartbeat(mpctx->x11_state);
3482 #endif
3483 if (heartbeat_cmd) {
3484 static unsigned last_heartbeat;
3485 unsigned now = GetTimerMS();
3486 if (now - last_heartbeat > 30000) {
3487 last_heartbeat = now;
3488 system(heartbeat_cmd);
3492 bool frame_time_remaining = sleep_until_near_frame(mpctx,
3493 &mpctx->time_frame,
3494 full_audio_buffers,
3495 &aq_sleep_time);
3497 //====================== FLIP PAGE (VIDEO BLT): =========================
3499 current_module = "flip_page";
3500 if (!frame_time_remaining && blit_frame) {
3501 struct sh_video *sh_video = mpctx->sh_video;
3502 mpctx->video_pts = sh_video->pts;
3503 update_subtitles(mpctx, sh_video->pts, mpctx->video_offset, false);
3504 update_teletext(sh_video, mpctx->demuxer, 0);
3505 update_osd_msg(mpctx);
3506 struct vf_instance *vf = sh_video->vfilter;
3507 vf->control(vf, VFCTRL_DRAW_EOSD, mpctx->osd);
3508 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
3509 vo_osd_changed(0);
3511 mpctx->time_frame -= mpctx->video_out->flip_queue_offset;
3512 aq_sleep_time += mpctx->time_frame;
3513 // flag 256 means: libvo driver does its timing (dvb card)
3514 if (mpctx->time_frame > 0.001
3515 && !(mpctx->sh_video->output_flags & VFCAP_TIMER))
3516 mpctx->time_frame = timing_sleep(mpctx, mpctx->time_frame);
3517 mpctx->time_frame += mpctx->video_out->flip_queue_offset;
3519 unsigned int t2 = GetTimer();
3520 /* Playing with playback speed it's possible to get pathological
3521 * cases with mpctx->time_frame negative enough to cause an
3522 * overflow in pts_us calculation, thus the FFMAX. */
3523 double time_frame = FFMAX(mpctx->time_frame, -1);
3524 unsigned int pts_us = mpctx->last_time + time_frame * 1e6;
3525 int duration = -1;
3526 double pts2 = mpctx->video_out->next_pts2;
3527 if (pts2 != MP_NOPTS_VALUE && opts->correct_pts
3528 && !mpctx->restart_playback) {
3529 // expected A/V sync correction is ignored
3530 double diff = (pts2 - mpctx->video_pts);
3531 diff /= opts->playback_speed;
3532 if (mpctx->time_frame < 0)
3533 diff += mpctx->time_frame;
3534 if (diff < 0)
3535 diff = 0;
3536 if (diff > 10)
3537 diff = 10;
3538 duration = diff * 1e6;
3540 vo_flip_page(mpctx->video_out, pts_us | 1, duration);
3542 mpctx->last_vo_flip_duration = (GetTimer() - t2) * 0.000001;
3543 vout_time_usage += mpctx->last_vo_flip_duration;
3544 if (mpctx->video_out->driver->flip_page_timed) {
3545 // No need to adjust sync based on flip speed
3546 mpctx->last_vo_flip_duration = 0;
3547 // For print_status - VO call finishing early is OK for sync
3548 mpctx->time_frame -= get_relative_time(mpctx);
3550 if (mpctx->restart_playback) {
3551 mpctx->syncing_audio = true;
3552 if (mpctx->sh_audio && !mpctx->paused)
3553 fill_audio_out_buffers(mpctx);
3554 mpctx->restart_playback = false;
3555 mpctx->time_frame = 0;
3556 get_relative_time(mpctx);
3558 print_status(mpctx, MP_NOPTS_VALUE, true);
3559 } else
3560 print_status(mpctx, MP_NOPTS_VALUE, false);
3562 //============================ Auto QUALITY ============================
3564 /*Output quality adjustments:*/
3565 if (opts->auto_quality > 0) {
3566 current_module = "autoq";
3567 if (output_quality < opts->auto_quality && aq_sleep_time > 0)
3568 ++output_quality;
3569 else
3570 if (output_quality>1 && aq_sleep_time<0)
3571 --output_quality;
3572 else if (output_quality>0 && aq_sleep_time<-0.050f) // 50ms
3573 output_quality = 0;
3574 set_video_quality(mpctx->sh_video, output_quality);
3577 if (!frame_time_remaining && blit_frame) {
3578 if (play_n_frames >= 0) {
3579 --play_n_frames;
3580 if (play_n_frames <= 0)
3581 mpctx->stop_play = PT_NEXT_ENTRY;
3583 if (mpctx->step_frames > 0) {
3584 mpctx->step_frames--;
3585 if (mpctx->step_frames == 0)
3586 pause_player(mpctx);
3590 // FIXME: add size based support for -endpos
3591 if (end_at.type == END_AT_TIME &&
3592 !frame_time_remaining && end_at.pos <= mpctx->sh_video->pts)
3593 mpctx->stop_play = PT_NEXT_ENTRY;
3595 } // end if(mpctx->sh_video)
3597 #ifdef CONFIG_DVDNAV
3598 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
3599 nav_highlight_t hl;
3600 mp_dvdnav_get_highlight(mpctx->stream, &hl);
3601 if (!vo_spudec || !spudec_apply_palette_crop(vo_spudec, hl.palette, hl.sx, hl.sy, hl.ex, hl.ey)) {
3602 osd_set_nav_box(hl.sx, hl.sy, hl.ex, hl.ey);
3603 vo_osd_changed(OSDTYPE_DVDNAV);
3604 } else {
3605 osd_set_nav_box(0, 0, 0, 0);
3606 vo_osd_changed(OSDTYPE_DVDNAV);
3607 vo_osd_changed(OSDTYPE_SPU);
3610 if (mp_dvdnav_stream_has_changed(mpctx->stream)) {
3611 double ar = -1.0;
3612 if (mpctx->sh_video &&
3613 stream_control(mpctx->demuxer->stream,
3614 STREAM_CTRL_GET_ASPECT_RATIO, &ar)
3615 != STREAM_UNSUPPORTED)
3616 mpctx->sh_video->stream_aspect = ar;
3619 #endif
3621 //================= Keyboard events, SEEKing ====================
3623 current_module = "key_events";
3625 while (1) {
3626 mp_cmd_t *cmd;
3627 while ((cmd = mp_input_get_cmd(mpctx->input, 0, 1)) != NULL) {
3628 /* Allow running consecutive seek commands to combine them,
3629 * but execute the seek before running other commands.
3630 * If the user seeks continuously (keeps arrow key down)
3631 * try to finish showing a frame from one location before doing
3632 * another seek (which could lead to unchanging display). */
3633 if (mpctx->seek.type && cmd->id != MP_CMD_SEEK
3634 || mpctx->restart_playback && cmd->id == MP_CMD_SEEK
3635 && GetTimerMS() - mpctx->start_timestamp < 300)
3636 break;
3637 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
3638 run_command(mpctx, cmd);
3639 mp_cmd_free(cmd);
3640 if (mpctx->stop_play)
3641 break;
3643 if (!mpctx->paused || mpctx->stop_play || mpctx->seek.type
3644 || mpctx->restart_playback)
3645 break;
3646 if (mpctx->sh_video) {
3647 update_osd_msg(mpctx);
3648 int hack = vo_osd_changed(0);
3649 vo_osd_changed(hack);
3650 if (hack) {
3651 if (redraw_osd(mpctx->sh_video, mpctx->osd) < 0) {
3652 add_step_frame(mpctx);
3653 break;
3654 } else
3655 vo_osd_changed(0);
3658 pause_loop(mpctx);
3661 // handle -sstep
3662 if (step_sec > 0 && !mpctx->paused) {
3663 mpctx->osd_function = OSD_FFW;
3664 queue_seek(mpctx, MPSEEK_RELATIVE, step_sec, 0);
3667 edl_update(mpctx);
3669 /* Looping. */
3670 if (mpctx->stop_play==AT_END_OF_FILE && opts->loop_times>=0) {
3671 mp_msg(MSGT_CPLAYER, MSGL_V, "loop_times = %d\n", opts->loop_times);
3673 if (opts->loop_times>1)
3674 opts->loop_times--;
3675 else if (opts->loop_times==1)
3676 opts->loop_times = -1;
3677 play_n_frames = play_n_frames_mf;
3678 mpctx->stop_play = 0;
3679 queue_seek(mpctx, MPSEEK_ABSOLUTE, 0, 0);
3682 if (mpctx->seek.type) {
3683 seek(mpctx, mpctx->seek, false);
3684 mpctx->seek = (struct seek_params){0};
3689 static int read_keys(void *ctx, int fd)
3691 getch2(ctx);
3692 return mplayer_get_key(ctx, 0);
3695 static bool attachment_is_font(struct demux_attachment *att)
3697 if (!att->name || !att->type || !att->data || !att->data_size)
3698 return false;
3699 // match against MIME types
3700 if (strcmp(att->type, "application/x-truetype-font") == 0
3701 || strcmp(att->type, "application/x-font") == 0)
3702 return true;
3703 // fallback: match against file extension
3704 if (strlen(att->name) > 4) {
3705 char *ext = att->name + strlen(att->name) - 4;
3706 if (strcasecmp(ext, ".ttf") == 0 || strcasecmp(ext, ".ttc") == 0
3707 || strcasecmp(ext, ".otf") == 0)
3708 return true;
3710 return false;
3713 static int select_audio(demuxer_t *demuxer, int audio_id, char **audio_lang)
3715 if (audio_id == -1)
3716 audio_id = demuxer_audio_track_by_lang_and_default(demuxer, audio_lang);
3717 if (audio_id != -1) // -1 (automatic) is the default behaviour of demuxers
3718 demuxer_switch_audio(demuxer, audio_id);
3719 if (audio_id == -2) { // some demuxers don't yet know how to switch to no sound
3720 demuxer->audio->id = -2;
3721 demuxer->audio->sh = NULL;
3723 return demuxer->audio->id;
3726 static void print_version(const char* name)
3728 mp_msg(MSGT_CPLAYER, MSGL_INFO, MP_TITLE, name);
3730 /* Test for CPU capabilities (and corresponding OS support) for optimizing */
3731 GetCpuCaps(&gCpuCaps);
3732 #if ARCH_X86
3733 mp_msg(MSGT_CPLAYER, MSGL_V,
3734 "CPUflags: MMX: %d MMX2: %d 3DNow: %d 3DNowExt: %d SSE: %d SSE2: %d SSSE3: %d\n",
3735 gCpuCaps.hasMMX, gCpuCaps.hasMMX2,
3736 gCpuCaps.has3DNow, gCpuCaps.has3DNowExt,
3737 gCpuCaps.hasSSE, gCpuCaps.hasSSE2, gCpuCaps.hasSSSE3);
3738 #if CONFIG_RUNTIME_CPUDETECT
3739 mp_tmsg(MSGT_CPLAYER,MSGL_V, "Compiled with runtime CPU detection.\n");
3740 #else
3741 mp_tmsg(MSGT_CPLAYER,MSGL_V, "Compiled for x86 CPU with extensions:");
3742 if (HAVE_MMX)
3743 mp_msg(MSGT_CPLAYER,MSGL_V," MMX");
3744 if (HAVE_MMX2)
3745 mp_msg(MSGT_CPLAYER,MSGL_V," MMX2");
3746 if (HAVE_AMD3DNOW)
3747 mp_msg(MSGT_CPLAYER,MSGL_V," 3DNow");
3748 if (HAVE_AMD3DNOWEXT)
3749 mp_msg(MSGT_CPLAYER,MSGL_V," 3DNowExt");
3750 if (HAVE_SSE)
3751 mp_msg(MSGT_CPLAYER,MSGL_V," SSE");
3752 if (HAVE_SSE2)
3753 mp_msg(MSGT_CPLAYER,MSGL_V," SSE2");
3754 if (HAVE_SSSE3)
3755 mp_msg(MSGT_CPLAYER,MSGL_V," SSSE3");
3756 if (HAVE_CMOV)
3757 mp_msg(MSGT_CPLAYER,MSGL_V," CMOV");
3758 mp_msg(MSGT_CPLAYER,MSGL_V,"\n");
3759 #endif /* CONFIG_RUNTIME_CPUDETECT */
3760 #endif /* ARCH_X86 */
3763 #ifdef PTW32_STATIC_LIB
3764 static void detach_ptw32(void)
3766 pthread_win32_thread_detach_np();
3767 pthread_win32_process_detach_np();
3769 #endif
3771 /* This preprocessor directive is a hack to generate a mplayer-nomain.o object
3772 * file for some tools to link against. */
3773 #ifndef DISABLE_MAIN
3774 int main(int argc,char* argv[]){
3775 #ifdef PTW32_STATIC_LIB
3776 pthread_win32_process_attach_np();
3777 pthread_win32_thread_attach_np();
3778 atexit(detach_ptw32);
3779 #endif
3780 if (argc > 1 && !strcmp(argv[1], "-leak-report"))
3781 talloc_enable_leak_report();
3783 char * mem_ptr;
3785 // movie info:
3787 /* Flag indicating whether MPlayer should exit without playing anything. */
3788 int opt_exit = 0;
3789 int i;
3791 struct MPContext *mpctx = &(struct MPContext){
3792 .osd_function = OSD_PLAY,
3793 .begin_skip = MP_NOPTS_VALUE,
3794 .play_tree_step = 1,
3795 .global_sub_pos = -1,
3796 .set_of_sub_pos = -1,
3797 .file_format = DEMUXER_TYPE_UNKNOWN,
3798 .last_dvb_step = 1,
3801 InitTimer();
3802 srand(GetTimerMS());
3804 mp_msg_init();
3805 set_av_log_callback();
3807 #ifdef CONFIG_X11
3808 mpctx->x11_state = vo_x11_init_state();
3809 #endif
3810 struct MPOpts *opts = &mpctx->opts;
3811 set_default_mplayer_options(opts);
3812 // Create the config context and register the options
3813 mpctx->mconfig = m_config_new(opts, cfg_include);
3814 m_config_register_options(mpctx->mconfig,mplayer_opts);
3815 m_config_register_options(mpctx->mconfig, common_opts);
3816 mp_input_register_options(mpctx->mconfig);
3818 // Preparse the command line
3819 m_config_preparse_command_line(mpctx->mconfig,argc,argv);
3821 #if (defined(__MINGW32__) || defined(__CYGWIN__)) && defined(CONFIG_WIN32DLL)
3822 set_path_env();
3823 #endif
3825 #ifdef CONFIG_TV
3826 stream_tv_defaults.immediate = 1;
3827 #endif
3829 parse_cfgfiles(mpctx, mpctx->mconfig);
3831 mpctx->playtree = m_config_parse_mp_command_line(mpctx->mconfig, argc, argv);
3832 if(mpctx->playtree == NULL)
3833 opt_exit = 1;
3834 else {
3835 mpctx->playtree = play_tree_cleanup(mpctx->playtree);
3836 if(mpctx->playtree) {
3837 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,mpctx->mconfig);
3838 if(mpctx->playtree_iter) {
3839 if(play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
3840 play_tree_iter_free(mpctx->playtree_iter);
3841 mpctx->playtree_iter = NULL;
3843 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,1);
3847 mpctx->key_fifo = mp_fifo_create(opts);
3849 print_version("MPlayer2");
3851 #if defined(__MINGW32__) || defined(__CYGWIN__)
3853 HMODULE kernel32 = GetModuleHandle("Kernel32.dll");
3854 BOOL WINAPI (*setDEP)(DWORD) = NULL;
3855 BOOL WINAPI (*setDllDir)(LPCTSTR) = NULL;
3856 if (kernel32) {
3857 setDEP = GetProcAddress(kernel32, "SetProcessDEPPolicy");
3858 setDllDir = GetProcAddress(kernel32, "SetDllDirectoryA");
3860 if (setDEP) setDEP(3);
3861 if (setDllDir) setDllDir("");
3863 // stop Windows from showing all kinds of annoying error dialogs
3864 SetErrorMode(0x8003);
3865 // request 1ms timer resolution
3866 timeBeginPeriod(1);
3867 #endif
3869 #ifdef CONFIG_PRIORITY
3870 set_priority();
3871 #endif
3873 if (codec_path)
3874 set_codec_path(codec_path);
3876 if(opts->video_driver_list && strcmp(opts->video_driver_list[0],"help")==0){
3877 list_video_out();
3878 opt_exit = 1;
3881 if(opts->audio_driver_list && strcmp(opts->audio_driver_list[0],"help")==0){
3882 list_audio_out();
3883 opt_exit = 1;
3886 /* Check codecs.conf. */
3887 if(!codecs_file || !parse_codec_cfg(codecs_file)){
3888 if(!parse_codec_cfg(mem_ptr=get_path("codecs.conf"))){
3889 if(!parse_codec_cfg(MPLAYER_CONFDIR "/codecs.conf")){
3890 if(!parse_codec_cfg(NULL)){
3891 exit_player_with_rc(mpctx, EXIT_NONE, 0);
3893 mp_tmsg(MSGT_CPLAYER,MSGL_V,"Using built-in default codecs.conf.\n");
3896 free( mem_ptr ); // release the buffer created by get_path()
3899 if(audio_codec_list && strcmp(audio_codec_list[0],"help")==0){
3900 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available audio codecs:\n");
3901 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AUDIO_CODECS\n");
3902 list_codecs(1);
3903 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3904 opt_exit = 1;
3906 if(video_codec_list && strcmp(video_codec_list[0],"help")==0){
3907 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available video codecs:\n");
3908 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODECS\n");
3909 list_codecs(0);
3910 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3911 opt_exit = 1;
3913 if(video_fm_list && strcmp(video_fm_list[0],"help")==0){
3914 vfm_help();
3915 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3916 opt_exit = 1;
3918 if(audio_fm_list && strcmp(audio_fm_list[0],"help")==0){
3919 afm_help();
3920 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3921 opt_exit = 1;
3923 if(af_cfg.list && strcmp(af_cfg.list[0],"help")==0){
3924 af_help();
3925 printf("\n");
3926 opt_exit = 1;
3928 #ifdef CONFIG_X11
3929 if(vo_fstype_list && strcmp(vo_fstype_list[0],"help")==0){
3930 fstype_help();
3931 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3932 opt_exit = 1;
3934 #endif
3935 if((opts->demuxer_name && strcmp(opts->demuxer_name,"help")==0) ||
3936 (opts->audio_demuxer_name && strcmp(opts->audio_demuxer_name,"help")==0) ||
3937 (opts->sub_demuxer_name && strcmp(opts->sub_demuxer_name,"help")==0)){
3938 demuxer_help();
3939 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
3940 opt_exit = 1;
3942 if (opts->list_properties) {
3943 property_print_help();
3944 opt_exit = 1;
3947 if(opt_exit)
3948 exit_player(mpctx, EXIT_NONE);
3950 if (!mpctx->filename && !opts->player_idle_mode) {
3951 // no file/vcd/dvd -> show HELP:
3952 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", mp_gtext(help_text));
3953 exit_player_with_rc(mpctx, EXIT_NONE, 0);
3956 /* Display what configure line was used */
3957 mp_msg(MSGT_CPLAYER, MSGL_V, "Configuration: " CONFIGURATION "\n");
3959 // Many users forget to include command line in bugreports...
3960 if( mp_msg_test(MSGT_CPLAYER,MSGL_V) ){
3961 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "CommandLine:");
3962 for(i=1;i<argc;i++)mp_msg(MSGT_CPLAYER, MSGL_INFO," '%s'",argv[i]);
3963 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
3966 //------ load global data first ------
3968 mpctx->osd = osd_create();
3970 // check font
3971 #ifdef CONFIG_FREETYPE
3972 init_freetype();
3973 #endif
3974 #ifdef CONFIG_FONTCONFIG
3975 if(font_fontconfig <= 0)
3977 #endif
3978 #ifdef CONFIG_BITMAP_FONT
3979 if(font_name){
3980 vo_font=read_font_desc(font_name,font_factor,verbose>1);
3981 if(!vo_font) mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load bitmap font: %s\n",
3982 filename_recode(font_name));
3983 } else {
3984 // try default:
3985 vo_font=read_font_desc( mem_ptr=get_path("font/font.desc"),font_factor,verbose>1);
3986 free(mem_ptr); // release the buffer created by get_path()
3987 if(!vo_font)
3988 vo_font=read_font_desc(MPLAYER_DATADIR "/font/font.desc",font_factor,verbose>1);
3990 if (sub_font_name)
3991 mpctx->osd->sub_font = read_font_desc(sub_font_name, font_factor, verbose>1);
3992 else
3993 mpctx->osd->sub_font = vo_font;
3994 #endif
3995 #ifdef CONFIG_FONTCONFIG
3997 #endif
3999 #ifdef CONFIG_ASS
4000 ass_library = mp_ass_init();
4001 #endif
4003 #ifdef HAVE_RTC
4004 if(opts->rtc)
4006 char *rtc_device = opts->rtc_device;
4007 // seteuid(0); /* Can't hurt to try to get root here */
4008 if ((rtc_fd = open(rtc_device ? rtc_device : "/dev/rtc", O_RDONLY)) < 0)
4009 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Failed to open %s: %s (it should be readable by the user.)\n",
4010 rtc_device ? rtc_device : "/dev/rtc", strerror(errno));
4011 else {
4012 unsigned long irqp = 1024; /* 512 seemed OK. 128 is jerky. */
4014 if (ioctl(rtc_fd, RTC_IRQP_SET, irqp) < 0) {
4015 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Linux RTC init error in ioctl (rtc_irqp_set %lu): %s\n", irqp, strerror(errno));
4016 mp_tmsg(MSGT_CPLAYER, MSGL_HINT, "Try adding \"echo %lu > /proc/sys/dev/rtc/max-user-freq\" to your system startup scripts.\n", irqp);
4017 close (rtc_fd);
4018 rtc_fd = -1;
4019 } else if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
4020 /* variable only by the root */
4021 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC init error in ioctl (rtc_pie_on): %s\n", strerror(errno));
4022 close (rtc_fd);
4023 rtc_fd = -1;
4024 } else
4025 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Using Linux hardware RTC timing (%ldHz).\n", irqp);
4028 if(rtc_fd<0)
4029 #endif /* HAVE_RTC */
4030 mp_msg(MSGT_CPLAYER, MSGL_V, "Using %s timing\n",
4031 opts->softsleep ? "software" : timer_name);
4033 #ifdef HAVE_TERMCAP
4034 load_termcap(NULL); // load key-codes
4035 #endif
4037 // ========== Init keyboard FIFO (connection to libvo) ============
4039 // Init input system
4040 current_module = "init_input";
4041 mpctx->input = mp_input_init(&opts->input);
4042 mp_input_add_key_fd(mpctx->input, -1,0,mplayer_get_key,NULL, mpctx->key_fifo);
4043 if(slave_mode) {
4044 #if USE_FD0_CMD_SELECT
4045 int flags = fcntl(0, F_GETFL);
4046 if (flags != -1)
4047 fcntl(0, F_SETFL, flags | O_NONBLOCK);
4048 #endif
4049 mp_input_add_cmd_fd(mpctx->input, 0,USE_FD0_CMD_SELECT,MP_INPUT_SLAVE_CMD_FUNC,NULL);
4051 else if (opts->consolecontrols)
4052 mp_input_add_key_fd(mpctx->input, 0, 1, read_keys, NULL, mpctx->key_fifo);
4053 // Set the libstream interrupt callback
4054 stream_set_interrupt_callback(mp_input_check_interrupt, mpctx->input);
4056 #ifdef CONFIG_MENU
4057 if(use_menu) {
4058 if(menu_cfg && menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
4059 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
4060 else {
4061 menu_cfg = get_path("menu.conf");
4062 if(menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
4063 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
4064 else {
4065 if(menu_init(mpctx, mpctx->mconfig, mpctx->input,
4066 MPLAYER_CONFDIR "/menu.conf"))
4067 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", MPLAYER_CONFDIR"/menu.conf");
4068 else {
4069 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Menu init failed.\n");
4070 use_menu = 0;
4075 #endif
4077 current_module = NULL;
4079 /// Catch signals
4080 #ifndef __MINGW32__
4081 signal(SIGCHLD,child_sighandler);
4082 #endif
4084 #ifdef CONFIG_CRASH_DEBUG
4085 prog_path = argv[0];
4086 #endif
4087 //========= Catch terminate signals: ================
4088 // terminate requests:
4089 signal(SIGTERM,exit_sighandler); // kill
4090 signal(SIGHUP,exit_sighandler); // kill -HUP / xterm closed
4092 signal(SIGINT,exit_sighandler); // Interrupt from keyboard
4094 signal(SIGQUIT,exit_sighandler); // Quit from keyboard
4095 signal(SIGPIPE,exit_sighandler); // Some window managers cause this
4096 #ifdef CONFIG_SIGHANDLER
4097 // fatal errors:
4098 signal(SIGBUS,exit_sighandler); // bus error
4099 signal(SIGSEGV,exit_sighandler); // segfault
4100 signal(SIGILL,exit_sighandler); // illegal instruction
4101 signal(SIGFPE,exit_sighandler); // floating point exc.
4102 signal(SIGABRT,exit_sighandler); // abort()
4103 #ifdef CONFIG_CRASH_DEBUG
4104 if (crash_debug)
4105 signal(SIGTRAP,exit_sighandler);
4106 #endif
4107 #endif
4109 // ******************* Now, let's see the per-file stuff ********************
4111 play_next_file:
4113 // init global sub numbers
4114 mpctx->global_sub_size = 0;
4115 memset(mpctx->sub_counts, 0, sizeof(mpctx->sub_counts));
4117 if (mpctx->filename) {
4118 load_per_protocol_config (mpctx->mconfig, mpctx->filename);
4119 load_per_extension_config (mpctx->mconfig, mpctx->filename);
4120 load_per_file_config (mpctx->mconfig, mpctx->filename);
4123 if (opts->video_driver_list)
4124 load_per_output_config (mpctx->mconfig, PROFILE_CFG_VO, opts->video_driver_list[0]);
4125 if (opts->audio_driver_list)
4126 load_per_output_config (mpctx->mconfig, PROFILE_CFG_AO, opts->audio_driver_list[0]);
4128 // We must enable getch2 here to be able to interrupt network connection
4129 // or cache filling
4130 if (opts->consolecontrols && !slave_mode) {
4131 if(mpctx->initialized_flags&INITIALIZED_GETCH2)
4132 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"WARNING: getch2_init called twice!\n");
4133 else
4134 getch2_enable(); // prepare stdin for hotkeys...
4135 mpctx->initialized_flags|=INITIALIZED_GETCH2;
4136 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[init getch2]]]\n");
4139 // =================== GUI idle loop (STOP state) ===========================
4140 while (opts->player_idle_mode && !mpctx->filename) {
4141 play_tree_t * entry = NULL;
4142 mp_cmd_t * cmd;
4143 if (mpctx->video_out && mpctx->video_out->config_ok)
4144 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
4145 while (!(cmd = mp_input_get_cmd(mpctx->input, 0, 0))) { // wait for command
4146 if (mpctx->video_out)
4147 vo_check_events(mpctx->video_out);
4148 usec_sleep(20000);
4150 switch (cmd->id) {
4151 case MP_CMD_LOADFILE:
4152 // prepare a tree entry with the new filename
4153 entry = play_tree_new();
4154 play_tree_add_file(entry, cmd->args[0].v.s);
4155 // The entry is added to the main playtree after the switch().
4156 break;
4157 case MP_CMD_LOADLIST:
4158 entry = parse_playlist_file(mpctx->mconfig, cmd->args[0].v.s);
4159 break;
4160 case MP_CMD_QUIT:
4161 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
4162 break;
4163 case MP_CMD_VO_FULLSCREEN:
4164 case MP_CMD_GET_PROPERTY:
4165 case MP_CMD_SET_PROPERTY:
4166 case MP_CMD_STEP_PROPERTY:
4167 run_command(mpctx, cmd);
4168 break;
4171 mp_cmd_free(cmd);
4173 if (entry) { // user entered a command that gave a valid entry
4174 if (mpctx->playtree) // the playtree is always a node with one child. let's clear it
4175 play_tree_free_list(mpctx->playtree->child, 1);
4176 else mpctx->playtree=play_tree_new(); // .. or make a brand new playtree
4178 if (!mpctx->playtree) continue; // couldn't make playtree! wait for next command
4180 play_tree_set_child(mpctx->playtree, entry);
4182 /* Make iterator start at the top the of tree. */
4183 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree, mpctx->mconfig);
4184 if (!mpctx->playtree_iter) continue;
4186 // find the first real item in the tree
4187 if (play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
4188 // no items!
4189 play_tree_iter_free(mpctx->playtree_iter);
4190 mpctx->playtree_iter = NULL;
4191 continue; // wait for next command
4193 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, 1);
4196 //---------------------------------------------------------------------------
4198 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
4199 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL);
4201 if (mpctx->filename) {
4202 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nPlaying %s.\n",
4203 filename_recode(mpctx->filename));
4204 if(use_filename_title && opts->vo_wintitle == NULL)
4205 opts->vo_wintitle = strdup(mp_basename(mpctx->filename));
4208 if (edl_filename) {
4209 if (edl_records) free_edl(edl_records);
4210 next_edl_record = edl_records = edl_parse_file();
4212 if (edl_output_filename) {
4213 if (edl_fd) fclose(edl_fd);
4214 if ((edl_fd = fopen(edl_output_filename, "w")) == NULL)
4216 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Can't open EDL file [%s] for writing.\n",
4217 filename_recode(edl_output_filename));
4221 //==================== Open VOB-Sub ============================
4223 current_module="vobsub";
4224 if (opts->vobsub_name){
4225 vo_vobsub=vobsub_open(opts->vobsub_name,spudec_ifo,1,&vo_spudec);
4226 if(vo_vobsub==NULL)
4227 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load subtitles: %s\n",
4228 filename_recode(opts->vobsub_name));
4229 } else if (opts->sub_auto && mpctx->filename){
4230 char **vob = find_vob_subtitles(opts, mpctx->filename);
4231 for (int i = 0; i < MP_TALLOC_ELEMS(vob); i++) {
4232 vo_vobsub = vobsub_open(vob[i], spudec_ifo, 0, &vo_spudec);
4233 if (vo_vobsub)
4234 break;
4236 talloc_free(vob);
4238 if(vo_vobsub){
4239 mpctx->initialized_flags|=INITIALIZED_VOBSUB;
4240 vobsub_set_from_lang(vo_vobsub, opts->sub_lang);
4241 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
4243 // setup global sub numbering
4244 mpctx->sub_counts[SUB_SOURCE_VOBSUB] = vobsub_get_indexes_count(vo_vobsub);
4247 //============ Open & Sync STREAM --- fork cache2 ====================
4249 mpctx->stream=NULL;
4250 mpctx->demuxer=NULL;
4251 mpctx->d_audio=NULL;
4252 mpctx->d_video=NULL;
4253 mpctx->d_sub = NULL;
4254 mpctx->sh_audio=NULL;
4255 mpctx->sh_video=NULL;
4257 current_module="open_stream";
4258 mpctx->stream = open_stream(mpctx->filename, opts, &mpctx->file_format);
4259 if(!mpctx->stream) { // error...
4260 mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY);
4261 goto goto_next_file;
4263 mpctx->initialized_flags|=INITIALIZED_STREAM;
4265 if(mpctx->file_format == DEMUXER_TYPE_PLAYLIST) {
4266 mp_msg(MSGT_CPLAYER, MSGL_ERR, "\nThis looks like a playlist, but "
4267 "playlist support will not be used automatically.\n"
4268 "MPlayer's playlist code is unsafe and should only be used with "
4269 "trusted sources.\nPlayback will probably fail.\n\n");
4270 #if 0
4271 play_tree_t* entry;
4272 // Handle playlist
4273 current_module="handle_playlist";
4274 mp_msg(MSGT_CPLAYER,MSGL_V,"Parsing playlist %s...\n",
4275 filename_recode(mpctx->filename));
4276 entry = parse_playtree(mpctx->stream, mpctx->mconfig, 0);
4277 mpctx->eof=playtree_add_playlist(mpctx, entry);
4278 goto goto_next_file;
4279 #endif
4281 mpctx->stream->start_pos+=seek_to_byte;
4283 if(stream_dump_type==5){
4284 unsigned char buf[4096];
4285 int len;
4286 FILE *f;
4287 current_module="dumpstream";
4288 stream_reset(mpctx->stream);
4289 stream_seek(mpctx->stream,mpctx->stream->start_pos);
4290 f=fopen(opts->stream_dump_name,"wb");
4291 if(!f){
4292 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
4293 exit_player(mpctx, EXIT_ERROR);
4295 if (opts->chapterrange[0] > 1) {
4296 int chapter = opts->chapterrange[0] - 1;
4297 stream_control(mpctx->stream, STREAM_CTRL_SEEK_TO_CHAPTER, &chapter);
4299 while(!mpctx->stream->eof && !async_quit_request){
4300 len=stream_read(mpctx->stream,buf,4096);
4301 if(len>0) {
4302 if(fwrite(buf,len,1,f) != 1) {
4303 mp_tmsg(MSGT_GLOBAL,MSGL_FATAL,"%s: Error writing file.\n",opts->stream_dump_name);
4304 exit_player(mpctx, EXIT_ERROR);
4307 if (opts->chapterrange[1] > 0) {
4308 int chapter = -1;
4309 if (stream_control(mpctx->stream, STREAM_CTRL_GET_CURRENT_CHAPTER,
4310 &chapter) == STREAM_OK
4311 && chapter + 1 > opts->chapterrange[1])
4312 break;
4315 if(fclose(f)) {
4316 mp_tmsg(MSGT_GLOBAL,MSGL_FATAL,"%s: Error writing file.\n",opts->stream_dump_name);
4317 exit_player(mpctx, EXIT_ERROR);
4319 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Stream dump complete.\n");
4320 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4323 #ifdef CONFIG_DVDREAD
4324 if(mpctx->stream->type==STREAMTYPE_DVD){
4325 current_module="dvd lang->id";
4326 if(opts->audio_lang && opts->audio_id==-1) opts->audio_id=dvd_aid_from_lang(mpctx->stream,opts->audio_lang);
4327 if(opts->sub_lang && opts->sub_id==-1) opts->sub_id=dvd_sid_from_lang(mpctx->stream,opts->sub_lang);
4328 // setup global sub numbering
4329 mpctx->sub_counts[SUB_SOURCE_DEMUX] = dvd_number_of_subs(mpctx->stream);
4330 current_module=NULL;
4332 #endif
4334 #ifdef CONFIG_DVDNAV
4335 if(mpctx->stream->type==STREAMTYPE_DVDNAV){
4336 current_module="dvdnav lang->id";
4337 if(opts->audio_lang && opts->audio_id==-1) opts->audio_id=mp_dvdnav_aid_from_lang(mpctx->stream,opts->audio_lang);
4338 dvdsub_lang_id = -3;
4339 if(opts->sub_lang && opts->sub_id==-1)
4340 dvdsub_lang_id = opts->sub_id = mp_dvdnav_sid_from_lang(mpctx->stream,opts->sub_lang);
4341 // setup global sub numbering
4342 mpctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(mpctx->stream);
4343 current_module=NULL;
4345 #endif
4347 // CACHE2: initial prefill: 20% later: 5% (should be set by -cacheopts)
4348 goto_enable_cache:
4349 if(stream_cache_size>0){
4350 int res;
4351 float stream_cache_min_percent = opts->stream_cache_min_percent;
4352 float stream_cache_seek_min_percent = opts->stream_cache_seek_min_percent;
4353 current_module="enable_cache";
4354 res = stream_enable_cache(mpctx->stream,stream_cache_size*1024,
4355 stream_cache_size*1024*(stream_cache_min_percent / 100.0),
4356 stream_cache_size*1024*(stream_cache_seek_min_percent / 100.0));
4357 if(res == 0)
4358 if((mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY))) goto goto_next_file;
4361 //============ Open DEMUXERS --- DETECT file type =======================
4362 current_module="demux_open";
4364 mpctx->demuxer=demux_open(opts, mpctx->stream,mpctx->file_format,opts->audio_id,opts->video_id,opts->sub_id,mpctx->filename);
4366 // HACK to get MOV Reference Files working
4368 if (mpctx->demuxer && mpctx->demuxer->type==DEMUXER_TYPE_PLAYLIST)
4370 unsigned char* playlist_entry;
4371 play_tree_t *list = NULL, *entry = NULL;
4373 current_module="handle_demux_playlist";
4374 while (ds_get_packet(mpctx->demuxer->video,&playlist_entry)>0)
4376 char *temp;
4377 const char *bname;
4379 mp_msg(MSGT_CPLAYER,MSGL_V,"Adding file %s to element entry.\n",
4380 filename_recode(playlist_entry));
4382 bname=mp_basename(playlist_entry);
4383 if ((strlen(bname)>10) && !strncmp(bname,"qt",2) && !strncmp(bname+3,"gateQT",6))
4384 continue;
4386 if (!strcmp(playlist_entry, mpctx->filename)) // ignoring self-reference
4387 continue;
4389 entry = play_tree_new();
4391 if (mpctx->filename && !strcmp(mp_basename(playlist_entry),playlist_entry)) // add reference path of current file
4393 temp=malloc((strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))+strlen(playlist_entry)+1));
4394 if (temp)
4396 strncpy(temp, mpctx->filename, strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename)));
4397 temp[strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))]='\0';
4398 strcat(temp, playlist_entry);
4399 if (!strcmp(temp, mpctx->filename)) {
4400 free(temp);
4401 continue;
4403 play_tree_add_file(entry,temp);
4404 mp_msg(MSGT_CPLAYER,MSGL_V,"Resolving reference to %s.\n",temp);
4405 free(temp);
4408 else
4409 play_tree_add_file(entry,playlist_entry);
4411 if(!list)
4412 list = entry;
4413 else
4414 play_tree_append_entry(list,entry);
4416 free_demuxer(mpctx->demuxer);
4417 mpctx->demuxer = NULL;
4419 if (list)
4421 entry = play_tree_new();
4422 play_tree_set_child(entry,list);
4423 mpctx->stop_play = playtree_add_playlist(mpctx, entry);
4424 goto goto_next_file;
4428 if(!mpctx->demuxer) {
4429 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Failed to recognize file format.\n");
4430 goto goto_next_file;
4433 if (mpctx->demuxer->matroska_data.ordered_chapters)
4434 build_ordered_chapter_timeline(mpctx);
4436 if (mpctx->demuxer->type == DEMUXER_TYPE_EDL)
4437 build_edl_timeline(mpctx);
4439 if (mpctx->timeline) {
4440 mpctx->timeline_part = 0;
4441 mpctx->demuxer = mpctx->timeline[0].source->demuxer;
4443 int part_count = mpctx->num_timeline_parts;
4444 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline contains %d parts from %d "
4445 "sources. Total length %.3f seconds.\n", part_count,
4446 mpctx->num_sources, mpctx->timeline[part_count].start);
4447 mp_msg(MSGT_CPLAYER, MSGL_V, "Source files:\n");
4448 for (int i = 0; i < mpctx->num_sources; i++)
4449 mp_msg(MSGT_CPLAYER, MSGL_V, "%d: %s\n", i,
4450 filename_recode(mpctx->sources[i].demuxer->filename));
4451 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline parts: (number, start, "
4452 "source_start, source):\n");
4453 for (int i = 0; i < part_count; i++) {
4454 struct timeline_part *p = mpctx->timeline + i;
4455 mp_msg(MSGT_CPLAYER, MSGL_V, "%3d %9.3f %9.3f %3td\n", i, p->start,
4456 p->source_start, p->source - mpctx->sources);
4458 mp_msg(MSGT_CPLAYER, MSGL_V, "END %9.3f\n",
4459 mpctx->timeline[part_count].start);
4462 if (!mpctx->sources) {
4463 mpctx->sources = talloc_ptrtype(NULL, mpctx->sources);
4464 *mpctx->sources = (struct content_source){.stream = mpctx->stream,
4465 .demuxer = mpctx->demuxer};
4466 mpctx->num_sources = 1;
4469 mpctx->initialized_flags|=INITIALIZED_DEMUXER;
4471 #ifdef CONFIG_ASS
4472 if (opts->ass_enabled && ass_library) {
4473 for (int j = 0; j < mpctx->num_sources; j++) {
4474 struct demuxer *d = mpctx->sources[j].demuxer;
4475 for (int i = 0; i < d->num_attachments; i++) {
4476 struct demux_attachment *att = d->attachments + i;
4477 if (use_embedded_fonts && attachment_is_font(att))
4478 ass_add_font(ass_library, att->name, att->data, att->data_size);
4482 #endif
4484 current_module="demux_open2";
4486 mpctx->d_audio=mpctx->demuxer->audio;
4487 mpctx->d_video=mpctx->demuxer->video;
4488 mpctx->d_sub=mpctx->demuxer->sub;
4490 if (ts_prog) {
4491 int tmp = ts_prog;
4492 mp_property_do("switch_program", M_PROPERTY_SET, &tmp, mpctx);
4494 // select audio stream
4495 for (int i = 0; i < mpctx->num_sources; i++)
4496 select_audio(mpctx->sources[i].demuxer->audio->demuxer, opts->audio_id,
4497 opts->audio_lang);
4499 // DUMP STREAMS:
4500 if((stream_dump_type)&&(stream_dump_type<4)){
4501 FILE *f;
4502 demux_stream_t *ds=NULL;
4503 current_module="dump";
4504 // select stream to dump
4505 switch(stream_dump_type){
4506 case 1: ds=mpctx->d_audio;break;
4507 case 2: ds=mpctx->d_video;break;
4508 case 3: ds=mpctx->d_sub;break;
4510 if(!ds){
4511 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"dump: FATAL: Selected stream missing!\n");
4512 exit_player(mpctx, EXIT_ERROR);
4514 // disable other streams:
4515 if(mpctx->d_audio && mpctx->d_audio!=ds) {ds_free_packs(mpctx->d_audio); mpctx->d_audio->id=-2; }
4516 if(mpctx->d_video && mpctx->d_video!=ds) {ds_free_packs(mpctx->d_video); mpctx->d_video->id=-2; }
4517 if(mpctx->d_sub && mpctx->d_sub!=ds) {ds_free_packs(mpctx->d_sub); mpctx->d_sub->id=-2; }
4518 // let's dump it!
4519 f=fopen(opts->stream_dump_name,"wb");
4520 if(!f){
4521 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
4522 exit_player(mpctx, EXIT_ERROR);
4524 while(!ds->eof){
4525 unsigned char* start;
4526 int in_size=ds_get_packet(ds,&start);
4527 if( (mpctx->demuxer->file_format==DEMUXER_TYPE_AVI || mpctx->demuxer->file_format==DEMUXER_TYPE_ASF || mpctx->demuxer->file_format==DEMUXER_TYPE_MOV)
4528 && stream_dump_type==2) fwrite(&in_size,1,4,f);
4529 if(in_size>0) fwrite(start,in_size,1,f);
4530 if (opts->chapterrange[1] > 0) {
4531 int cur_chapter = demuxer_get_current_chapter(mpctx->demuxer, 0);
4532 if(cur_chapter!=-1 && cur_chapter+1 > opts->chapterrange[1])
4533 break;
4536 fclose(f);
4537 mp_tmsg(MSGT_CPLAYER ,MSGL_INFO, "Stream dump complete.\n");
4538 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4541 mpctx->sh_audio=mpctx->d_audio->sh;
4542 mpctx->sh_video=mpctx->d_video->sh;
4544 if(mpctx->sh_video){
4546 current_module="video_read_properties";
4547 if(!video_read_properties(mpctx->sh_video)) {
4548 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Video: Cannot read properties.\n");
4549 mpctx->sh_video=mpctx->d_video->sh=NULL;
4550 } else {
4551 mp_tmsg(MSGT_CPLAYER,MSGL_V,"[V] filefmt:%d fourcc:0x%X size:%dx%d fps:%5.3f ftime:=%6.4f\n",
4552 mpctx->demuxer->file_format,mpctx->sh_video->format, mpctx->sh_video->disp_w,mpctx->sh_video->disp_h,
4553 mpctx->sh_video->fps,mpctx->sh_video->frametime
4556 /* need to set fps here for output encoders to pick it up in their init */
4557 if(force_fps){
4558 mpctx->sh_video->fps=force_fps;
4559 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
4561 vo_fps = mpctx->sh_video->fps;
4563 if(!mpctx->sh_video->fps && !force_fps){
4564 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"FPS not specified in the header or invalid, use the -fps option.\n");
4565 mpctx->opts.correct_pts = 1;
4571 if(!mpctx->sh_video && !mpctx->sh_audio){
4572 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL, "No stream found.\n");
4573 #ifdef CONFIG_DVBIN
4574 if(mpctx->stream->type == STREAMTYPE_DVB)
4576 int dir;
4577 int v = mpctx->last_dvb_step;
4578 if(v > 0)
4579 dir = DVB_CHANNEL_HIGHER;
4580 else
4581 dir = DVB_CHANNEL_LOWER;
4583 if(dvb_step_channel(mpctx->stream, dir)) {
4584 mpctx->stop_play = PT_NEXT_ENTRY;
4585 mpctx->dvbin_reopen = 1;
4588 #endif
4589 goto goto_next_file; // exit_player(_("Fatal error"));
4592 /* display clip info */
4593 demux_info_print(mpctx->demuxer);
4595 //================== Read SUBTITLES (DVD & TEXT) ==========================
4596 if(vo_spudec==NULL &&
4597 (mpctx->stream->type==STREAMTYPE_DVD || mpctx->stream->type == STREAMTYPE_DVDNAV)){
4598 init_vo_spudec(mpctx);
4601 // after reading video params we should load subtitles because
4602 // we know fps so now we can adjust subtitle time to ~6 seconds AST
4603 // check .sub
4604 current_module="read_subtitles_file";
4605 double sub_fps = mpctx->sh_video ? mpctx->sh_video->fps : 25;
4606 if(opts->sub_name){
4607 for (i = 0; opts->sub_name[i] != NULL; ++i)
4608 add_subtitles(mpctx, opts->sub_name[i], sub_fps, 0);
4610 if(opts->sub_auto) { // auto load sub file ...
4611 char **tmp = find_text_subtitles(opts, mpctx->filename);
4612 int nsub = MP_TALLOC_ELEMS(tmp);
4613 for (int i = 0; i < nsub; i++)
4614 add_subtitles(mpctx, tmp[i], sub_fps, 1);
4615 talloc_free(tmp);
4617 if (mpctx->set_of_sub_size > 0)
4618 mpctx->sub_counts[SUB_SOURCE_SUBS] = mpctx->set_of_sub_size;
4620 if (select_subtitle(mpctx)) {
4621 if(mpctx->subdata)
4622 switch (stream_dump_type) {
4623 case 3: list_sub_file(mpctx->subdata); break;
4624 case 4: dump_mpsub(mpctx->subdata, mpctx->sh_video->fps); break;
4625 case 6: dump_srt(mpctx->subdata, mpctx->sh_video->fps); break;
4626 case 7: dump_microdvd(mpctx->subdata, mpctx->sh_video->fps); break;
4627 case 8: dump_jacosub(mpctx->subdata, mpctx->sh_video->fps); break;
4628 case 9: dump_sami(mpctx->subdata, mpctx->sh_video->fps); break;
4632 print_file_properties(mpctx, mpctx->filename);
4634 reinit_video_chain(mpctx);
4635 if (mpctx->sh_video) {
4636 if(mpctx->sh_video->output_flags & VFCAP_SPU && vo_spudec)
4637 spudec_set_hw_spu(vo_spudec,mpctx->video_out);
4638 #ifdef CONFIG_FREETYPE
4639 force_load_font = 1;
4640 #endif
4641 } else if (!mpctx->sh_audio)
4642 goto goto_next_file;
4644 //================== MAIN: ==========================
4645 current_module="main";
4647 if (opts->playing_msg) {
4648 char* msg = property_expand_string(mpctx, opts->playing_msg);
4649 mp_msg(MSGT_CPLAYER,MSGL_INFO,"%s",msg);
4650 free(msg);
4654 // Disable the term OSD in verbose mode
4655 if (verbose)
4656 opts->term_osd = 0;
4660 // Make sure old OSD does not stay around,
4661 // e.g. with -fixed-vo and same-resolution files
4662 clear_osd_msgs();
4663 update_osd_msg(mpctx);
4665 //================ SETUP AUDIO ==========================
4667 if(mpctx->sh_audio){
4668 reinit_audio_chain(mpctx);
4669 if (mpctx->sh_audio && mpctx->sh_audio->codec)
4670 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_CODEC=%s\n", mpctx->sh_audio->codec->name);
4673 current_module="av_init";
4675 if(mpctx->sh_video){
4676 mpctx->sh_video->timer=0;
4677 if (! ignore_start)
4678 audio_delay += mpctx->sh_video->stream_delay;
4680 if(mpctx->sh_audio){
4681 if (start_volume >= 0)
4682 mixer_setvolume(&mpctx->mixer, start_volume, start_volume);
4683 if (! ignore_start)
4684 audio_delay -= mpctx->sh_audio->stream_delay;
4685 mpctx->delay=-audio_delay;
4688 if(!mpctx->sh_audio){
4689 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Audio: no sound\n");
4690 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused audio chunks.\n",mpctx->d_audio->packs);
4691 ds_free_packs(mpctx->d_audio); // free buffered chunks
4692 //mpctx->d_audio->id=-2; // do not read audio chunks
4693 //uninit_player(mpctx, INITIALIZED_AO); // close device
4695 if(!mpctx->sh_video){
4696 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Video: no video\n");
4697 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused video chunks.\n",mpctx->d_video->packs);
4698 ds_free_packs(mpctx->d_video);
4699 mpctx->d_video->id=-2;
4700 //if(!fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
4703 if (!mpctx->sh_video && !mpctx->sh_audio)
4704 goto goto_next_file;
4706 //if(demuxer->file_format!=DEMUXER_TYPE_AVI) pts_from_bps=0; // it must be 0 for mpeg/asf!
4707 if(force_fps && mpctx->sh_video){
4708 vo_fps = mpctx->sh_video->fps=force_fps;
4709 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
4710 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"FPS forced to be %5.3f (ftime: %5.3f).\n",mpctx->sh_video->fps,mpctx->sh_video->frametime);
4713 mp_input_set_section(mpctx->input, NULL);
4714 //TODO: add desired (stream-based) sections here
4715 if (mpctx->stream->type==STREAMTYPE_TV) mp_input_set_section(mpctx->input, "tv");
4716 if (mpctx->stream->type==STREAMTYPE_DVDNAV) mp_input_set_section(mpctx->input, "dvdnav");
4718 //==================== START PLAYING =======================
4720 if(opts->loop_times>1) opts->loop_times--; else
4721 if(opts->loop_times==1) opts->loop_times = -1;
4723 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Starting playback...\n");
4725 total_time_usage_start=GetTimer();
4726 audio_time_usage=0; video_time_usage=0; vout_time_usage=0;
4727 total_frame_cnt=0; drop_frame_cnt=0; // fix for multifile fps benchmark
4728 play_n_frames=play_n_frames_mf;
4730 if(play_n_frames==0){
4731 mpctx->stop_play=PT_NEXT_ENTRY; goto goto_next_file;
4734 mpctx->time_frame = 0;
4735 mpctx->drop_message_shown = 0;
4736 mpctx->restart_playback = true;
4737 mpctx->video_pts = 0;
4738 mpctx->hrseek_active = false;
4739 mpctx->hrseek_framedrop = false;
4740 mpctx->step_frames = 0;
4741 mpctx->total_avsync_change = 0;
4742 mpctx->last_chapter_seek = -1;
4744 // If there's a timeline force an absolute seek to initialize state
4745 if (seek_to_sec || mpctx->timeline) {
4746 queue_seek(mpctx, MPSEEK_ABSOLUTE, seek_to_sec, 0);
4747 seek(mpctx, mpctx->seek, false);
4748 end_at.pos += seek_to_sec;
4750 if (opts->chapterrange[0] > 0) {
4751 double pts;
4752 if (seek_chapter(mpctx, opts->chapterrange[0]-1, &pts, NULL) >= 0
4753 && pts > -1.0) {
4754 queue_seek(mpctx, MPSEEK_ABSOLUTE, pts, 0);
4755 seek(mpctx, mpctx->seek, false);
4759 if (end_at.type == END_AT_SIZE) {
4760 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Option -endpos in MPlayer does not yet support size units.\n");
4761 end_at.type = END_AT_NONE;
4764 #ifdef CONFIG_DVDNAV
4765 mp_dvdnav_context_free(mpctx);
4766 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4767 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
4768 mp_dvdnav_cell_has_changed(mpctx->stream,1);
4770 #endif
4772 mpctx->seek = (struct seek_params){0};
4773 get_relative_time(mpctx); // reset current delta
4774 // Make sure VO knows current pause state
4775 if (mpctx->sh_video)
4776 vo_control(mpctx->video_out, mpctx->paused ? VOCTRL_PAUSE : VOCTRL_RESUME,
4777 NULL);
4779 while (!mpctx->stop_play)
4780 run_playloop(mpctx);
4782 mp_msg(MSGT_GLOBAL,MSGL_V,"EOF code: %d \n",mpctx->stop_play);
4784 #ifdef CONFIG_DVBIN
4785 if(mpctx->dvbin_reopen)
4787 mpctx->stop_play = 0;
4788 uninit_player(mpctx, INITIALIZED_ALL-(INITIALIZED_STREAM|INITIALIZED_GETCH2|(opts->fixed_vo?INITIALIZED_VO:0)));
4789 cache_uninit(mpctx->stream);
4790 mpctx->dvbin_reopen = 0;
4791 goto goto_enable_cache;
4793 #endif
4796 goto_next_file: // don't jump here after ao/vo/getch initialization!
4798 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\n");
4800 if (opts->benchmark) {
4801 double tot=video_time_usage+vout_time_usage+audio_time_usage;
4802 double total_time_usage;
4803 total_time_usage_start=GetTimer()-total_time_usage_start;
4804 total_time_usage = (float)total_time_usage_start*0.000001;
4805 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\nBENCHMARKs: VC:%8.3fs VO:%8.3fs A:%8.3fs Sys:%8.3fs = %8.3fs\n",
4806 video_time_usage,vout_time_usage,audio_time_usage,
4807 total_time_usage-tot,total_time_usage);
4808 if(total_time_usage>0.0)
4809 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARK%%: VC:%8.4f%% VO:%8.4f%% A:%8.4f%% Sys:%8.4f%% = %8.4f%%\n",
4810 100.0*video_time_usage/total_time_usage,
4811 100.0*vout_time_usage/total_time_usage,
4812 100.0*audio_time_usage/total_time_usage,
4813 100.0*(total_time_usage-tot)/total_time_usage,
4814 100.0);
4815 if(total_frame_cnt && frame_dropping)
4816 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARKn: disp: %d (%3.2f fps) drop: %d (%d%%) total: %d (%3.2f fps)\n",
4817 total_frame_cnt-drop_frame_cnt,
4818 (total_time_usage>0.5)?((total_frame_cnt-drop_frame_cnt)/total_time_usage):0,
4819 drop_frame_cnt,
4820 100*drop_frame_cnt/total_frame_cnt,
4821 total_frame_cnt,
4822 (total_time_usage>0.5)?(total_frame_cnt/total_time_usage):0);
4825 // time to uninit all, except global stuff:
4826 int uninitialize_parts = INITIALIZED_ALL;
4827 if (opts->fixed_vo)
4828 uninitialize_parts -= INITIALIZED_VO;
4829 if (opts->gapless_audio && mpctx->stop_play == AT_END_OF_FILE)
4830 uninitialize_parts -= INITIALIZED_AO;
4831 uninit_player(mpctx, uninitialize_parts);
4833 if(mpctx->set_of_sub_size > 0) {
4834 current_module="sub_free";
4835 for(i = 0; i < mpctx->set_of_sub_size; ++i) {
4836 sub_free(mpctx->set_of_subtitles[i]);
4837 #ifdef CONFIG_ASS
4838 if(mpctx->set_of_ass_tracks[i])
4839 ass_free_track( mpctx->set_of_ass_tracks[i] );
4840 #endif
4842 mpctx->set_of_sub_size = 0;
4844 mpctx->vo_sub_last = vo_sub=NULL;
4845 mpctx->subdata=NULL;
4846 #ifdef CONFIG_ASS
4847 mpctx->osd->ass_track = NULL;
4848 if(ass_library)
4849 ass_clear_fonts(ass_library);
4850 #endif
4852 if (!mpctx->stop_play) // In case some goto jumped here...
4853 mpctx->stop_play = PT_NEXT_ENTRY;
4855 int playtree_direction = 1;
4857 if(mpctx->stop_play == PT_NEXT_ENTRY || mpctx->stop_play == PT_PREV_ENTRY) {
4858 if(play_tree_iter_step(mpctx->playtree_iter,mpctx->play_tree_step,0) != PLAY_TREE_ITER_ENTRY) {
4859 play_tree_iter_free(mpctx->playtree_iter);
4860 mpctx->playtree_iter = NULL;
4862 mpctx->play_tree_step = 1;
4863 } else if(mpctx->stop_play == PT_UP_NEXT || mpctx->stop_play == PT_UP_PREV) {
4864 int direction = mpctx->stop_play == PT_UP_NEXT ? 1 : -1;
4865 if(mpctx->playtree_iter) {
4866 if(play_tree_iter_up_step(mpctx->playtree_iter,direction,0) != PLAY_TREE_ITER_ENTRY) {
4867 play_tree_iter_free(mpctx->playtree_iter);
4868 mpctx->playtree_iter = NULL;
4871 } else if (mpctx->stop_play == PT_STOP) {
4872 play_tree_iter_free(mpctx->playtree_iter);
4873 mpctx->playtree_iter = NULL;
4874 } else { // NEXT PREV SRC
4875 playtree_direction = mpctx->stop_play == PT_PREV_SRC ? -1 : 1;
4878 while(mpctx->playtree_iter != NULL) {
4879 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, playtree_direction);
4880 if(mpctx->filename == NULL) {
4881 if(play_tree_iter_step(mpctx->playtree_iter, playtree_direction, 0) != PLAY_TREE_ITER_ENTRY) {
4882 play_tree_iter_free(mpctx->playtree_iter);
4883 mpctx->playtree_iter = NULL;
4885 } else
4886 break;
4889 if (mpctx->playtree_iter != NULL || opts->player_idle_mode) {
4890 if(!mpctx->playtree_iter) mpctx->filename = NULL;
4891 mpctx->stop_play = 0;
4892 goto play_next_file;
4896 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4898 return 1;
4900 #endif /* DISABLE_MAIN */