ao_pcm, core: use new API in ao_pcm, change timing with it
[mplayer.git] / mplayer.c
blobaf3ad127ebae25538090a29e30372fe861ef5142
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>
27 #include "config.h"
28 #include "talloc.h"
30 #if defined(__MINGW32__) || defined(__CYGWIN__)
31 #define _UWIN 1 /*disable Non-underscored versions of non-ANSI functions as otherwise int eof would conflict with eof()*/
32 #include <windows.h>
33 #endif
34 #include <string.h>
35 #include <unistd.h>
37 // #include <sys/mman.h>
38 #include <sys/types.h>
39 #ifndef __MINGW32__
40 #include <sys/ioctl.h>
41 #include <sys/wait.h>
42 #else
43 #define SIGHUP 1 /* hangup */
44 #define SIGQUIT 3 /* quit */
45 #define SIGKILL 9 /* kill (cannot be caught or ignored) */
46 #define SIGBUS 10 /* bus error */
47 #define SIGPIPE 13 /* broken pipe */
48 #endif
50 #include <sys/time.h>
51 #include <sys/stat.h>
53 #include <signal.h>
54 #include <time.h>
55 #include <fcntl.h>
56 #include <limits.h>
58 #include <errno.h>
60 #include "mp_msg.h"
61 #include "av_log.h"
64 #include "m_option.h"
65 #include "m_config.h"
66 #include "mplayer.h"
67 #include "access_mpcontext.h"
68 #include "m_property.h"
70 #include "libavutil/avstring.h"
72 #include "sub/subreader.h"
73 #include "sub/find_subfiles.h"
74 #include "sub/dec_sub.h"
76 #include "mp_osd.h"
77 #include "libvo/video_out.h"
79 #include "sub/font_load.h"
80 #include "sub/sub.h"
81 #include "ffmpeg_files/intreadwrite.h"
82 #include "sub/av_sub.h"
83 #include "libmpcodecs/dec_teletext.h"
84 #include "cpudetect.h"
85 #include "version.h"
87 #ifdef CONFIG_X11
88 #include "libvo/x11_common.h"
89 #endif
91 #include "libao2/audio_out.h"
93 #include "codec-cfg.h"
95 #include "edl.h"
97 #include "sub/spudec.h"
98 #include "sub/vobsub.h"
100 #include "osdep/getch2.h"
101 #include "osdep/timer.h"
103 #include "input/input.h"
105 int slave_mode=0;
106 int enable_mouse_movements=0;
107 float start_volume = -1;
109 #include "osdep/priority.h"
111 char *heartbeat_cmd;
113 #ifdef HAVE_RTC
114 #ifdef __linux__
115 #include <linux/rtc.h>
116 #else
117 #include <rtc.h>
118 #define RTC_IRQP_SET RTCIO_IRQP_SET
119 #define RTC_PIE_ON RTCIO_PIE_ON
120 #endif /* __linux__ */
121 #endif /* HAVE_RTC */
123 #include "stream/tv.h"
124 #include "stream/stream_radio.h"
125 #ifdef CONFIG_DVBIN
126 #include "stream/dvbin.h"
127 #endif
128 #include "stream/cache2.h"
130 //**************************************************************************//
131 // Playtree
132 //**************************************************************************//
133 #include "playtree.h"
134 #include "playtreeparser.h"
136 //**************************************************************************//
137 // Config
138 //**************************************************************************//
139 #include "parser-cfg.h"
140 #include "parser-mpcmd.h"
142 //**************************************************************************//
143 // Config file
144 //**************************************************************************//
146 static int cfg_inc_verbose(m_option_t *conf){ ++verbose; return 0;}
148 #include "path.h"
150 //**************************************************************************//
151 //**************************************************************************//
152 // Input media streaming & demultiplexer:
153 //**************************************************************************//
155 static int max_framesize=0;
157 #include "stream/stream.h"
158 #include "libmpdemux/demuxer.h"
159 #include "libmpdemux/stheader.h"
161 #ifdef CONFIG_DVDREAD
162 #include "stream/stream_dvd.h"
163 #endif
164 #include "stream/stream_dvdnav.h"
166 #include "libmpcodecs/dec_audio.h"
167 #include "libmpcodecs/dec_video.h"
168 #include "libmpcodecs/mp_image.h"
169 #include "libmpcodecs/vf.h"
170 #include "libmpcodecs/vd.h"
172 #include "mixer.h"
174 #include "mp_core.h"
175 #include "options.h"
176 #include "defaultopts.h"
178 static const char help_text[]=_(
179 "Usage: mplayer [options] [url|path/]filename\n"
180 "\n"
181 "Basic options: (complete list in the man page)\n"
182 " -vo <drv> select video output driver ('-vo help' for a list)\n"
183 " -ao <drv> select audio output driver ('-ao help' for a list)\n"
184 #ifdef CONFIG_VCD
185 " vcd://<trackno> play (S)VCD (Super Video CD) track (raw device, no mount)\n"
186 #endif
187 #ifdef CONFIG_DVDREAD
188 " dvd://<titleno> play DVD title from device instead of plain file\n"
189 #endif
190 " -alang/-slang select DVD audio/subtitle language (by 2-char country code)\n"
191 " -ss <position> seek to given (seconds or hh:mm:ss) position\n"
192 " -nosound do not play sound\n"
193 " -fs fullscreen playback (or -vm, -zoom, details in the man page)\n"
194 " -x <x> -y <y> set display resolution (for use with -vm or -zoom)\n"
195 " -sub <file> specify subtitle file to use (also see -subfps, -subdelay)\n"
196 " -playlist <file> specify playlist file\n"
197 " -vid x -aid y select video (x) and audio (y) stream to play\n"
198 " -fps x -srate y change video (x fps) and audio (y Hz) rate\n"
199 " -pp <quality> enable postprocessing filter (details in the man page)\n"
200 " -framedrop enable frame dropping (for slow machines)\n"
201 "\n"
202 "Basic keys: (complete list in the man page, also check input.conf)\n"
203 " <- or -> seek backward/forward 10 seconds\n"
204 " down or up seek backward/forward 1 minute\n"
205 " pgdown or pgup seek backward/forward 10 minutes\n"
206 " < or > step backward/forward in playlist\n"
207 " p or SPACE pause movie (press any key to continue)\n"
208 " q or ESC stop playing and quit program\n"
209 " + or - adjust audio delay by +/- 0.1 second\n"
210 " o cycle OSD mode: none / seekbar / seekbar + timer\n"
211 " * or / increase or decrease PCM volume\n"
212 " x or z adjust subtitle delay by +/- 0.1 second\n"
213 " r or t adjust subtitle position up/down, also see -vf expand\n"
214 "\n"
215 " * * * SEE THE MAN PAGE FOR DETAILS, FURTHER (ADVANCED) OPTIONS AND KEYS * * *\n"
216 "\n");
219 #define Exit_SIGILL_RTCpuSel _(\
220 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
221 " It may be a bug in our new runtime CPU-detection code...\n"\
222 " Please read DOCS/HTML/en/bugreports.html.\n")
224 #define Exit_SIGILL _(\
225 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
226 " It usually happens when you run it on a CPU different than the one it was\n"\
227 " compiled/optimized for.\n"\
228 " Verify this!\n")
230 #define Exit_SIGSEGV_SIGFPE _(\
231 "- MPlayer crashed by bad usage of CPU/FPU/RAM.\n"\
232 " Recompile MPlayer with --enable-debug and make a 'gdb' backtrace and\n"\
233 " disassembly. Details in DOCS/HTML/en/bugreports_what.html#bugreports_crash.\n")
235 #define Exit_SIGCRASH _(\
236 "- MPlayer crashed. This shouldn't happen.\n"\
237 " It can be a bug in the MPlayer code _or_ in your drivers _or_ in your\n"\
238 " gcc version. If you think it's MPlayer's fault, please read\n"\
239 " DOCS/HTML/en/bugreports.html and follow the instructions there. We can't and\n"\
240 " won't help unless you provide this information when reporting a possible bug.\n")
242 #define SystemTooSlow _("\n\n"\
243 " ************************************************\n"\
244 " **** Your system is too SLOW to play this! ****\n"\
245 " ************************************************\n\n"\
246 "Possible reasons, problems, workarounds:\n"\
247 "- Most common: broken/buggy _audio_ driver\n"\
248 " - Try -ao sdl or use the OSS emulation of ALSA.\n"\
249 " - Experiment with different values for -autosync, 30 is a good start.\n"\
250 "- Slow video output\n"\
251 " - Try a different -vo driver (-vo help for a list) or try -framedrop!\n"\
252 "- Slow CPU\n"\
253 " - Don't try to play a big DVD/DivX on a slow CPU! Try some of the lavdopts,\n"\
254 " e.g. -vfm ffmpeg -lavdopts lowres=1:fast:skiploopfilter=all.\n"\
255 "- Broken file\n"\
256 " - Try various combinations of -nobps -ni -forceidx -mc 0.\n"\
257 "- Slow media (NFS/SMB mounts, DVD, VCD etc)\n"\
258 " - Try -cache 8192.\n"\
259 "- Are you using -cache to play a non-interleaved AVI file?\n"\
260 " - Try -nocache.\n"\
261 "Read DOCS/HTML/en/video.html for tuning/speedup tips.\n"\
262 "If none of this helps you, read DOCS/HTML/en/bugreports.html.\n\n")
265 //**************************************************************************//
266 //**************************************************************************//
268 #include "mp_fifo.h"
270 // benchmark:
271 double video_time_usage=0;
272 double vout_time_usage=0;
273 static double audio_time_usage=0;
274 static int total_time_usage_start=0;
275 static int total_frame_cnt=0;
276 static int drop_frame_cnt=0; // total number of dropped frames
278 // options:
279 static int output_quality=0;
281 // seek:
282 static double seek_to_sec;
283 static off_t seek_to_byte=0;
284 static off_t step_sec=0;
286 static m_time_size_t end_at = { .type = END_AT_NONE, .pos = 0 };
288 // codecs:
289 char **audio_codec_list=NULL; // override audio codec
290 char **video_codec_list=NULL; // override video codec
291 char **audio_fm_list=NULL; // override audio codec family
292 char **video_fm_list=NULL; // override video codec family
294 // this dvdsub_id was selected via slang
295 // use this to allow dvdnav to follow -slang across stream resets,
296 // in particular the subtitle ID for a language changes
297 int dvdsub_lang_id;
298 int vobsub_id=-1;
299 static char* spudec_ifo=NULL;
300 int forced_subs_only=0;
301 int file_filter=1;
303 // cache2:
304 int stream_cache_size=-1;
306 // dump:
307 int stream_dump_type=0;
309 // A-V sync:
310 static float default_max_pts_correction=-1;//0.01f;
311 float audio_delay=0;
312 static int ignore_start=0;
314 double force_fps=0;
315 static int force_srate=0;
316 int frame_dropping=0; // option 0=no drop 1= drop vo 2= drop decode
317 static int play_n_frames=-1;
318 static int play_n_frames_mf=-1;
320 // sub:
321 char *font_name=NULL;
322 char *sub_font_name=NULL;
323 extern int font_fontconfig;
324 float font_factor=0.75;
325 float sub_delay=0;
326 float sub_fps=0;
327 int subcc_enabled=0;
328 int suboverlap_enabled = 1;
330 #include "sub/ass_mp.h"
332 char* current_module=NULL; // for debugging
335 // ---
337 #ifdef CONFIG_MENU
338 #include "m_struct.h"
339 #include "libmenu/menu.h"
340 static const vf_info_t* const libmenu_vfs[] = {
341 &vf_info_menu,
342 NULL
344 static vf_instance_t* vf_menu = NULL;
345 int use_menu = 0;
346 static char* menu_cfg = NULL;
347 static char* menu_root = "main";
348 #endif
351 edl_record_ptr edl_records = NULL; ///< EDL entries memory area
352 edl_record_ptr next_edl_record = NULL; ///< only for traversing edl_records
353 FILE* edl_fd = NULL; ///< fd to write to when in -edlout mode.
354 int use_filedir_conf;
355 int use_filename_title;
357 #include "mpcommon.h"
358 #include "command.h"
360 #include "metadata.h"
362 const void *mpctx_get_video_out(MPContext *mpctx)
364 return mpctx->video_out;
367 void *mpctx_get_demuxer(MPContext *mpctx)
369 return mpctx->demuxer;
372 void *mpctx_get_playtree_iter(MPContext *mpctx)
374 return mpctx->playtree_iter;
377 void *mpctx_get_mixer(MPContext *mpctx)
379 return &mpctx->mixer;
382 int mpctx_get_global_sub_size(MPContext *mpctx)
384 return mpctx->global_sub_size;
387 int mpctx_get_osd_function(MPContext *mpctx)
389 return mpctx->osd_function;
392 static float get_relative_time(struct MPContext *mpctx)
394 unsigned int new_time = GetTimer();
395 unsigned int delta = new_time - mpctx->last_time;
396 mpctx->last_time = new_time;
397 return delta * 0.000001;
400 static int is_valid_metadata_type(struct MPContext *mpctx, metadata_t type) {
401 switch (type)
403 /* check for valid video stream */
404 case META_VIDEO_CODEC:
405 case META_VIDEO_BITRATE:
406 case META_VIDEO_RESOLUTION:
408 if (!mpctx->sh_video)
409 return 0;
410 break;
413 /* check for valid audio stream */
414 case META_AUDIO_CODEC:
415 case META_AUDIO_BITRATE:
416 case META_AUDIO_SAMPLES:
418 if (!mpctx->sh_audio)
419 return 0;
420 break;
423 /* check for valid demuxer */
424 case META_INFO_TITLE:
425 case META_INFO_ARTIST:
426 case META_INFO_ALBUM:
427 case META_INFO_YEAR:
428 case META_INFO_COMMENT:
429 case META_INFO_TRACK:
430 case META_INFO_GENRE:
432 if (!mpctx->demuxer)
433 return 0;
434 break;
437 default:
438 break;
441 return 1;
444 static char *get_demuxer_info(struct MPContext *mpctx, char *tag) {
445 char **info = mpctx->demuxer->info;
446 int n;
448 if (!info || !tag)
449 return talloc_strdup(NULL, "");
451 for (n = 0; info[2*n] != NULL ; n++)
452 if (!strcasecmp (info[2*n], tag))
453 break;
455 return talloc_strdup(NULL, info[2*n+1] ? info[2*n+1] : "");
458 char *get_metadata(struct MPContext *mpctx, metadata_t type)
460 sh_audio_t * const sh_audio = mpctx->sh_audio;
461 sh_video_t * const sh_video = mpctx->sh_video;
463 if (!is_valid_metadata_type(mpctx, type))
464 return NULL;
466 switch (type) {
467 case META_NAME:
468 return talloc_strdup(NULL, mp_basename(mpctx->filename));
469 case META_VIDEO_CODEC:
470 if (sh_video->format == 0x10000001)
471 return talloc_strdup(NULL, "mpeg1");
472 else if (sh_video->format == 0x10000002)
473 return talloc_strdup(NULL, "mpeg2");
474 else if (sh_video->format == 0x10000004)
475 return talloc_strdup(NULL, "mpeg4");
476 else if (sh_video->format == 0x10000005)
477 return talloc_strdup(NULL, "h264");
478 else if (sh_video->format >= 0x20202020)
479 return talloc_asprintf(NULL, "%.4s", (char *) &sh_video->format);
480 else
481 return talloc_asprintf(NULL, "0x%08X", sh_video->format);
482 case META_VIDEO_BITRATE:
483 return talloc_asprintf(NULL, "%d kbps",
484 (int) (sh_video->i_bps * 8 / 1024));
485 case META_VIDEO_RESOLUTION:
486 return talloc_asprintf(NULL, "%d x %d", sh_video->disp_w,
487 sh_video->disp_h);
488 case META_AUDIO_CODEC:
489 if (sh_audio->codec && sh_audio->codec->name)
490 return talloc_strdup(NULL, sh_audio->codec->name);
491 return talloc_strdup(NULL, "");
492 case META_AUDIO_BITRATE:
493 return talloc_asprintf(NULL, "%d kbps",
494 (int) (sh_audio->i_bps * 8/1000));
495 case META_AUDIO_SAMPLES:
496 return talloc_asprintf(NULL, "%d Hz, %d ch.", sh_audio->samplerate,
497 sh_audio->channels);
499 /* check for valid demuxer */
500 case META_INFO_TITLE:
501 return get_demuxer_info(mpctx, "Title");
503 case META_INFO_ARTIST:
504 return get_demuxer_info(mpctx, "Artist");
506 case META_INFO_ALBUM:
507 return get_demuxer_info(mpctx, "Album");
509 case META_INFO_YEAR:
510 return get_demuxer_info(mpctx, "Year");
512 case META_INFO_COMMENT:
513 return get_demuxer_info(mpctx, "Comment");
515 case META_INFO_TRACK:
516 return get_demuxer_info(mpctx, "Track");
518 case META_INFO_GENRE:
519 return get_demuxer_info(mpctx, "Genre");
521 default:
522 break;
525 return talloc_strdup(NULL, "");
528 static void print_file_properties(struct MPContext *mpctx, const char *filename)
530 double start_pts = MP_NOPTS_VALUE;
531 double video_start_pts = MP_NOPTS_VALUE;
532 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_FILENAME=%s\n",
533 filename_recode(filename));
534 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_DEMUXER=%s\n", mpctx->demuxer->desc->name);
535 if (mpctx->sh_video) {
536 /* Assume FOURCC if all bytes >= 0x20 (' ') */
537 if (mpctx->sh_video->format >= 0x20202020)
538 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=%.4s\n", (char *)&mpctx->sh_video->format);
539 else
540 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=0x%08X\n", mpctx->sh_video->format);
541 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_BITRATE=%d\n", mpctx->sh_video->i_bps*8);
542 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_WIDTH=%d\n", mpctx->sh_video->disp_w);
543 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_HEIGHT=%d\n", mpctx->sh_video->disp_h);
544 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FPS=%5.3f\n", mpctx->sh_video->fps);
545 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_ASPECT=%1.4f\n", mpctx->sh_video->aspect);
546 video_start_pts = ds_get_next_pts(mpctx->d_video);
548 if (mpctx->sh_audio) {
549 /* Assume FOURCC if all bytes >= 0x20 (' ') */
550 if (mpctx->sh_audio->format >= 0x20202020)
551 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_FORMAT=%.4s\n", (char *)&mpctx->sh_audio->format);
552 else
553 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_FORMAT=%d\n", mpctx->sh_audio->format);
554 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_BITRATE=%d\n", mpctx->sh_audio->i_bps*8);
555 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_RATE=%d\n", mpctx->sh_audio->samplerate);
556 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_NCH=%d\n", mpctx->sh_audio->channels);
557 start_pts = ds_get_next_pts(mpctx->d_audio);
559 if (video_start_pts != MP_NOPTS_VALUE) {
560 if (start_pts == MP_NOPTS_VALUE || !mpctx->sh_audio ||
561 (mpctx->sh_video && video_start_pts < start_pts))
562 start_pts = video_start_pts;
564 if (start_pts != MP_NOPTS_VALUE)
565 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_START_TIME=%.2f\n", start_pts);
566 else
567 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_START_TIME=unknown\n");
568 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_LENGTH=%.2f\n", get_time_length(mpctx));
569 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_SEEKABLE=%d\n",
570 mpctx->stream->seek && (!mpctx->demuxer || mpctx->demuxer->seekable));
571 if (mpctx->demuxer) {
572 if (mpctx->demuxer->num_chapters == 0)
573 stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_NUM_CHAPTERS, &mpctx->demuxer->num_chapters);
574 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_CHAPTERS=%d\n", mpctx->demuxer->num_chapters);
578 /// step size of mixer changes
579 int volstep = 3;
581 #ifdef CONFIG_DVDNAV
582 static void mp_dvdnav_context_free(MPContext *ctx){
583 if (ctx->nav_smpi) free_mp_image(ctx->nav_smpi);
584 ctx->nav_smpi = NULL;
585 free(ctx->nav_buffer);
586 ctx->nav_buffer = NULL;
587 ctx->nav_start = NULL;
588 ctx->nav_in_size = 0;
590 #endif
592 static void uninit_subs(struct demuxer *demuxer)
594 for (int i = 0; i < MAX_S_STREAMS; i++) {
595 struct sh_sub *sh = demuxer->s_streams[i];
596 if (sh && sh->initialized)
597 sub_uninit(sh);
601 void uninit_player(struct MPContext *mpctx, unsigned int mask){
602 mask &= mpctx->initialized_flags;
604 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n*** uninit(0x%X)\n",mask);
606 if(mask&INITIALIZED_ACODEC){
607 mpctx->initialized_flags&=~INITIALIZED_ACODEC;
608 current_module="uninit_acodec";
609 if(mpctx->sh_audio) uninit_audio(mpctx->sh_audio);
610 mpctx->sh_audio=NULL;
611 mpctx->mixer.afilter = NULL;
614 if (mask & INITIALIZED_SUB) {
615 mpctx->initialized_flags &= ~INITIALIZED_SUB;
616 if (mpctx->d_sub->sh)
617 sub_switchoff(mpctx->d_sub->sh, mpctx->osd);
620 if(mask&INITIALIZED_VCODEC){
621 mpctx->initialized_flags&=~INITIALIZED_VCODEC;
622 current_module="uninit_vcodec";
623 if(mpctx->sh_video) uninit_video(mpctx->sh_video);
624 mpctx->sh_video=NULL;
625 #ifdef CONFIG_MENU
626 vf_menu=NULL;
627 #endif
630 if(mask&INITIALIZED_DEMUXER){
631 mpctx->initialized_flags&=~INITIALIZED_DEMUXER;
632 current_module="free_demuxer";
633 if (mpctx->num_sources) {
634 mpctx->demuxer = mpctx->sources[0].demuxer;
635 for (int i = 1; i < mpctx->num_sources; i++) {
636 uninit_subs(mpctx->sources[i].demuxer);
637 free_stream(mpctx->sources[i].stream);
638 free_demuxer(mpctx->sources[i].demuxer);
641 talloc_free(mpctx->sources);
642 mpctx->sources = NULL;
643 mpctx->num_sources = 0;
644 talloc_free(mpctx->timeline);
645 mpctx->timeline = NULL;
646 mpctx->num_timeline_parts = 0;
647 talloc_free(mpctx->chapters);
648 mpctx->chapters = NULL;
649 mpctx->num_chapters = 0;
650 mpctx->video_offset = 0;
651 if(mpctx->demuxer){
652 mpctx->stream=mpctx->demuxer->stream;
653 uninit_subs(mpctx->demuxer);
654 free_demuxer(mpctx->demuxer);
656 mpctx->demuxer=NULL;
659 // kill the cache process:
660 if(mask&INITIALIZED_STREAM){
661 mpctx->initialized_flags&=~INITIALIZED_STREAM;
662 current_module="uninit_stream";
663 if(mpctx->stream) free_stream(mpctx->stream);
664 mpctx->stream=NULL;
667 if(mask&INITIALIZED_VO){
668 mpctx->initialized_flags&=~INITIALIZED_VO;
669 current_module="uninit_vo";
670 vo_destroy(mpctx->video_out);
671 mpctx->video_out=NULL;
672 #ifdef CONFIG_DVDNAV
673 mp_dvdnav_context_free(mpctx);
674 #endif
677 // Must be after libvo uninit, as few vo drivers (svgalib) have tty code.
678 if(mask&INITIALIZED_GETCH2){
679 mpctx->initialized_flags&=~INITIALIZED_GETCH2;
680 current_module="uninit_getch2";
681 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[uninit getch2]]]\n");
682 // restore terminal:
683 getch2_disable();
686 if(mask&INITIALIZED_VOBSUB){
687 mpctx->initialized_flags&=~INITIALIZED_VOBSUB;
688 current_module="uninit_vobsub";
689 if(vo_vobsub) vobsub_close(vo_vobsub);
690 vo_vobsub=NULL;
693 if (mask&INITIALIZED_SPUDEC){
694 mpctx->initialized_flags&=~INITIALIZED_SPUDEC;
695 current_module="uninit_spudec";
696 spudec_free(vo_spudec);
697 vo_spudec=NULL;
700 if(mask&INITIALIZED_AO){
701 mpctx->initialized_flags&=~INITIALIZED_AO;
702 current_module="uninit_ao";
703 if (mpctx->edl_muted) mixer_mute(&mpctx->mixer);
704 if (mpctx->ao)
705 ao_uninit(mpctx->ao, mpctx->stop_play != AT_END_OF_FILE);
706 mpctx->ao = NULL;
709 current_module=NULL;
712 void exit_player_with_rc(struct MPContext *mpctx, enum exit_reason how, int rc)
714 if (mpctx->user_muted && !mpctx->edl_muted) mixer_mute(&mpctx->mixer);
715 uninit_player(mpctx, INITIALIZED_ALL);
716 #if defined(__MINGW32__) || defined(__CYGWIN__)
717 timeEndPeriod(1);
718 #endif
719 #ifdef CONFIG_X11
720 vo_uninit(mpctx->x11_state); // Close the X11 connection (if any is open).
721 #endif
723 current_module="uninit_input";
724 mp_input_uninit(mpctx->input);
725 #ifdef CONFIG_MENU
726 if (use_menu)
727 menu_uninit();
728 #endif
730 #ifdef CONFIG_FREETYPE
731 current_module="uninit_font";
732 if (mpctx->osd && mpctx->osd->sub_font != vo_font)
733 free_font_desc(mpctx->osd->sub_font);
734 free_font_desc(vo_font);
735 vo_font = NULL;
736 done_freetype();
737 #endif
738 osd_free(mpctx->osd);
740 #ifdef CONFIG_ASS
741 ass_library_done(ass_library);
742 ass_library = NULL;
743 #endif
745 current_module="exit_player";
747 // free mplayer config
748 if(mpctx->mconfig)
749 m_config_free(mpctx->mconfig);
750 mpctx->mconfig = NULL;
752 if(mpctx->playtree_iter)
753 play_tree_iter_free(mpctx->playtree_iter);
754 mpctx->playtree_iter = NULL;
755 if(mpctx->playtree)
756 play_tree_free(mpctx->playtree, 1);
757 mpctx->playtree = NULL;
759 talloc_free(mpctx->key_fifo);
761 free(edl_records); // free mem allocated for EDL
762 edl_records = NULL;
763 switch(how) {
764 case EXIT_QUIT:
765 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Quit");
766 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=QUIT\n");
767 break;
768 case EXIT_EOF:
769 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","End of file");
770 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=EOF\n");
771 break;
772 case EXIT_ERROR:
773 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Fatal error");
774 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=ERROR\n");
775 break;
776 default:
777 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=NONE\n");
779 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"max framesize was %d bytes\n",max_framesize);
781 exit(rc);
784 static void exit_player(struct MPContext *mpctx, enum exit_reason how)
786 exit_player_with_rc(mpctx, how, 1);
789 #ifndef __MINGW32__
790 static void child_sighandler(int x){
791 pid_t pid;
792 while((pid=waitpid(-1,NULL,WNOHANG)) > 0);
794 #endif
796 #ifdef CONFIG_CRASH_DEBUG
797 static char *prog_path;
798 static int crash_debug = 0;
799 #endif
801 static void exit_sighandler(int x){
802 static int sig_count=0;
803 #ifdef CONFIG_CRASH_DEBUG
804 if (!crash_debug || x != SIGTRAP)
805 #endif
806 ++sig_count;
807 if(sig_count==5)
809 /* We're crashing bad and can't uninit cleanly :(
810 * by popular request, we make one last (dirty)
811 * effort to restore the user's
812 * terminal. */
813 getch2_disable();
814 exit(1);
816 if(sig_count==6) exit(1);
817 if(sig_count>6){
818 // can't stop :(
819 #ifndef __MINGW32__
820 kill(getpid(),SIGKILL);
821 #endif
823 mp_msg(MSGT_CPLAYER, MSGL_FATAL, "\n");
824 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,
825 "\nMPlayer interrupted by signal %d in module: %s\n", x,
826 current_module ? current_module : "unknown");
827 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SIGNAL=%d\n", x);
828 if(sig_count<=1)
829 switch(x){
830 case SIGINT:
831 case SIGPIPE:
832 case SIGQUIT:
833 case SIGTERM:
834 case SIGKILL:
835 async_quit_request = 1;
836 return; // killed from keyboard (^C) or killed [-9]
837 case SIGILL:
838 #if CONFIG_RUNTIME_CPUDETECT
839 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL_RTCpuSel);
840 #else
841 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL);
842 #endif
843 case SIGFPE:
844 case SIGSEGV:
845 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGSEGV_SIGFPE);
846 default:
847 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGCRASH);
848 #ifdef CONFIG_CRASH_DEBUG
849 if (crash_debug) {
850 int gdb_pid;
851 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forking...\n");
852 gdb_pid = fork();
853 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forked...\n");
854 if (gdb_pid == 0) { // We are the child
855 char spid[20];
856 snprintf(spid, sizeof(spid), "%i", getppid());
857 getch2_disable(); // allow terminal to work properly with gdb
858 if (execlp("gdb", "gdb", prog_path, spid, "-ex", "bt", NULL) == -1)
859 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't start gdb\n");
860 } else if (gdb_pid < 0)
861 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't fork\n");
862 else {
863 waitpid(gdb_pid, NULL, 0);
865 if (x == SIGTRAP) return;
867 #endif
869 getch2_disable();
870 exit(1);
873 #include "cfg-mplayer.h"
875 static int cfg_include(m_option_t *conf, char *filename)
877 return m_config_parse_config_file(conf->priv, filename);
880 #define DEF_CONFIG "# Write your default config options here!\n\n\n"
882 static void parse_cfgfiles(struct MPContext *mpctx, m_config_t* conf)
884 struct MPOpts *opts = &mpctx->opts;
885 char *conffile;
886 int conffile_fd;
887 if (!(opts->noconfig & 2) &&
888 m_config_parse_config_file(conf, MPLAYER_CONFDIR "/mplayer.conf") < 0)
889 exit_player(mpctx, EXIT_NONE);
890 if ((conffile = get_path("")) == NULL) {
891 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"Cannot find HOME directory.\n");
892 } else {
893 #ifdef __MINGW32__
894 mkdir(conffile);
895 #else
896 mkdir(conffile, 0777);
897 #endif
898 free(conffile);
899 if ((conffile = get_path("config")) == NULL) {
900 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"get_path(\"config\") problem\n");
901 } else {
902 if ((conffile_fd = open(conffile, O_CREAT | O_EXCL | O_WRONLY, 0666)) != -1) {
903 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Creating config file: %s\n", conffile);
904 write(conffile_fd, DEF_CONFIG, sizeof(DEF_CONFIG) - 1);
905 close(conffile_fd);
907 if (!(opts->noconfig & 1) &&
908 m_config_parse_config_file(conf, conffile) < 0)
909 exit_player(mpctx, EXIT_NONE);
910 free(conffile);
915 #define PROFILE_CFG_PROTOCOL "protocol."
917 static void load_per_protocol_config (m_config_t* conf, const char *const file)
919 char *str;
920 char protocol[strlen (PROFILE_CFG_PROTOCOL) + strlen (file) + 1];
921 m_profile_t *p;
923 /* does filename actually uses a protocol ? */
924 str = strstr (file, "://");
925 if (!str)
926 return;
928 sprintf (protocol, "%s%s", PROFILE_CFG_PROTOCOL, file);
929 protocol[strlen (PROFILE_CFG_PROTOCOL)+strlen(file)-strlen(str)] = '\0';
930 p = m_config_get_profile (conf, protocol);
931 if (p)
933 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading protocol-related profile '%s'\n", protocol);
934 m_config_set_profile(conf,p);
938 #define PROFILE_CFG_EXTENSION "extension."
940 static void load_per_extension_config (m_config_t* conf, const char *const file)
942 char *str;
943 char extension[strlen (PROFILE_CFG_EXTENSION) + 8];
944 m_profile_t *p;
946 /* does filename actually have an extension ? */
947 str = strrchr (file, '.');
948 if (!str)
949 return;
951 sprintf (extension, PROFILE_CFG_EXTENSION);
952 strncat (extension, ++str, 7);
953 p = m_config_get_profile (conf, extension);
954 if (p)
956 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", extension);
957 m_config_set_profile(conf,p);
961 #define PROFILE_CFG_VO "vo."
962 #define PROFILE_CFG_AO "ao."
964 static void load_per_output_config (m_config_t* conf, char *cfg, char *out)
966 char profile[strlen (cfg) + strlen (out) + 1];
967 m_profile_t *p;
969 sprintf (profile, "%s%s", cfg, out);
970 p = m_config_get_profile (conf, profile);
971 if (p)
973 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", profile);
974 m_config_set_profile(conf,p);
979 * Tries to load a config file
980 * @return 0 if file was not found, 1 otherwise
982 static int try_load_config(m_config_t *conf, const char *file)
984 struct stat st;
985 if (stat(file, &st))
986 return 0;
987 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Loading config '%s'\n", file);
988 m_config_parse_config_file (conf, file);
989 return 1;
992 static void load_per_file_config (m_config_t* conf, const char *const file)
994 char *confpath;
995 char cfg[PATH_MAX];
996 const char *name;
998 if (strlen(file) > PATH_MAX - 14) {
999 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Filename is too long, can not load file or directory specific config files\n");
1000 return;
1002 sprintf (cfg, "%s.conf", file);
1004 name = mp_basename(cfg);
1005 if (use_filedir_conf) {
1006 char dircfg[PATH_MAX];
1007 strcpy(dircfg, cfg);
1008 strcpy(dircfg + (name - cfg), "mplayer.conf");
1009 try_load_config(conf, dircfg);
1011 if (try_load_config(conf, cfg))
1012 return;
1015 if ((confpath = get_path (name)) != NULL)
1017 try_load_config(conf, confpath);
1019 free (confpath);
1023 /* When libmpdemux performs a blocking operation (network connection or
1024 * cache filling) if the operation fails we use this function to check
1025 * if it was interrupted by the user.
1026 * The function returns a new value for eof. */
1027 static int libmpdemux_was_interrupted(struct MPContext *mpctx, int stop_play)
1029 mp_cmd_t* cmd;
1030 if((cmd = mp_input_get_cmd(mpctx->input, 0, 0)) != NULL) {
1031 switch(cmd->id) {
1032 case MP_CMD_QUIT:
1033 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
1034 case MP_CMD_PLAY_TREE_STEP: {
1035 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_ENTRY : PT_PREV_ENTRY;
1036 mpctx->play_tree_step = (cmd->args[0].v.i == 0) ? 1 : cmd->args[0].v.i;
1037 } break;
1038 case MP_CMD_PLAY_TREE_UP_STEP: {
1039 stop_play = (cmd->args[0].v.i > 0) ? PT_UP_NEXT : PT_UP_PREV;
1040 } break;
1041 case MP_CMD_PLAY_ALT_SRC_STEP: {
1042 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_SRC : PT_PREV_SRC;
1043 } break;
1045 mp_cmd_free(cmd);
1047 return stop_play;
1050 static int playtree_add_playlist(struct MPContext *mpctx, play_tree_t* entry)
1052 play_tree_add_bpf(entry,mpctx->filename);
1055 if(!entry) {
1056 entry = mpctx->playtree_iter->tree;
1057 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1058 return PT_NEXT_ENTRY;
1060 if(mpctx->playtree_iter->tree == entry ) { // Loop with a single file
1061 if(play_tree_iter_up_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1062 return PT_NEXT_ENTRY;
1065 play_tree_remove(entry,1,1);
1066 return PT_NEXT_SRC;
1068 play_tree_insert_entry(mpctx->playtree_iter->tree,entry);
1069 play_tree_set_params_from(entry,mpctx->playtree_iter->tree);
1070 entry = mpctx->playtree_iter->tree;
1071 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1072 return PT_NEXT_ENTRY;
1074 play_tree_remove(entry,1,1);
1076 return PT_NEXT_SRC;
1079 void add_subtitles(struct MPContext *mpctx, char *filename, float fps, int noerr)
1081 struct MPOpts *opts = &mpctx->opts;
1082 sub_data *subd = NULL;
1083 struct ass_track *asst = NULL;
1084 bool is_native_ass = false;
1086 if (filename == NULL || mpctx->set_of_sub_size >= MAX_SUBTITLE_FILES)
1087 return;
1089 #ifdef CONFIG_ASS
1090 if (opts->ass_enabled) {
1091 #ifdef CONFIG_ICONV
1092 asst = mp_ass_read_stream(ass_library, filename, sub_cp);
1093 #else
1094 asst = mp_ass_read_stream(ass_library, filename, 0);
1095 #endif
1096 is_native_ass = asst;
1097 if (!asst) {
1098 subd = sub_read_file(filename, fps, &mpctx->opts);
1099 if (subd) {
1100 asst = mp_ass_read_subdata(ass_library, subd, fps);
1101 sub_free(subd);
1102 subd = NULL;
1105 } else
1106 #endif
1107 subd = sub_read_file(filename, fps, &mpctx->opts);
1110 if (!asst && !subd) {
1111 mp_tmsg(MSGT_CPLAYER, noerr ? MSGL_WARN : MSGL_ERR,
1112 "Cannot load subtitles: %s\n", filename_recode(filename));
1113 return;
1116 mpctx->set_of_ass_tracks[mpctx->set_of_sub_size] = asst;
1117 mpctx->set_of_subtitles[mpctx->set_of_sub_size] = subd;
1118 mpctx->track_was_native_ass[mpctx->set_of_sub_size] = is_native_ass;
1119 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_ID=%d\n", mpctx->set_of_sub_size);
1120 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_FILENAME=%s\n",
1121 filename_recode(filename));
1122 ++mpctx->set_of_sub_size;
1123 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "SUB: Added subtitle file (%d): %s\n", mpctx->set_of_sub_size,
1124 filename_recode(filename));
1127 void init_vo_spudec(struct MPContext *mpctx)
1129 spudec_free(vo_spudec);
1130 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
1131 vo_spudec = NULL;
1133 // we currently can't work without video stream
1134 if (!mpctx->sh_video)
1135 return;
1137 if (spudec_ifo) {
1138 unsigned int palette[16], width, height;
1139 current_module="spudec_init_vobsub";
1140 if (vobsub_parse_ifo(NULL,spudec_ifo, palette, &width, &height, 1, -1, NULL) >= 0)
1141 vo_spudec=spudec_new_scaled(palette, width, height, NULL, 0);
1144 #ifdef CONFIG_DVDREAD
1145 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVD) {
1146 current_module="spudec_init_dvdread";
1147 vo_spudec=spudec_new_scaled(((dvd_priv_t *)(mpctx->stream->priv))->cur_pgc->palette,
1148 mpctx->sh_video->disp_w, mpctx->sh_video->disp_h,
1149 NULL, 0);
1151 #endif
1153 #ifdef CONFIG_DVDNAV
1154 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVDNAV) {
1155 unsigned int *palette = mp_dvdnav_get_spu_clut(mpctx->stream);
1156 current_module="spudec_init_dvdnav";
1157 vo_spudec=spudec_new_scaled(palette, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, NULL, 0);
1159 #endif
1161 if (vo_spudec==NULL) {
1162 sh_sub_t *sh = mpctx->d_sub->sh;
1163 current_module="spudec_init_normal";
1164 vo_spudec=spudec_new_scaled(NULL, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, sh->extradata, sh->extradata_len);
1165 spudec_set_font_factor(vo_spudec,font_factor);
1168 if (vo_spudec!=NULL) {
1169 mpctx->initialized_flags|=INITIALIZED_SPUDEC;
1170 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
1175 * In Mac OS X the SDL-lib is built upon Cocoa. The easiest way to
1176 * make it all work is to use the builtin SDL-bootstrap code, which
1177 * will be done automatically by replacing our main() if we include SDL.h.
1179 #if defined(__APPLE__) && defined(CONFIG_SDL)
1180 #ifdef CONFIG_SDL_SDL_H
1181 #include <SDL/SDL.h>
1182 #else
1183 #include <SDL.h>
1184 #endif
1185 #endif
1188 * \brief append a formatted string
1189 * \param buf buffer to print into
1190 * \param pos position of terminating 0 in buf
1191 * \param len maximum number of characters in buf, not including terminating 0
1192 * \param format printf format string
1194 static void saddf(char *buf, unsigned *pos, int len, const char *format, ...)
1196 va_list va;
1197 va_start(va, format);
1198 *pos += vsnprintf(&buf[*pos], len - *pos, format, va);
1199 va_end(va);
1200 if (*pos >= len ) {
1201 buf[len] = 0;
1202 *pos = len;
1207 * \brief append time in the hh:mm:ss.f format
1208 * \param buf buffer to print into
1209 * \param pos position of terminating 0 in buf
1210 * \param len maximum number of characters in buf, not including terminating 0
1211 * \param time time value to convert/append
1213 static void sadd_hhmmssf(char *buf, unsigned *pos, int len, float time) {
1214 int64_t tenths = 10 * time;
1215 int f1 = tenths % 10;
1216 int ss = (tenths / 10) % 60;
1217 int mm = (tenths / 600) % 60;
1218 int hh = tenths / 36000;
1219 if (time <= 0) {
1220 saddf(buf, pos, len, "unknown");
1221 return;
1223 if (hh > 0)
1224 saddf(buf, pos, len, "%2d:", hh);
1225 if (hh > 0 || mm > 0)
1226 saddf(buf, pos, len, "%02d:", mm);
1227 saddf(buf, pos, len, "%02d.%1d", ss, f1);
1230 static void print_status(struct MPContext *mpctx, double a_pos, bool at_frame)
1232 struct MPOpts *opts = &mpctx->opts;
1233 sh_video_t * const sh_video = mpctx->sh_video;
1235 if (mpctx->sh_audio && a_pos == MP_NOPTS_VALUE)
1236 a_pos = playing_audio_pts(mpctx);
1237 if (mpctx->sh_audio && sh_video && at_frame) {
1238 mpctx->last_av_difference = a_pos - mpctx->video_pts - audio_delay;
1239 if (mpctx->time_frame > 0)
1240 mpctx->last_av_difference += mpctx->time_frame * opts->playback_speed;
1241 if (mpctx->last_av_difference > 0.5 && drop_frame_cnt > 50
1242 && !mpctx->drop_message_shown) {
1243 mp_tmsg(MSGT_AVSYNC,MSGL_WARN,SystemTooSlow);
1244 mpctx->drop_message_shown = true;
1247 if (opts->quiet)
1248 return;
1251 int width;
1252 char *line;
1253 unsigned pos = 0;
1254 get_screen_size();
1255 if (screen_width > 0)
1256 width = screen_width;
1257 else
1258 width = 80;
1259 #if defined(__MINGW32__) || defined(__CYGWIN__) || defined(__OS2__)
1260 /* Windows command line is broken (MinGW's rxvt works, but we
1261 * should not depend on that). */
1262 width--;
1263 #endif
1264 line = malloc(width + 1); // one additional char for the terminating null
1266 // Audio time
1267 if (mpctx->sh_audio) {
1268 saddf(line, &pos, width, "A:%6.1f ", a_pos);
1269 if (!sh_video) {
1270 float len = get_time_length(mpctx);
1271 saddf(line, &pos, width, "(");
1272 sadd_hhmmssf(line, &pos, width, a_pos);
1273 saddf(line, &pos, width, ") of %.1f (", len);
1274 sadd_hhmmssf(line, &pos, width, len);
1275 saddf(line, &pos, width, ") ");
1279 // Video time
1280 if (sh_video)
1281 saddf(line, &pos, width, "V:%6.1f ", mpctx->video_pts);
1283 // A-V sync
1284 if (mpctx->sh_audio && sh_video)
1285 saddf(line, &pos, width, "A-V:%7.3f ct:%7.3f ",
1286 mpctx->last_av_difference, mpctx->total_avsync_change);
1288 // Video stats
1289 if (sh_video)
1290 saddf(line, &pos, width, "%3d/%3d ",
1291 (int)sh_video->num_frames,
1292 (int)sh_video->num_frames_decoded);
1294 // CPU usage
1295 if (sh_video) {
1296 if (sh_video->timer > 0.5)
1297 saddf(line, &pos, width, "%2d%% %2d%% %4.1f%% ",
1298 (int)(100.0*video_time_usage*opts->playback_speed/(double)sh_video->timer),
1299 (int)(100.0*vout_time_usage*opts->playback_speed/(double)sh_video->timer),
1300 (100.0*audio_time_usage*opts->playback_speed/(double)sh_video->timer));
1301 else
1302 saddf(line, &pos, width, "??%% ??%% ??,?%% ");
1303 } else if (mpctx->sh_audio) {
1304 if (mpctx->delay > 0.5)
1305 saddf(line, &pos, width, "%4.1f%% ",
1306 100.0*audio_time_usage/(double)mpctx->delay);
1307 else
1308 saddf(line, &pos, width, "??,?%% ");
1311 // VO stats
1312 if (sh_video)
1313 saddf(line, &pos, width, "%d %d ", drop_frame_cnt, output_quality);
1315 #ifdef CONFIG_STREAM_CACHE
1316 // cache stats
1317 if (stream_cache_size > 0)
1318 saddf(line, &pos, width, "%d%% ", cache_fill_status(mpctx->stream));
1319 #endif
1321 // other
1322 if (opts->playback_speed != 1)
1323 saddf(line, &pos, width, "%4.2fx ", opts->playback_speed);
1325 // end
1326 if (erase_to_end_of_line) {
1327 line[pos] = 0;
1328 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s%s\r", line, erase_to_end_of_line);
1329 } else {
1330 memset(&line[pos], ' ', width - pos);
1331 line[width] = 0;
1332 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s\r", line);
1334 free(line);
1338 * \brief build a chain of audio filters that converts the input format
1339 * to the ao's format, taking into account the current playback_speed.
1340 * sh_audio describes the requested input format of the chain.
1341 * ao describes the requested output format of the chain.
1343 static int build_afilter_chain(struct MPContext *mpctx)
1345 struct sh_audio *sh_audio = mpctx->sh_audio;
1346 struct ao *ao = mpctx->ao;
1347 struct MPOpts *opts = &mpctx->opts;
1348 int new_srate;
1349 int result;
1350 if (!sh_audio)
1352 mpctx->mixer.afilter = NULL;
1353 return 0;
1355 if(af_control_any_rev(sh_audio->afilter,
1356 AF_CONTROL_PLAYBACK_SPEED | AF_CONTROL_SET,
1357 &opts->playback_speed)) {
1358 new_srate = sh_audio->samplerate;
1359 } else {
1360 new_srate = sh_audio->samplerate * opts->playback_speed;
1361 if (new_srate != ao->samplerate) {
1362 // limits are taken from libaf/af_resample.c
1363 if (new_srate < 8000)
1364 new_srate = 8000;
1365 if (new_srate > 192000)
1366 new_srate = 192000;
1367 opts->playback_speed = (float)new_srate / (float)sh_audio->samplerate;
1370 result = init_audio_filters(sh_audio, new_srate,
1371 &ao->samplerate, &ao->channels, &ao->format);
1372 mpctx->mixer.afilter = sh_audio->afilter;
1373 return result;
1377 typedef struct mp_osd_msg mp_osd_msg_t;
1378 struct mp_osd_msg {
1379 /// Previous message on the stack.
1380 mp_osd_msg_t* prev;
1381 /// Message text.
1382 char msg[128];
1383 int id,level,started;
1384 /// Display duration in ms.
1385 unsigned time;
1388 /// OSD message stack.
1389 static mp_osd_msg_t* osd_msg_stack = NULL;
1392 * \brief Add a message on the OSD message stack
1394 * If a message with the same id is already present in the stack
1395 * it is pulled on top of the stack, otherwise a new message is created.
1398 static void set_osd_msg_va(int id, int level, int time, const char *fmt,
1399 va_list ap)
1401 mp_osd_msg_t *msg,*last=NULL;
1402 int r;
1404 // look if the id is already in the stack
1405 for(msg = osd_msg_stack ; msg && msg->id != id ;
1406 last = msg, msg = msg->prev);
1407 // not found: alloc it
1408 if(!msg) {
1409 msg = calloc(1,sizeof(mp_osd_msg_t));
1410 msg->prev = osd_msg_stack;
1411 osd_msg_stack = msg;
1412 } else if(last) { // found, but it's not on top of the stack
1413 last->prev = msg->prev;
1414 msg->prev = osd_msg_stack;
1415 osd_msg_stack = msg;
1417 // write the msg
1418 r = vsnprintf(msg->msg, 128, fmt, ap);
1419 if(r >= 128) msg->msg[127] = 0;
1420 // set id and time
1421 msg->id = id;
1422 msg->level = level;
1423 msg->time = time;
1427 void set_osd_msg(int id, int level, int time, const char *fmt, ...)
1429 va_list ap;
1430 va_start(ap, fmt);
1431 set_osd_msg_va(id, level, time, fmt, ap);
1432 va_end(ap);
1435 void set_osd_tmsg(int id, int level, int time, const char *fmt, ...)
1437 va_list ap;
1438 va_start(ap, fmt);
1439 set_osd_msg_va(id, level, time, mp_gtext(fmt), ap);
1440 va_end(ap);
1445 * \brief Remove a message from the OSD stack
1447 * This function can be used to get rid of a message right away.
1451 void rm_osd_msg(int id) {
1452 mp_osd_msg_t *msg,*last=NULL;
1454 // Search for the msg
1455 for(msg = osd_msg_stack ; msg && msg->id != id ;
1456 last = msg, msg = msg->prev);
1457 if(!msg) return;
1459 // Detach it from the stack and free it
1460 if(last)
1461 last->prev = msg->prev;
1462 else
1463 osd_msg_stack = msg->prev;
1464 free(msg);
1468 * \brief Remove all messages from the OSD stack
1472 static void clear_osd_msgs(void) {
1473 mp_osd_msg_t* msg = osd_msg_stack, *prev = NULL;
1474 while(msg) {
1475 prev = msg->prev;
1476 free(msg);
1477 msg = prev;
1479 osd_msg_stack = NULL;
1483 * \brief Get the current message from the OSD stack.
1485 * This function decrements the message timer and destroys the old ones.
1486 * The message that should be displayed is returned (if any).
1490 static mp_osd_msg_t* get_osd_msg(struct MPContext *mpctx)
1492 struct MPOpts *opts = &mpctx->opts;
1493 mp_osd_msg_t *msg,*prev,*last = NULL;
1494 static unsigned last_update = 0;
1495 unsigned now = GetTimerMS();
1496 unsigned diff;
1497 char hidden_dec_done = 0;
1499 if (mpctx->osd_visible) {
1500 // 36000000 means max timed visibility is 1 hour into the future, if
1501 // the difference is greater assume it's wrapped around from below 0
1502 if (mpctx->osd_visible - now > 36000000) {
1503 mpctx->osd_visible = 0;
1504 vo_osd_progbar_type = -1; // disable
1505 vo_osd_changed(OSDTYPE_PROGBAR);
1506 mpctx->osd_function = mpctx->paused ? OSD_PAUSE : OSD_PLAY;
1509 if (mpctx->osd_show_percentage_until - now > 36000000)
1510 mpctx->osd_show_percentage_until = 0;
1512 if(!last_update) last_update = now;
1513 diff = now >= last_update ? now - last_update : 0;
1515 last_update = now;
1517 // Look for the first message in the stack with high enough level.
1518 for(msg = osd_msg_stack ; msg ; last = msg, msg = prev) {
1519 prev = msg->prev;
1520 if (msg->level > opts->osd_level && hidden_dec_done)
1521 continue;
1522 // The message has a high enough level or it is the first hidden one
1523 // in both cases we decrement the timer or kill it.
1524 if(!msg->started || msg->time > diff) {
1525 if(msg->started) msg->time -= diff;
1526 else msg->started = 1;
1527 // display it
1528 if (msg->level <= opts->osd_level)
1529 return msg;
1530 hidden_dec_done = 1;
1531 continue;
1533 // kill the message
1534 free(msg);
1535 if(last) {
1536 last->prev = prev;
1537 msg = last;
1538 } else {
1539 osd_msg_stack = prev;
1540 msg = NULL;
1543 // Nothing found
1544 return NULL;
1548 * \brief Display the OSD bar.
1550 * Display the OSD bar or fall back on a simple message.
1554 void set_osd_bar(struct MPContext *mpctx, int type,const char* name,double min,double max,double val) {
1555 struct MPOpts *opts = &mpctx->opts;
1556 if (opts->osd_level < 1)
1557 return;
1559 if(mpctx->sh_video) {
1560 mpctx->osd_visible = (GetTimerMS() + 1000) | 1;
1561 vo_osd_progbar_type = type;
1562 vo_osd_progbar_value = 256*(val-min)/(max-min);
1563 vo_osd_changed(OSDTYPE_PROGBAR);
1564 return;
1567 set_osd_msg(OSD_MSG_BAR, 1, opts->osd_duration, "%s: %d %%",
1568 name, ROUND(100*(val-min)/(max-min)));
1572 * \brief Display text subtitles on the OSD
1574 void set_osd_subtitle(struct MPContext *mpctx, subtitle *subs)
1576 int i;
1577 vo_sub = subs;
1578 vo_osd_changed(OSDTYPE_SUBTITLE);
1579 if (!mpctx->sh_video) {
1580 // reverse order, since newest set_osd_msg is displayed first
1581 for (i = SUB_MAX_TEXT - 1; i >= 0; i--) {
1582 if (!subs || i >= subs->lines || !subs->text[i])
1583 rm_osd_msg(OSD_MSG_SUB_BASE + i);
1584 else {
1585 // HACK: currently display time for each sub line except the last is set to 2 seconds.
1586 int display_time = i == subs->lines - 1 ? 180000 : 2000;
1587 set_osd_msg(OSD_MSG_SUB_BASE + i, 1, display_time, "%s", subs->text[i]);
1594 * \brief Update the OSD message line.
1596 * This function displays the current message on the vo OSD or on the term.
1597 * If the stack is empty and the OSD level is high enough the timer
1598 * is displayed (only on the vo OSD).
1602 static void update_osd_msg(struct MPContext *mpctx)
1604 struct MPOpts *opts = &mpctx->opts;
1605 mp_osd_msg_t *msg;
1606 struct osd_state *osd = mpctx->osd;
1607 char osd_text_timer[128];
1609 if (mpctx->add_osd_seek_info) {
1610 double percentage = get_percent_pos(mpctx);
1611 set_osd_bar(mpctx, 0, "Position", 0, 100, percentage);
1612 if (mpctx->sh_video)
1613 mpctx->osd_show_percentage_until = (GetTimerMS() + 1000) | 1;
1614 mpctx->add_osd_seek_info = false;
1617 // Look if we have a msg
1618 if((msg = get_osd_msg(mpctx))) {
1619 if (strcmp(osd->osd_text, msg->msg)) {
1620 strncpy(osd->osd_text, msg->msg, 127);
1621 if(mpctx->sh_video) vo_osd_changed(OSDTYPE_OSD); else
1622 if(opts->term_osd)
1623 mp_msg(MSGT_CPLAYER,MSGL_STATUS, "%s%s\n", opts->term_osd_esc,
1624 msg->msg);
1626 return;
1629 if(mpctx->sh_video) {
1630 // fallback on the timer
1631 if (opts->osd_level >= 2) {
1632 int len = get_time_length(mpctx);
1633 int percentage = -1;
1634 char percentage_text[10];
1635 char fractions_text[4];
1636 double fpts = get_current_time(mpctx);
1637 int pts = fpts;
1639 if (mpctx->osd_show_percentage_until)
1640 percentage = get_percent_pos(mpctx);
1642 if (percentage >= 0)
1643 snprintf(percentage_text, 9, " (%d%%)", percentage);
1644 else
1645 percentage_text[0] = 0;
1647 if (opts->osd_fractions == 1) {
1648 //print fractions as sub-second timestamp
1649 snprintf(fractions_text, sizeof(fractions_text), ".%02d",
1650 (int)((fpts - pts) * 100));
1651 } else if (opts->osd_fractions == 2) {
1652 /* Print fractions by estimating the frame count within the
1653 * second.
1655 * Rounding or cutting off numbers after the decimal point
1656 * causes problems because of float's precision and movies
1657 * whose first frame is not exactly at timestamp 0. Therefore,
1658 * we add 0.2 and cut off at the decimal point, which proved
1659 * to be good heuristic.
1661 double fps = mpctx->sh_video->fps;
1662 if (fps <= 1 || fps > 99)
1663 strcpy(fractions_text, ".??");
1664 else
1665 snprintf(fractions_text, sizeof(fractions_text), ".%02d",
1666 (int) ( (fpts - pts) * fps + 0.2 ) );
1667 } else {
1668 //do not print fractions
1669 fractions_text[0] = 0;
1672 if (opts->osd_level == 3)
1673 snprintf(osd_text_timer, 63,
1674 "%c %02d:%02d:%02d%s / %02d:%02d:%02d%s",
1675 mpctx->osd_function,pts/3600,(pts/60)%60,pts%60,
1676 fractions_text, len/3600, (len/60)%60, len%60,
1677 percentage_text);
1678 else
1679 snprintf(osd_text_timer, 63, "%c %02d:%02d:%02d%s%s",
1680 mpctx->osd_function,pts/3600,(pts/60)%60,
1681 pts%60, fractions_text, percentage_text);
1682 } else
1683 osd_text_timer[0]=0;
1685 if (strcmp(osd->osd_text, osd_text_timer)) {
1686 strncpy(osd->osd_text, osd_text_timer, 63);
1687 vo_osd_changed(OSDTYPE_OSD);
1689 return;
1692 // Clear the term osd line
1693 if (opts->term_osd && osd->osd_text[0]) {
1694 osd->osd_text[0] = 0;
1695 printf("%s\n", opts->term_osd_esc);
1699 ///@}
1700 // OSDMsgStack
1703 void reinit_audio_chain(struct MPContext *mpctx)
1705 struct MPOpts *opts = &mpctx->opts;
1706 struct ao *ao;
1707 if (!mpctx->sh_audio)
1708 return;
1709 if (!(mpctx->initialized_flags & INITIALIZED_ACODEC)) {
1710 current_module="init_audio_codec";
1711 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1712 if(!init_best_audio_codec(mpctx->sh_audio,audio_codec_list,audio_fm_list)){
1713 goto init_error;
1715 mpctx->initialized_flags|=INITIALIZED_ACODEC;
1716 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1720 current_module="af_preinit";
1721 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1722 mpctx->initialized_flags |= INITIALIZED_AO;
1723 mpctx->ao = ao_create();
1724 mpctx->ao->samplerate = force_srate;
1725 mpctx->ao->format = opts->audio_output_format;
1727 ao = mpctx->ao;
1729 // first init to detect best values
1730 if(!init_audio_filters(mpctx->sh_audio, // preliminary init
1731 // input:
1732 mpctx->sh_audio->samplerate,
1733 // output:
1734 &ao->samplerate, &ao->channels, &ao->format)) {
1735 mp_tmsg(MSGT_CPLAYER,MSGL_ERR, "Error at audio filter chain "
1736 "pre-init!\n");
1737 exit_player(mpctx, EXIT_ERROR);
1739 if (!ao->initialized) {
1740 current_module="ao2_init";
1741 ao->buffersize = opts->ao_buffersize;
1742 ao_init(ao, opts->audio_driver_list);
1743 if (!ao->initialized) {
1744 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Could not open/initialize audio device -> no sound.\n");
1745 goto init_error;
1747 mp_msg(MSGT_CPLAYER,MSGL_INFO,"AO: [%s] %dHz %dch %s (%d bytes per sample)\n",
1748 ao->driver->info->short_name,
1749 ao->samplerate, ao->channels,
1750 af_fmt2str_short(ao->format),
1751 af_fmt2bits(ao->format)/8 );
1752 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Description: %s\nAO: Author: %s\n",
1753 ao->driver->info->name, ao->driver->info->author);
1754 if (strlen(ao->driver->info->comment) > 0)
1755 mp_msg(MSGT_CPLAYER, MSGL_V, "AO: Comment: %s\n",
1756 ao->driver->info->comment);
1759 // init audio filters:
1760 current_module="af_init";
1761 if (!build_afilter_chain(mpctx)) {
1762 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Couldn't find matching filter/ao format!\n");
1763 goto init_error;
1765 mpctx->mixer.ao = ao;
1766 mpctx->mixer.volstep = volstep;
1767 mpctx->syncing_audio = true;
1768 return;
1770 init_error:
1771 uninit_player(mpctx, INITIALIZED_ACODEC|INITIALIZED_AO); // close codec and possibly AO
1772 mpctx->sh_audio=mpctx->d_audio->sh=NULL; // -> nosound
1773 mpctx->d_audio->id = -2;
1777 ///@}
1778 // Command2Property
1781 // Return pts value corresponding to the end point of audio written to the
1782 // ao so far.
1783 static double written_audio_pts(struct MPContext *mpctx)
1785 sh_audio_t *sh_audio = mpctx->sh_audio;
1786 demux_stream_t *d_audio = mpctx->d_audio;
1787 double buffered_output;
1788 // first calculate the end pts of audio that has been output by decoder
1789 double a_pts = sh_audio->pts;
1790 if (a_pts != MP_NOPTS_VALUE)
1791 // Good, decoder supports new way of calculating audio pts.
1792 // sh_audio->pts is the timestamp of the latest input packet with
1793 // known pts that the decoder has decoded. sh_audio->pts_bytes is
1794 // the amount of bytes the decoder has written after that timestamp.
1795 a_pts += sh_audio->pts_bytes / (double) sh_audio->o_bps;
1796 else {
1797 // Decoder doesn't support new way of calculating pts (or we're
1798 // being called before it has decoded anything with known timestamp).
1799 // Use the old method of audio pts calculation: take the timestamp
1800 // of last packet with known pts the decoder has read data from,
1801 // and add amount of bytes read after the beginning of that packet
1802 // divided by input bps. This will be inaccurate if the input/output
1803 // ratio is not constant for every audio packet or if it is constant
1804 // but not accurately known in sh_audio->i_bps.
1806 a_pts = d_audio->pts;
1807 // ds_tell_pts returns bytes read after last timestamp from
1808 // demuxing layer, decoder might use sh_audio->a_in_buffer for bytes
1809 // it has read but not decoded
1810 if (sh_audio->i_bps)
1811 a_pts += (ds_tell_pts(d_audio) - sh_audio->a_in_buffer_len) /
1812 (double)sh_audio->i_bps;
1814 // Now a_pts hopefully holds the pts for end of audio from decoder.
1815 // Substract data in buffers between decoder and audio out.
1817 // Decoded but not filtered
1818 a_pts -= sh_audio->a_buffer_len / (double)sh_audio->o_bps;
1820 // Data buffered in audio filters, measured in bytes of "missing" output
1821 buffered_output = af_calc_delay(sh_audio->afilter);
1823 // Data that was ready for ao but was buffered because ao didn't fully
1824 // accept everything to internal buffers yet
1825 buffered_output += sh_audio->a_out_buffer_len;
1827 // Filters divide audio length by playback_speed, so multiply by it
1828 // to get the length in original units without speedup or slowdown
1829 a_pts -= buffered_output * mpctx->opts.playback_speed / mpctx->ao->bps;
1831 return a_pts + mpctx->video_offset;
1834 // Return pts value corresponding to currently playing audio.
1835 double playing_audio_pts(struct MPContext *mpctx)
1837 return written_audio_pts(mpctx) - mpctx->opts.playback_speed *
1838 ao_get_delay(mpctx->ao);
1841 static bool is_av_sub(int type)
1843 return type == 'b' || type == 'p' || type == 'x';
1846 void update_subtitles(struct MPContext *mpctx, double refpts,
1847 double sub_offset, bool reset)
1849 struct MPOpts *opts = &mpctx->opts;
1850 struct sh_video *sh_video = mpctx->sh_video;
1851 struct demux_stream *d_sub = mpctx->d_sub;
1852 double curpts = refpts + sub_delay;
1853 unsigned char *packet=NULL;
1854 int len;
1855 struct sh_sub *sh_sub = d_sub->sh;
1856 int type = sh_sub ? sh_sub->type : 'v';
1857 static subtitle subs;
1858 if (reset) {
1859 if (sh_sub)
1860 sub_reset(sh_sub, mpctx->osd);
1861 sub_clear_text(&subs, MP_NOPTS_VALUE);
1862 if (vo_sub)
1863 set_osd_subtitle(mpctx, NULL);
1864 if (vo_spudec) {
1865 spudec_reset(vo_spudec);
1866 vo_osd_changed(OSDTYPE_SPU);
1868 #ifdef CONFIG_FFMPEG
1869 if (is_av_sub(type))
1870 reset_avsub(sh_sub);
1871 #endif
1872 return;
1874 // find sub
1875 if (mpctx->subdata) {
1876 if (sub_fps==0) sub_fps = sh_video ? sh_video->fps : 25;
1877 current_module = "find_sub";
1878 find_sub(mpctx, mpctx->subdata, curpts *
1879 (mpctx->subdata->sub_uses_time ? 100. : sub_fps));
1880 if (vo_sub)
1881 mpctx->vo_sub_last = vo_sub;
1884 // DVD sub:
1885 if (vobsub_id >= 0 || type == 'v') {
1886 int timestamp;
1887 current_module = "spudec";
1888 /* Get a sub packet from the DVD or a vobsub */
1889 while(1) {
1890 // Vobsub
1891 len = 0;
1892 if (vo_vobsub) {
1893 if (curpts >= 0) {
1894 len = vobsub_get_packet(vo_vobsub, curpts,
1895 (void**)&packet, &timestamp);
1896 if (len > 0) {
1897 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);
1900 } else {
1901 // DVD sub
1902 len = ds_get_packet_sub(d_sub, (unsigned char**)&packet);
1903 if (len > 0) {
1904 // XXX This is wrong, sh_video->pts can be arbitrarily
1905 // much behind demuxing position. Unfortunately using
1906 // d_video->pts which would have been the simplest
1907 // improvement doesn't work because mpeg specific hacks
1908 // in video.c set d_video->pts to 0.
1909 float x = d_sub->pts - refpts;
1910 if (x > -20 && x < 20) // prevent missing subs on pts reset
1911 timestamp = 90000*d_sub->pts;
1912 else timestamp = 90000*curpts;
1913 mp_dbg(MSGT_CPLAYER, MSGL_V, "\rDVD sub: len=%d "
1914 "v_pts=%5.3f s_pts=%5.3f ts=%d \n", len,
1915 refpts, d_sub->pts, timestamp);
1918 if (len<=0 || !packet) break;
1919 // create it only here, since with some broken demuxers we might
1920 // type = v but no DVD sub and we currently do not change the
1921 // "original frame size" ever after init, leading to wrong-sized
1922 // PGS subtitles.
1923 if (!vo_spudec)
1924 vo_spudec = spudec_new(NULL);
1925 if (vo_vobsub || timestamp >= 0)
1926 spudec_assemble(vo_spudec, packet, len, timestamp);
1928 } else if (is_text_sub(type) || is_av_sub(type) || type == 'd') {
1929 if (type == 'd' && !d_sub->demuxer->teletext) {
1930 tt_stream_props tsp = {0};
1931 void *ptr = &tsp;
1932 if (teletext_control(NULL, TV_VBI_CONTROL_START, &ptr) == VBI_CONTROL_TRUE)
1933 d_sub->demuxer->teletext = ptr;
1935 if (d_sub->non_interleaved)
1936 ds_get_next_pts(d_sub);
1938 while (d_sub->first) {
1939 double subpts = ds_get_next_pts(d_sub) + sub_offset;
1940 if (subpts > curpts) {
1941 // Libass handled subs can be fed to it in advance
1942 if (!opts->ass_enabled || !is_text_sub(type))
1943 break;
1944 // Try to avoid demuxing whole file at once
1945 if (d_sub->non_interleaved && subpts > curpts + 1)
1946 break;
1948 double duration = d_sub->first->duration;
1949 len = ds_get_packet_sub(d_sub, &packet);
1950 if (is_av_sub(type)) {
1951 #ifdef CONFIG_FFMPEG
1952 int ret = decode_avsub(sh_sub, packet, len, subpts, duration);
1953 if (ret < 0)
1954 mp_msg(MSGT_SPUDEC, MSGL_WARN, "lavc failed decoding "
1955 "subtitle\n");
1956 #endif
1957 continue;
1959 if (type == 'm') {
1960 if (len < 2) continue;
1961 len = FFMIN(len - 2, AV_RB16(packet));
1962 packet += 2;
1964 if (type == 'd') {
1965 if (d_sub->demuxer->teletext) {
1966 uint8_t *p = packet;
1967 p++;
1968 len--;
1969 while (len >= 46) {
1970 int sublen = p[1];
1971 if (p[0] == 2 || p[0] == 3)
1972 teletext_control(d_sub->demuxer->teletext,
1973 TV_VBI_CONTROL_DECODE_DVB, p + 2);
1974 p += sublen + 2;
1975 len -= sublen + 2;
1978 continue;
1980 if (sh_sub && sh_sub->active) {
1981 sub_decode(sh_sub, mpctx->osd, packet, len, subpts, duration);
1982 continue;
1984 if (subpts != MP_NOPTS_VALUE) {
1985 if (duration < 0)
1986 sub_clear_text(&subs, MP_NOPTS_VALUE);
1987 if (type == 'a') { // ssa/ass subs without libass => convert to plaintext
1988 int i;
1989 unsigned char* p = packet;
1990 for (i=0; i < 8 && *p != '\0'; p++)
1991 if (*p == ',')
1992 i++;
1993 if (*p == '\0') /* Broken line? */
1994 continue;
1995 len -= p - packet;
1996 packet = p;
1998 double endpts = MP_NOPTS_VALUE;
1999 if (subpts != MP_NOPTS_VALUE && duration >= 0)
2000 endpts = subpts + duration;
2001 sub_add_text(&subs, packet, len, endpts);
2002 set_osd_subtitle(mpctx, &subs);
2004 if (d_sub->non_interleaved)
2005 ds_get_next_pts(d_sub);
2007 if (!opts->ass_enabled)
2008 if (sub_clear_text(&subs, curpts))
2009 set_osd_subtitle(mpctx, &subs);
2011 if (vo_spudec) {
2012 spudec_heartbeat(vo_spudec, 90000*curpts);
2013 if (spudec_changed(vo_spudec))
2014 vo_osd_changed(OSDTYPE_SPU);
2017 current_module=NULL;
2020 static void update_teletext(sh_video_t *sh_video, demuxer_t *demuxer, int reset)
2022 int page_changed;
2024 if (!demuxer->teletext)
2025 return;
2027 //Also forcing page update when such ioctl is not supported or call error occured
2028 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_IS_CHANGED,&page_changed)!=VBI_CONTROL_TRUE)
2029 page_changed=1;
2031 if(!page_changed)
2032 return;
2034 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_GET_VBIPAGE,&vo_osd_teletext_page)!=VBI_CONTROL_TRUE)
2035 vo_osd_teletext_page=NULL;
2036 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_GET_HALF_PAGE,&vo_osd_teletext_half)!=VBI_CONTROL_TRUE)
2037 vo_osd_teletext_half=0;
2038 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_GET_MODE,&vo_osd_teletext_mode)!=VBI_CONTROL_TRUE)
2039 vo_osd_teletext_mode=0;
2040 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_GET_FORMAT,&vo_osd_teletext_format)!=VBI_CONTROL_TRUE)
2041 vo_osd_teletext_format=0;
2042 vo_osd_changed(OSDTYPE_TELETEXT);
2044 teletext_control(demuxer->teletext,TV_VBI_CONTROL_MARK_UNCHANGED,NULL);
2047 static int check_framedrop(struct MPContext *mpctx, double frame_time) {
2048 struct MPOpts *opts = &mpctx->opts;
2049 // check for frame-drop:
2050 current_module = "check_framedrop";
2051 if (mpctx->sh_audio && !mpctx->ao->untimed && !mpctx->d_audio->eof) {
2052 static int dropped_frames;
2053 float delay = opts->playback_speed * ao_get_delay(mpctx->ao);
2054 float d = delay-mpctx->delay;
2055 ++total_frame_cnt;
2056 // we should avoid dropping too many frames in sequence unless we
2057 // are too late. and we allow 100ms A-V delay here:
2058 if (d < -dropped_frames*frame_time-0.100 && !mpctx->paused
2059 && !mpctx->restart_playback) {
2060 ++drop_frame_cnt;
2061 ++dropped_frames;
2062 return frame_dropping;
2063 } else
2064 dropped_frames = 0;
2066 return 0;
2070 #ifdef HAVE_RTC
2071 int rtc_fd = -1;
2072 #endif
2074 static float timing_sleep(struct MPContext *mpctx, float time_frame)
2076 #ifdef HAVE_RTC
2077 if (rtc_fd >= 0){
2078 // -------- RTC -----------
2079 current_module="sleep_rtc";
2080 while (time_frame > 0.000) {
2081 unsigned long rtc_ts;
2082 if (read(rtc_fd, &rtc_ts, sizeof(rtc_ts)) <= 0)
2083 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC read error: %s\n", strerror(errno));
2084 time_frame -= get_relative_time(mpctx);
2086 } else
2087 #endif
2089 // assume kernel HZ=100 for softsleep, works with larger HZ but with
2090 // unnecessarily high CPU usage
2091 struct MPOpts *opts = &mpctx->opts;
2092 float margin = opts->softsleep ? 0.011 : 0;
2093 current_module = "sleep_timer";
2094 while (time_frame > margin) {
2095 usec_sleep(1000000 * (time_frame - margin));
2096 time_frame -= get_relative_time(mpctx);
2098 if (opts->softsleep){
2099 current_module = "sleep_soft";
2100 if (time_frame < 0)
2101 mp_tmsg(MSGT_AVSYNC, MSGL_WARN, "Warning! Softsleep underflow!\n");
2102 while (time_frame > 0)
2103 time_frame -= get_relative_time(mpctx); // burn the CPU
2106 return time_frame;
2109 static int select_subtitle(MPContext *mpctx)
2111 struct MPOpts *opts = &mpctx->opts;
2112 // find the best sub to use
2113 int id;
2114 int found = 0;
2115 mpctx->global_sub_pos = -1; // no subs by default
2116 if (vobsub_id >= 0) {
2117 // if user asks for a vobsub id, use that first.
2118 id = vobsub_id;
2119 found = mp_property_do("sub_vob", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
2122 if (!found && opts->sub_id >= 0) {
2123 // if user asks for a dvd sub id, use that next.
2124 id = opts->sub_id;
2125 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
2128 if (!found) {
2129 // if there are text subs to use, use those. (autosubs come last here)
2130 id = 0;
2131 found = mp_property_do("sub_file", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
2134 if (!found && opts->sub_id == -1) {
2135 // finally select subs by language and container hints
2136 if (opts->sub_id == -1)
2137 opts->sub_id =
2138 demuxer_sub_track_by_lang_and_default(mpctx->d_sub->demuxer,
2139 opts->sub_lang);
2140 if (opts->sub_id >= 0) {
2141 id = opts->sub_id;
2142 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
2145 return found;
2148 #ifdef CONFIG_DVDNAV
2149 #ifndef FF_B_TYPE
2150 #define FF_B_TYPE 3
2151 #endif
2152 /// store decoded video image
2153 static mp_image_t * mp_dvdnav_copy_mpi(mp_image_t *to_mpi,
2154 mp_image_t *from_mpi) {
2155 mp_image_t *mpi;
2157 /// Do not store B-frames
2158 if (from_mpi->pict_type == FF_B_TYPE)
2159 return to_mpi;
2161 if (to_mpi &&
2162 to_mpi->w == from_mpi->w &&
2163 to_mpi->h == from_mpi->h &&
2164 to_mpi->imgfmt == from_mpi->imgfmt)
2165 mpi = to_mpi;
2166 else {
2167 if (to_mpi)
2168 free_mp_image(to_mpi);
2169 if (from_mpi->w == 0 || from_mpi->h == 0)
2170 return NULL;
2171 mpi = alloc_mpi(from_mpi->w,from_mpi->h,from_mpi->imgfmt);
2174 copy_mpi(mpi,from_mpi);
2175 return mpi;
2178 static void mp_dvdnav_reset_stream (MPContext *ctx) {
2179 struct MPOpts *opts = &ctx->opts;
2180 if (ctx->sh_video) {
2181 /// clear video pts
2182 ctx->d_video->pts = 0.0f;
2183 ctx->sh_video->pts = 0.0f;
2184 ctx->sh_video->i_pts = 0.0f;
2185 ctx->sh_video->last_pts = 0.0f;
2186 ctx->sh_video->num_buffered_pts = 0;
2187 ctx->sh_video->num_frames = 0;
2188 ctx->sh_video->num_frames_decoded = 0;
2189 ctx->sh_video->timer = 0.0f;
2190 ctx->sh_video->stream_delay = 0.0f;
2191 ctx->sh_video->timer = 0;
2192 ctx->demuxer->stream_pts = MP_NOPTS_VALUE;
2195 if (ctx->sh_audio) {
2196 /// free audio packets and reset
2197 ds_free_packs(ctx->d_audio);
2198 audio_delay -= ctx->sh_audio->stream_delay;
2199 ctx->delay =- audio_delay;
2200 ao_reset(ctx->ao);
2201 resync_audio_stream(ctx->sh_audio);
2204 audio_delay = 0.0f;
2205 ctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(ctx->stream);
2206 if (opts->sub_lang && opts->sub_id == dvdsub_lang_id) {
2207 dvdsub_lang_id = mp_dvdnav_sid_from_lang(ctx->stream, opts->sub_lang);
2208 if (dvdsub_lang_id != opts->sub_id) {
2209 opts->sub_id = dvdsub_lang_id;
2210 select_subtitle(ctx);
2214 /// clear all EOF related flags
2215 ctx->d_video->eof = ctx->d_audio->eof = ctx->stream->eof = 0;
2218 /// Restore last decoded DVDNAV (still frame)
2219 static mp_image_t *mp_dvdnav_restore_smpi(struct MPContext *mpctx,
2220 int *in_size,
2221 unsigned char **start,
2222 mp_image_t *decoded_frame)
2224 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2225 return decoded_frame;
2227 /// a change occured in dvdnav stream
2228 if (mp_dvdnav_cell_has_changed(mpctx->stream,0)) {
2229 mp_dvdnav_read_wait(mpctx->stream, 1, 1);
2230 mp_dvdnav_context_free(mpctx);
2231 mp_dvdnav_reset_stream(mpctx);
2232 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
2233 mp_dvdnav_cell_has_changed(mpctx->stream,1);
2236 if (*in_size < 0) {
2237 float len;
2239 /// Display still frame, if any
2240 if (mpctx->nav_smpi && !mpctx->nav_buffer)
2241 decoded_frame = mpctx->nav_smpi;
2243 /// increment video frame : continue playing after still frame
2244 len = get_time_length(mpctx);
2245 if (mpctx->sh_video->pts >= len &&
2246 mpctx->sh_video->pts > 0.0 && len > 0.0) {
2247 mp_dvdnav_skip_still(mpctx->stream);
2248 mp_dvdnav_skip_wait(mpctx->stream);
2250 mpctx->sh_video->pts += 1 / mpctx->sh_video->fps;
2252 if (mpctx->nav_buffer) {
2253 *start = mpctx->nav_start;
2254 *in_size = mpctx->nav_in_size;
2255 if (mpctx->nav_start)
2256 memcpy(*start,mpctx->nav_buffer,mpctx->nav_in_size);
2260 return decoded_frame;
2263 /// Save last decoded DVDNAV (still frame)
2264 static void mp_dvdnav_save_smpi(struct MPContext *mpctx, int in_size,
2265 unsigned char *start,
2266 mp_image_t *decoded_frame)
2268 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2269 return;
2271 free(mpctx->nav_buffer);
2273 mpctx->nav_buffer = malloc(in_size);
2274 mpctx->nav_start = start;
2275 mpctx->nav_in_size = mpctx->nav_buffer ? in_size : -1;
2276 if (mpctx->nav_buffer)
2277 memcpy(mpctx->nav_buffer,start,in_size);
2279 if (decoded_frame && mpctx->nav_smpi != decoded_frame)
2280 mpctx->nav_smpi = mp_dvdnav_copy_mpi(mpctx->nav_smpi,decoded_frame);
2282 #endif /* CONFIG_DVDNAV */
2284 /* Modify video timing to match the audio timeline. There are two main
2285 * reasons this is needed. First, video and audio can start from different
2286 * positions at beginning of file or after a seek (MPlayer starts both
2287 * immediately even if they have different pts). Second, the file can have
2288 * audio timestamps that are inconsistent with the duration of the audio
2289 * packets, for example two consecutive timestamp values differing by
2290 * one second but only a packet with enough samples for half a second
2291 * of playback between them.
2293 static void adjust_sync(struct MPContext *mpctx, double frame_time)
2295 current_module = "av_sync";
2297 if (!mpctx->sh_audio || mpctx->syncing_audio)
2298 return;
2300 double a_pts = written_audio_pts(mpctx) - mpctx->delay;
2301 double v_pts = mpctx->sh_video->pts;
2302 double av_delay = a_pts - v_pts;
2303 // Try to sync vo_flip() so it will *finish* at given time
2304 av_delay += mpctx->last_vo_flip_duration;
2305 av_delay -= audio_delay; // This much pts difference is desired
2307 double change = av_delay * 0.1;
2308 double max_change = default_max_pts_correction >= 0 ?
2309 default_max_pts_correction : frame_time * 0.1;
2310 if (change < -max_change)
2311 change = -max_change;
2312 else if (change > max_change)
2313 change = max_change;
2314 mpctx->delay += change;
2315 mpctx->total_avsync_change += change;
2318 #define ASYNC_PLAY_DONE -3
2319 static int audio_start_sync(struct MPContext *mpctx, int playsize)
2321 struct ao *ao = mpctx->ao;
2322 struct MPOpts *opts = &mpctx->opts;
2323 sh_audio_t * const sh_audio = mpctx->sh_audio;
2324 int res;
2326 // Timing info may not be set without
2327 res = decode_audio(sh_audio, 1);
2328 if (res < 0)
2329 return res;
2331 int bytes;
2332 bool did_retry = false;
2333 while (1) {
2334 double written_pts = written_audio_pts(mpctx);
2335 double ptsdiff = written_pts - mpctx->video_pts - mpctx->delay
2336 - audio_delay;
2337 bytes = ptsdiff * ao->bps / mpctx->opts.playback_speed;
2338 bytes -= bytes % (ao->channels * af_fmt2bits(ao->format) / 8);
2340 // ogg demuxers give packets without timing
2341 if (written_pts <= 1 && sh_audio->pts == MP_NOPTS_VALUE) {
2342 if (!did_retry) {
2343 // Try to read more data to see packets that have pts
2344 int res = decode_audio(sh_audio, ao->bps);
2345 if (res < 0)
2346 return res;
2347 did_retry = true;
2348 continue;
2350 bytes = 0;
2353 if (fabs(ptsdiff) > 300) // pts reset or just broken?
2354 bytes = 0;
2356 if (bytes > 0)
2357 break;
2359 mpctx->syncing_audio = false;
2360 int a = FFMIN(-bytes, FFMAX(playsize, 20000));
2361 int res = decode_audio(sh_audio, a);
2362 bytes += sh_audio->a_out_buffer_len;
2363 if (bytes >= 0) {
2364 memmove(sh_audio->a_out_buffer,
2365 sh_audio->a_out_buffer +
2366 sh_audio->a_out_buffer_len - bytes,
2367 bytes);
2368 sh_audio->a_out_buffer_len = bytes;
2369 if (res < 0)
2370 return res;
2371 return decode_audio(sh_audio, playsize);
2373 sh_audio->a_out_buffer_len = 0;
2374 if (res < 0)
2375 return res;
2377 int fillbyte = 0;
2378 if ((ao->format & AF_FORMAT_SIGN_MASK) == AF_FORMAT_US)
2379 fillbyte = 0x80;
2380 if (bytes >= playsize) {
2381 /* This case could fall back to the one below with
2382 * bytes = playsize, but then silence would keep accumulating
2383 * in a_out_buffer if the AO accepts less data than it asks for
2384 * in playsize. */
2385 char *p = malloc(playsize);
2386 memset(p, fillbyte, playsize);
2387 playsize = ao_play(ao, p, playsize, 0);
2388 free(p);
2389 mpctx->delay += opts->playback_speed*playsize/(double)ao->bps;
2390 return ASYNC_PLAY_DONE;
2392 mpctx->syncing_audio = false;
2393 decode_audio_prepend_bytes(sh_audio, bytes, fillbyte);
2394 return decode_audio(sh_audio, playsize);
2397 static int fill_audio_out_buffers(struct MPContext *mpctx)
2399 struct MPOpts *opts = &mpctx->opts;
2400 struct ao *ao = mpctx->ao;
2401 unsigned int t;
2402 double tt;
2403 int playsize;
2404 int playflags=0;
2405 bool audio_eof = false;
2406 bool partial_fill = false;
2407 bool format_change = false;
2408 sh_audio_t * const sh_audio = mpctx->sh_audio;
2409 bool modifiable_audio_format = !(ao->format & AF_FORMAT_SPECIAL_MASK);
2410 int unitsize = ao->channels * af_fmt2bits(ao->format) / 8;
2412 current_module="play_audio";
2414 if (ao->untimed && mpctx->sh_video && mpctx->delay > 0)
2415 return 0;
2417 // all the current uses of ao->pts seem to be in aos that handle
2418 // sync completely wrong; there should be no need to use ao->pts
2419 // in get_space()
2420 ao->pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2421 playsize = ao_get_space(ao);
2423 // Fill buffer if needed:
2424 current_module="decode_audio";
2425 t = GetTimer();
2427 if (!opts->initial_audio_sync || !modifiable_audio_format)
2428 mpctx->syncing_audio = false;
2430 int res;
2431 if (mpctx->syncing_audio && mpctx->sh_video)
2432 res = audio_start_sync(mpctx, playsize);
2433 else
2434 res = decode_audio(sh_audio, playsize);
2435 if (res < 0) { // EOF, error or format change
2436 if (res == -2)
2437 format_change = true;
2438 else if (res == ASYNC_PLAY_DONE)
2439 return 0;
2440 else if (mpctx->d_audio->eof)
2441 audio_eof = true;
2443 t = GetTimer() - t;
2444 tt = t*0.000001f; audio_time_usage+=tt;
2445 if (mpctx->timeline && modifiable_audio_format) {
2446 double endpts = mpctx->timeline[mpctx->timeline_part + 1].start;
2447 double bytes = (endpts - written_audio_pts(mpctx) + audio_delay)
2448 * ao->bps / opts->playback_speed;
2449 if (playsize > bytes) {
2450 playsize = FFMAX(bytes, 0);
2451 playflags |= AOPLAY_FINAL_CHUNK;
2452 audio_eof = true;
2453 partial_fill = true;
2457 if (playsize > sh_audio->a_out_buffer_len) {
2458 partial_fill = true;
2459 playsize = sh_audio->a_out_buffer_len;
2460 if (audio_eof)
2461 playflags |= AOPLAY_FINAL_CHUNK;
2463 playsize -= playsize % unitsize;
2464 if (!playsize)
2465 return partial_fill && audio_eof ? -2 : -partial_fill;
2467 // play audio:
2468 current_module="play_audio";
2470 // Is this pts value actually useful for the aos that access it?
2471 // They're obviously badly broken in the way they handle av sync;
2472 // would not having access to this make them more broken?
2473 ao->pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2474 playsize = ao_play(ao, sh_audio->a_out_buffer, playsize, playflags);
2476 if (playsize > 0) {
2477 sh_audio->a_out_buffer_len -= playsize;
2478 memmove(sh_audio->a_out_buffer, &sh_audio->a_out_buffer[playsize],
2479 sh_audio->a_out_buffer_len);
2480 mpctx->delay += opts->playback_speed*playsize/(double)ao->bps;
2481 } else if (audio_eof && ao_get_delay(ao) < .04) {
2482 // Sanity check to avoid hanging in case current ao doesn't output
2483 // partial chunks and doesn't check for AOPLAY_FINAL_CHUNK
2484 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Audio output truncated at end.\n");
2485 sh_audio->a_out_buffer_len = 0;
2488 /* The format change isn't handled too gracefully. A more precise
2489 * implementation would require draining buffered old-format audio
2490 * while displaying video, then doing the output format switch.
2492 if (format_change) {
2493 uninit_player(mpctx, INITIALIZED_AO);
2494 reinit_audio_chain(mpctx);
2495 return -1;
2498 return -partial_fill;
2501 static int sleep_until_near_frame(struct MPContext *mpctx, float *time_frame,
2502 bool sync_to_audio, float *aq_sleep_time)
2504 struct MPOpts *opts = &mpctx->opts;
2505 double audio_limit = 2;
2506 current_module="calc_sleep_time";
2508 if (mpctx->restart_playback)
2509 return 0;
2511 *time_frame -= get_relative_time(mpctx); // reset timer
2513 if (sync_to_audio) {
2514 float delay = ao_get_delay(mpctx->ao);
2515 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "delay=%f\n", delay);
2517 if (opts->autosync) {
2519 * Adjust this raw delay value by calculating the expected
2520 * delay for this frame and generating a new value which is
2521 * weighted between the two. The higher autosync is, the
2522 * closer to the delay value gets to that which "-nosound"
2523 * would have used, and the longer it will take for A/V
2524 * sync to settle at the right value (but it eventually will.)
2525 * This settling time is very short for values below 100.
2527 float predicted = mpctx->delay / opts->playback_speed + *time_frame;
2528 float difference = delay - predicted;
2529 delay = predicted + difference / (float)opts->autosync;
2532 *time_frame = delay - mpctx->delay / opts->playback_speed;
2534 // delay = amount of audio buffered in soundcard/driver
2535 delay = FFMIN(delay, 0.5);
2536 delay = FFMAX(delay, 0.1);
2537 audio_limit = delay;
2538 } else {
2539 // If we're lagging more than 200 ms behind the right playback rate,
2540 // don't try to "catch up".
2541 // If benchmark is set always output frames as fast as possible
2542 // without sleeping.
2543 if (*time_frame < -0.2 || opts->benchmark)
2544 *time_frame = 0;
2547 double t = *time_frame - mpctx->video_out->flip_queue_offset;
2549 if (t <= 0.05)
2550 return 0;
2552 t -= 0.05;
2553 if (t > audio_limit * 0.6)
2554 t = audio_limit * 0.5;
2555 *aq_sleep_time += t;
2556 mp_input_get_cmd(mpctx->input, t * 1000 + 1, 1);
2557 return 1;
2560 int reinit_video_chain(struct MPContext *mpctx)
2562 struct MPOpts *opts = &mpctx->opts;
2563 sh_video_t * const sh_video = mpctx->sh_video;
2564 if (!sh_video)
2565 return 0;
2566 double ar=-1.0;
2567 //================== Init VIDEO (codec & libvo) ==========================
2568 if (!opts->fixed_vo || !(mpctx->initialized_flags & INITIALIZED_VO)) {
2569 current_module="preinit_libvo";
2571 //shouldn't we set dvideo->id=-2 when we fail?
2572 //if((mpctx->video_out->preinit(vo_subdevice))!=0){
2573 if(!(mpctx->video_out=init_best_video_out(opts, mpctx->x11_state, mpctx->key_fifo, mpctx->input))){
2574 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Error opening/initializing the selected video_out (-vo) device.\n");
2575 goto err_out;
2577 mpctx->initialized_flags|=INITIALIZED_VO;
2580 if(stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_ASPECT_RATIO, &ar) != STREAM_UNSUPPORTED)
2581 mpctx->sh_video->stream_aspect = ar;
2582 current_module="init_video_filters";
2584 char* vf_arg[] = { "_oldargs_", (char*)mpctx->video_out , NULL };
2585 sh_video->vfilter = vf_open_filter(opts, NULL,"vo",vf_arg);
2587 #ifdef CONFIG_MENU
2588 if(use_menu) {
2589 char* vf_arg[] = { "_oldargs_", menu_root, NULL };
2590 vf_menu = vf_open_plugin(opts,libmenu_vfs,sh_video->vfilter,"menu",vf_arg);
2591 if(!vf_menu) {
2592 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Can't open libmenu video filter with root menu %s.\n",menu_root);
2593 use_menu = 0;
2596 if(vf_menu)
2597 sh_video->vfilter = vf_menu;
2598 #endif
2600 #ifdef CONFIG_ASS
2601 if(opts->ass_enabled) {
2602 int i;
2603 int insert = 1;
2604 if (opts->vf_settings)
2605 for (i = 0; opts->vf_settings[i].name; ++i)
2606 if (strcmp(opts->vf_settings[i].name, "ass") == 0) {
2607 insert = 0;
2608 break;
2610 if (insert) {
2611 extern vf_info_t vf_info_ass;
2612 const vf_info_t* libass_vfs[] = {&vf_info_ass, NULL};
2613 char* vf_arg[] = {"auto", "1", NULL};
2614 int retcode = 0;
2615 struct vf_instance *vf_ass = vf_open_plugin_noerr(opts, libass_vfs,
2616 sh_video->vfilter,
2617 "ass", vf_arg,
2618 &retcode);
2619 if (vf_ass)
2620 sh_video->vfilter = vf_ass;
2621 else if (retcode == -1) // vf_ass open() returns -1 if there's VO EOSD
2622 mp_msg(MSGT_CPLAYER, MSGL_V, "[ass] vf_ass not needed\n");
2623 else
2624 mp_msg(MSGT_CPLAYER,MSGL_ERR, "ASS: cannot add video filter\n");
2627 #endif
2629 sh_video->vfilter = append_filters(sh_video->vfilter, opts->vf_settings);
2631 #ifdef CONFIG_ASS
2632 if (opts->ass_enabled)
2633 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_INIT_EOSD, ass_library);
2634 #endif
2636 current_module="init_video_codec";
2638 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2639 init_best_video_codec(sh_video,video_codec_list,video_fm_list);
2640 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2642 if(!sh_video->initialized){
2643 if(!opts->fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
2644 goto err_out;
2647 mpctx->initialized_flags|=INITIALIZED_VCODEC;
2649 if (sh_video->codec)
2650 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODEC=%s\n", sh_video->codec->name);
2652 sh_video->last_pts = MP_NOPTS_VALUE;
2653 sh_video->num_buffered_pts = 0;
2654 sh_video->next_frame_time = 0;
2656 if (opts->auto_quality > 0) {
2657 // Auto quality option enabled
2658 output_quality=get_video_quality_max(sh_video);
2659 if (opts->auto_quality > output_quality)
2660 opts->auto_quality = output_quality;
2661 else
2662 output_quality = opts->auto_quality;
2663 mp_msg(MSGT_CPLAYER,MSGL_V,"AutoQ: setting quality to %d.\n",output_quality);
2664 set_video_quality(sh_video,output_quality);
2667 // ========== Init display (sh_video->disp_w*sh_video->disp_h/out_fmt) ============
2669 current_module="init_vo";
2671 return 1;
2673 err_out:
2674 mpctx->sh_video = mpctx->d_video->sh = NULL;
2675 return 0;
2678 static double update_video_nocorrect_pts(struct MPContext *mpctx)
2680 struct sh_video *sh_video = mpctx->sh_video;
2681 double frame_time = 0;
2682 struct vo *video_out = mpctx->video_out;
2683 while (1) {
2684 current_module = "filter_video";
2685 // In nocorrect-pts mode there is no way to properly time these frames
2686 if (vo_get_buffered_frame(video_out, 0) >= 0)
2687 break;
2688 if (vf_output_queued_frame(sh_video->vfilter))
2689 break;
2690 unsigned char *packet = NULL;
2691 frame_time = sh_video->next_frame_time;
2692 if (mpctx->restart_playback)
2693 frame_time = 0;
2694 int in_size = video_read_frame(sh_video, &sh_video->next_frame_time,
2695 &packet, force_fps);
2696 if (in_size < 0) {
2697 #ifdef CONFIG_DVDNAV
2698 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
2699 if (mp_dvdnav_is_eof(mpctx->stream))
2700 return -1;
2701 if (mpctx->d_video)
2702 mpctx->d_video->eof = 0;
2703 if (mpctx->d_audio)
2704 mpctx->d_audio->eof = 0;
2705 mpctx->stream->eof = 0;
2706 } else
2707 #endif
2708 return -1;
2710 if (in_size > max_framesize)
2711 max_framesize = in_size;
2712 sh_video->timer += frame_time;
2713 if (mpctx->sh_audio)
2714 mpctx->delay -= frame_time;
2715 // video_read_frame can change fps (e.g. for ASF video)
2716 vo_fps = sh_video->fps;
2717 int framedrop_type = check_framedrop(mpctx, frame_time);
2718 current_module = "decode video";
2720 void *decoded_frame;
2721 #ifdef CONFIG_DVDNAV
2722 decoded_frame = mp_dvdnav_restore_smpi(mpctx, &in_size, &packet, NULL);
2723 if (in_size >= 0 && !decoded_frame)
2724 #endif
2725 decoded_frame = decode_video(sh_video, packet, in_size, framedrop_type,
2726 sh_video->pts);
2727 #ifdef CONFIG_DVDNAV
2728 // Save last still frame for future display
2729 mp_dvdnav_save_smpi(mpctx, in_size, packet, decoded_frame);
2730 #endif
2731 if (decoded_frame) {
2732 current_module = "filter video";
2733 filter_video(sh_video, decoded_frame, sh_video->pts);
2735 break;
2737 return frame_time;
2740 static void determine_frame_pts(struct MPContext *mpctx)
2742 struct sh_video *sh_video = mpctx->sh_video;
2743 struct MPOpts *opts = &mpctx->opts;
2745 if (opts->user_pts_assoc_mode) {
2746 sh_video->pts_assoc_mode = opts->user_pts_assoc_mode;
2747 } else if (sh_video->pts_assoc_mode == 0) {
2748 if (mpctx->d_video->demuxer->timestamp_type == TIMESTAMP_TYPE_PTS
2749 && sh_video->codec_reordered_pts != MP_NOPTS_VALUE)
2750 sh_video->pts_assoc_mode = 1;
2751 else
2752 sh_video->pts_assoc_mode = 2;
2753 } else {
2754 int probcount1 = sh_video->num_reordered_pts_problems;
2755 int probcount2 = sh_video->num_sorted_pts_problems;
2756 if (sh_video->pts_assoc_mode == 2) {
2757 int tmp = probcount1;
2758 probcount1 = probcount2;
2759 probcount2 = tmp;
2761 if (probcount1 >= probcount2 * 1.5 + 2) {
2762 sh_video->pts_assoc_mode = 3 - sh_video->pts_assoc_mode;
2763 mp_msg(MSGT_CPLAYER, MSGL_V, "Switching to pts association mode "
2764 "%d.\n", sh_video->pts_assoc_mode);
2767 sh_video->pts = sh_video->pts_assoc_mode == 1 ?
2768 sh_video->codec_reordered_pts : sh_video->sorted_pts;
2771 static double update_video(struct MPContext *mpctx)
2773 struct sh_video *sh_video = mpctx->sh_video;
2774 struct vo *video_out = mpctx->video_out;
2775 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_SET_OSD_OBJ,
2776 mpctx->osd); // hack for vf_expand
2777 if (!mpctx->opts.correct_pts)
2778 return update_video_nocorrect_pts(mpctx);
2780 double pts;
2782 while (1) {
2783 current_module = "filter_video";
2784 if (!mpctx->hrseek_active
2785 && vo_get_buffered_frame(video_out, false) >= 0)
2786 break;
2787 // XXX Time used in this call is not counted in any performance
2788 // timer now
2789 if (vf_output_queued_frame(sh_video->vfilter))
2790 break;
2791 unsigned char *packet = NULL;
2792 int in_size = ds_get_packet_pts(mpctx->d_video, &packet, &pts);
2793 if (pts != MP_NOPTS_VALUE)
2794 pts += mpctx->video_offset;
2795 bool hit_eof = false;
2796 if (in_size < 0) {
2797 // try to extract last frames in case of decoder lag
2798 in_size = 0;
2799 pts = MP_NOPTS_VALUE;
2800 hit_eof = true;
2802 if (in_size > max_framesize)
2803 max_framesize = in_size;
2804 current_module = "decode video";
2805 if (pts >= mpctx->hrseek_pts - .005)
2806 mpctx->hrseek_framedrop = false;
2807 int framedrop_type = mpctx->hrseek_framedrop ? 1 :
2808 check_framedrop(mpctx, sh_video->frametime);
2809 void *decoded_frame = decode_video(sh_video, packet, in_size,
2810 framedrop_type, pts);
2811 if (decoded_frame) {
2812 determine_frame_pts(mpctx);
2813 current_module = "filter video";
2814 filter_video(sh_video, decoded_frame, sh_video->pts);
2815 } else if (hit_eof) {
2816 if (vo_get_buffered_frame(video_out, true) < 0)
2817 return -1;
2819 break;
2822 if (!video_out->frame_loaded)
2823 return 0;
2825 pts = video_out->next_pts;
2826 if (pts == MP_NOPTS_VALUE) {
2827 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Video pts after filters MISSING\n");
2828 // Try to use decoder pts from before filters
2829 pts = sh_video->pts;
2830 if (pts == MP_NOPTS_VALUE)
2831 pts = sh_video->last_pts;
2833 if (mpctx->hrseek_active && pts < mpctx->hrseek_pts - .005) {
2834 vo_skip_frame(video_out);
2835 return 0;
2837 mpctx->hrseek_active = false;
2838 sh_video->pts = pts;
2839 if (sh_video->last_pts == MP_NOPTS_VALUE)
2840 sh_video->last_pts = sh_video->pts;
2841 else if (sh_video->last_pts > sh_video->pts) {
2842 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Decreasing video pts: %f < %f\n",
2843 sh_video->pts, sh_video->last_pts);
2844 /* If the difference in pts is small treat it as jitter around the
2845 * right value (possibly caused by incorrect timestamp ordering) and
2846 * just show this frame immediately after the last one.
2847 * Treat bigger differences as timestamp resets and start counting
2848 * timing of later frames from the position of this one. */
2849 if (sh_video->last_pts - sh_video->pts > 0.5)
2850 sh_video->last_pts = sh_video->pts;
2851 else
2852 sh_video->pts = sh_video->last_pts;
2854 double frame_time = sh_video->pts - sh_video->last_pts;
2855 sh_video->last_pts = sh_video->pts;
2856 sh_video->timer += frame_time;
2857 if (mpctx->sh_audio)
2858 mpctx->delay -= frame_time;
2859 return frame_time;
2862 void pause_player(struct MPContext *mpctx)
2864 if (mpctx->paused)
2865 return;
2866 mpctx->paused = 1;
2867 mpctx->step_frames = 0;
2868 mpctx->time_frame -= get_relative_time(mpctx);
2870 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2871 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2873 if (mpctx->ao && mpctx->sh_audio)
2874 ao_pause(mpctx->ao); // pause audio, keep data if possible
2877 void unpause_player(struct MPContext *mpctx)
2879 if (!mpctx->paused)
2880 return;
2881 mpctx->paused = 0;
2883 if (mpctx->ao && mpctx->sh_audio)
2884 ao_resume(mpctx->ao);
2885 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok
2886 && !mpctx->step_frames)
2887 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL); // resume video
2888 (void)get_relative_time(mpctx); // ignore time that passed during pause
2891 void add_step_frame(struct MPContext *mpctx)
2893 mpctx->step_frames++;
2894 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2895 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2896 unpause_player(mpctx);
2899 static void pause_loop(struct MPContext *mpctx)
2901 struct MPOpts *opts = &mpctx->opts;
2902 mp_cmd_t* cmd;
2903 #ifdef CONFIG_STREAM_CACHE
2904 int old_cache_fill = stream_cache_size > 0 ?
2905 cache_fill_status(mpctx->stream) : 0;
2906 #endif
2907 if (!opts->quiet) {
2908 if (opts->term_osd && !mpctx->sh_video) {
2909 set_osd_tmsg(OSD_MSG_PAUSE, 1, 0, " ===== PAUSE =====");
2910 update_osd_msg(mpctx);
2911 } else
2912 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "\n%s\r",
2913 mp_gtext(" ===== PAUSE ====="));
2914 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_PAUSED\n");
2917 while ( (cmd = mp_input_get_cmd(mpctx->input, 20, 1)) == NULL
2918 || cmd->id == MP_CMD_SET_MOUSE_POS || cmd->pausing == 4) {
2919 if (cmd) {
2920 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
2921 run_command(mpctx, cmd);
2922 mp_cmd_free(cmd);
2923 continue;
2925 if (mpctx->sh_video && mpctx->video_out)
2926 vo_check_events(mpctx->video_out);
2927 #ifdef CONFIG_MENU
2928 if (vf_menu)
2929 vf_menu_pause_update(vf_menu);
2930 #endif
2931 usec_sleep(20000);
2932 update_osd_msg(mpctx);
2933 int hack = vo_osd_changed(0);
2934 vo_osd_changed(hack);
2935 if (hack)
2936 break;
2937 #ifdef CONFIG_STREAM_CACHE
2938 if (!opts->quiet && stream_cache_size > 0) {
2939 int new_cache_fill = cache_fill_status(mpctx->stream);
2940 if (new_cache_fill != old_cache_fill) {
2941 if (opts->term_osd && !mpctx->sh_video) {
2942 set_osd_tmsg(OSD_MSG_PAUSE, 1, 0, "%s %d%%",
2943 mp_gtext(" ===== PAUSE ====="),
2944 new_cache_fill);
2945 update_osd_msg(mpctx);
2946 } else
2947 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "%s %d%%\r",
2948 mp_gtext(" ===== PAUSE ====="),
2949 new_cache_fill);
2950 old_cache_fill = new_cache_fill;
2953 #endif
2958 // Find the right mute status and record position for new file position
2959 static void edl_seek_reset(MPContext *mpctx)
2961 mpctx->edl_muted = 0;
2962 next_edl_record = edl_records;
2964 while (next_edl_record) {
2965 if (next_edl_record->start_sec >= get_current_time(mpctx))
2966 break;
2968 if (next_edl_record->action == EDL_MUTE)
2969 mpctx->edl_muted = !mpctx->edl_muted;
2970 next_edl_record = next_edl_record->next;
2972 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2973 mixer_mute(&mpctx->mixer);
2977 // Execute EDL command for the current position if one exists
2978 static void edl_update(MPContext *mpctx)
2980 if (!next_edl_record)
2981 return;
2983 if (!mpctx->sh_video) {
2984 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot use EDL without video, disabling.\n");
2985 free_edl(edl_records);
2986 next_edl_record = NULL;
2987 edl_records = NULL;
2988 return;
2991 if (get_current_time(mpctx) >= next_edl_record->start_sec) {
2992 if (next_edl_record->action == EDL_SKIP) {
2993 mpctx->osd_function = OSD_FFW;
2994 queue_seek(mpctx, MPSEEK_RELATIVE, next_edl_record->length_sec, 0);
2995 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_SKIP: start [%f], stop "
2996 "[%f], length [%f]\n", next_edl_record->start_sec,
2997 next_edl_record->stop_sec, next_edl_record->length_sec);
2999 else if (next_edl_record->action == EDL_MUTE) {
3000 mpctx->edl_muted = !mpctx->edl_muted;
3001 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
3002 mixer_mute(&mpctx->mixer);
3003 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_MUTE: [%f]\n",
3004 next_edl_record->start_sec );
3006 next_edl_record = next_edl_record->next;
3010 static void reinit_decoders(struct MPContext *mpctx)
3012 reinit_video_chain(mpctx);
3013 reinit_audio_chain(mpctx);
3014 mp_property_do("sub", M_PROPERTY_SET, &(int){mpctx->global_sub_pos}, mpctx);
3017 static void seek_reset(struct MPContext *mpctx, bool reset_ao)
3019 if (mpctx->sh_video) {
3020 current_module = "seek_video_reset";
3021 resync_video_stream(mpctx->sh_video);
3022 mpctx->sh_video->timer = 0;
3023 vo_seek_reset(mpctx->video_out);
3024 mpctx->sh_video->timer = 0;
3025 mpctx->sh_video->num_buffered_pts = 0;
3026 mpctx->sh_video->last_pts = MP_NOPTS_VALUE;
3027 mpctx->delay = 0;
3028 mpctx->time_frame = 0;
3029 mpctx->restart_playback = true;
3030 // Not all demuxers set d_video->pts during seek, so this value
3031 // (which is used by at least vobsub and edl code below) may
3032 // be completely wrong (probably 0).
3033 mpctx->sh_video->pts = mpctx->d_video->pts + mpctx->video_offset;
3034 mpctx->video_pts = mpctx->sh_video->pts;
3035 update_subtitles(mpctx, mpctx->sh_video->pts, mpctx->video_offset,
3036 true);
3037 update_teletext(mpctx->sh_video, mpctx->demuxer, 1);
3040 if (mpctx->sh_audio) {
3041 current_module = "seek_audio_reset";
3042 resync_audio_stream(mpctx->sh_audio);
3043 if (reset_ao)
3044 // stop audio, throwing away buffered data
3045 ao_reset(mpctx->ao);
3046 mpctx->sh_audio->a_buffer_len = 0;
3047 mpctx->sh_audio->a_out_buffer_len = 0;
3048 if (!mpctx->sh_video)
3049 update_subtitles(mpctx, mpctx->sh_audio->pts,
3050 mpctx->video_offset, true);
3053 if (vo_vobsub && mpctx->sh_video) {
3054 current_module = "seek_vobsub_reset";
3055 vobsub_seek(vo_vobsub, mpctx->sh_video->pts);
3058 edl_seek_reset(mpctx);
3060 mpctx->hrseek_active = false;
3061 mpctx->hrseek_framedrop = false;
3062 mpctx->total_avsync_change = 0;
3063 audio_time_usage = 0; video_time_usage = 0; vout_time_usage = 0;
3064 drop_frame_cnt = 0;
3066 current_module = NULL;
3069 static bool timeline_set_part(struct MPContext *mpctx, int i)
3071 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
3072 struct timeline_part *n = mpctx->timeline + i;
3073 mpctx->timeline_part = i;
3074 mpctx->video_offset = n->start - n->source_start;
3075 if (n->source == p->source)
3076 return false;
3077 enum stop_play_reason orig_stop_play = mpctx->stop_play;
3078 if (!mpctx->sh_video && mpctx->stop_play == KEEP_PLAYING)
3079 mpctx->stop_play = AT_END_OF_FILE; // let audio uninit drain data
3080 uninit_player(mpctx, INITIALIZED_VCODEC | (mpctx->opts.fixed_vo ? 0 : INITIALIZED_VO) | (mpctx->opts.gapless_audio ? 0 : INITIALIZED_AO) | INITIALIZED_ACODEC | INITIALIZED_SUB);
3081 mpctx->stop_play = orig_stop_play;
3082 mpctx->demuxer = n->source->demuxer;
3083 mpctx->d_video = mpctx->demuxer->video;
3084 mpctx->d_audio = mpctx->demuxer->audio;
3085 mpctx->d_sub = mpctx->demuxer->sub;
3086 mpctx->sh_video = mpctx->d_video->sh;
3087 mpctx->sh_audio = mpctx->d_audio->sh;
3088 return true;
3091 // Given pts, switch playback to the corresponding part.
3092 // Return offset within that part.
3093 static double timeline_set_from_time(struct MPContext *mpctx, double pts,
3094 bool *need_reset)
3096 if (pts < 0)
3097 pts = 0;
3098 for (int i = 0; i < mpctx->num_timeline_parts; i++) {
3099 struct timeline_part *p = mpctx->timeline + i;
3100 if (pts < (p+1)->start) {
3101 *need_reset = timeline_set_part(mpctx, i);
3102 return pts - p->start + p->source_start;
3105 return -1;
3109 // return -1 if seek failed (non-seekable stream?), 0 otherwise
3110 static int seek(MPContext *mpctx, struct seek_params seek,
3111 bool timeline_fallthrough)
3113 struct MPOpts *opts = &mpctx->opts;
3115 current_module = "seek";
3116 if (mpctx->stop_play == AT_END_OF_FILE)
3117 mpctx->stop_play = KEEP_PLAYING;
3118 bool hr_seek = mpctx->demuxer->accurate_seek && opts->correct_pts;
3119 hr_seek &= seek.exact >= 0 && seek.type != MPSEEK_FACTOR;
3120 hr_seek &= opts->hr_seek == 0 && seek.type == MPSEEK_ABSOLUTE
3121 || opts->hr_seek > 0 || seek.exact > 0;
3122 if (seek.type == MPSEEK_FACTOR
3123 || seek.type == MPSEEK_ABSOLUTE
3124 && seek.amount < mpctx->last_chapter_pts
3125 || seek.amount < 0)
3126 mpctx->last_chapter_seek = -1;
3127 if (mpctx->timeline && seek.type == MPSEEK_FACTOR) {
3128 seek.amount *= mpctx->timeline[mpctx->num_timeline_parts].start;
3129 seek.type = MPSEEK_ABSOLUTE;
3131 if ((mpctx->demuxer->accurate_seek || mpctx->timeline)
3132 && seek.type == MPSEEK_RELATIVE) {
3133 seek.type = MPSEEK_ABSOLUTE;
3134 seek.direction = seek.amount > 0 ? 1 : -1;
3135 seek.amount += get_current_time(mpctx);
3138 /* At least the liba52 decoder wants to read from the input stream
3139 * during initialization, so reinit must be done after the demux_seek()
3140 * call that clears possible stream EOF. */
3141 bool need_reset = false;
3142 double demuxer_amount = seek.amount;
3143 if (mpctx->timeline) {
3144 demuxer_amount = timeline_set_from_time(mpctx, seek.amount,
3145 &need_reset);
3146 if (demuxer_amount == -1) {
3147 mpctx->stop_play = AT_END_OF_FILE;
3148 // Clear audio from current position
3149 if (mpctx->sh_audio) {
3150 ao_reset(mpctx->ao);
3151 mpctx->sh_audio->a_buffer_len = 0;
3152 mpctx->sh_audio->a_out_buffer_len = 0;
3154 return -1;
3157 int demuxer_style = 0;
3158 switch (seek.type) {
3159 case MPSEEK_FACTOR:
3160 demuxer_style |= SEEK_FACTOR; // fallthrough
3161 case MPSEEK_ABSOLUTE:
3162 demuxer_style |= SEEK_ABSOLUTE;
3164 if (hr_seek || seek.direction < 0)
3165 demuxer_style |= SEEK_BACKWARD;
3166 else if (seek.direction > 0)
3167 demuxer_style |= SEEK_FORWARD;
3169 int seekresult = demux_seek(mpctx->demuxer, demuxer_amount, audio_delay,
3170 demuxer_style);
3171 if (need_reset)
3172 reinit_decoders(mpctx);
3173 if (seekresult == 0)
3174 return -1;
3176 seek_reset(mpctx, !timeline_fallthrough);
3178 /* Use the target time as "current position" for further relative
3179 * seeks etc until a new video frame has been decoded */
3180 if (seek.type == MPSEEK_ABSOLUTE)
3181 mpctx->video_pts = seek.amount;
3183 if (hr_seek) {
3184 mpctx->hrseek_active = true;
3185 mpctx->hrseek_framedrop = true;
3186 mpctx->hrseek_pts = seek.amount;
3189 mpctx->start_timestamp = GetTimerMS();
3191 return 0;
3194 void queue_seek(struct MPContext *mpctx, enum seek_type type, double amount,
3195 int exact)
3197 struct seek_params *seek = &mpctx->seek;
3198 switch (type) {
3199 case MPSEEK_RELATIVE:
3200 if (seek->type == MPSEEK_FACTOR)
3201 return; // Well... not common enough to bother doing better
3202 seek->amount += amount;
3203 seek->exact = FFMAX(seek->exact, exact);
3204 if (seek->type == MPSEEK_NONE)
3205 seek->exact = exact;
3206 if (seek->type == MPSEEK_ABSOLUTE)
3207 return;
3208 if (seek->amount == 0) {
3209 *seek = (struct seek_params){0};
3210 return;
3212 seek->type = MPSEEK_RELATIVE;
3213 return;
3214 case MPSEEK_ABSOLUTE:
3215 case MPSEEK_FACTOR:
3216 *seek = (struct seek_params) {
3217 .type = type,
3218 .amount = amount,
3219 .exact = exact,
3221 return;
3222 case MPSEEK_NONE:
3223 *seek = (struct seek_params){0};
3224 return;
3226 abort();
3230 double get_time_length(struct MPContext *mpctx)
3232 if (mpctx->timeline)
3233 return mpctx->timeline[mpctx->num_timeline_parts].start;
3235 struct demuxer *demuxer = mpctx->demuxer;
3236 double get_time_ans;
3237 // <= 0 means DEMUXER_CTRL_NOTIMPL or DEMUXER_CTRL_DONTKNOW
3238 if (demux_control(demuxer, DEMUXER_CTRL_GET_TIME_LENGTH,
3239 (void *) &get_time_ans) > 0)
3240 return get_time_ans;
3242 struct sh_video *sh_video = mpctx->d_video->sh;
3243 struct sh_audio *sh_audio = mpctx->d_audio->sh;
3244 if (sh_video && sh_video->i_bps && sh_audio && sh_audio->i_bps)
3245 return (double) (demuxer->movi_end - demuxer->movi_start) /
3246 (sh_video->i_bps + sh_audio->i_bps);
3247 if (sh_video && sh_video->i_bps)
3248 return (double) (demuxer->movi_end - demuxer->movi_start) /
3249 sh_video->i_bps;
3250 if (sh_audio && sh_audio->i_bps)
3251 return (double) (demuxer->movi_end - demuxer->movi_start) /
3252 sh_audio->i_bps;
3253 return 0;
3256 /* If there are timestamps from stream level then use those (for example
3257 * DVDs can have consistent times there while the MPEG-level timestamps
3258 * reset). */
3259 double get_current_time(struct MPContext *mpctx)
3261 struct demuxer *demuxer = mpctx->demuxer;
3262 if (demuxer->stream_pts != MP_NOPTS_VALUE)
3263 return demuxer->stream_pts;
3264 struct sh_video *sh_video = demuxer->video->sh;
3265 if (sh_video)
3266 return mpctx->video_pts;
3267 return playing_audio_pts(mpctx);
3270 int get_percent_pos(struct MPContext *mpctx)
3272 struct demuxer *demuxer = mpctx->demuxer;
3273 int ans = 0;
3274 if (mpctx->timeline)
3275 ans = get_current_time(mpctx) * 100 /
3276 mpctx->timeline[mpctx->num_timeline_parts].start;
3277 else if (demux_control(demuxer, DEMUXER_CTRL_GET_PERCENT_POS, &ans) > 0)
3279 else {
3280 int len = (demuxer->movi_end - demuxer->movi_start) / 100;
3281 off_t pos = demuxer->filepos > 0 ?
3282 demuxer->filepos : stream_tell(demuxer->stream);
3283 if (len > 0)
3284 ans = (pos - demuxer->movi_start) / len;
3285 else
3286 ans = 0;
3288 if (ans < 0)
3289 ans = 0;
3290 if (ans > 100)
3291 ans = 100;
3292 return ans;
3295 // -2 is no chapters, -1 is before first chapter
3296 int get_current_chapter(struct MPContext *mpctx)
3298 double current_pts = get_current_time(mpctx);
3299 if (!mpctx->chapters)
3300 return FFMAX(mpctx->last_chapter_seek,
3301 demuxer_get_current_chapter(mpctx->demuxer, current_pts));
3303 int i;
3304 for (i = 1; i < mpctx->num_chapters; i++)
3305 if (current_pts < mpctx->chapters[i].start)
3306 break;
3307 return FFMAX(mpctx->last_chapter_seek, i - 1);
3310 // currently returns a string allocated with malloc, not talloc
3311 char *chapter_display_name(struct MPContext *mpctx, int chapter)
3313 if (!mpctx->chapters || !mpctx->sh_video)
3314 return demuxer_chapter_display_name(mpctx->demuxer, chapter);
3315 return strdup(mpctx->chapters[chapter].name);
3318 int seek_chapter(struct MPContext *mpctx, int chapter, double *seek_pts,
3319 char **chapter_name)
3321 mpctx->last_chapter_seek = -1;
3322 if (!mpctx->chapters || !mpctx->sh_video) {
3323 int res = demuxer_seek_chapter(mpctx->demuxer, chapter, seek_pts,
3324 chapter_name);
3325 if (res >= 0) {
3326 if (*seek_pts == -1)
3327 seek_reset(mpctx, true);
3328 else {
3329 mpctx->last_chapter_seek = res;
3330 mpctx->last_chapter_pts = *seek_pts;
3333 return res;
3336 if (chapter >= mpctx->num_chapters)
3337 return -1;
3338 if (chapter < 0)
3339 chapter = 0;
3340 *seek_pts = mpctx->chapters[chapter].start;
3341 mpctx->last_chapter_seek = chapter;
3342 mpctx->last_chapter_pts = *seek_pts;
3343 if (chapter_name)
3344 *chapter_name = talloc_strdup(NULL, mpctx->chapters[chapter].name);
3345 return chapter;
3349 static void run_playloop(struct MPContext *mpctx)
3351 struct MPOpts *opts = &mpctx->opts;
3352 float aq_sleep_time = 0;
3353 bool full_audio_buffers = false;
3355 if (opts->chapterrange[1] > 0) {
3356 int cur_chapter = get_current_chapter(mpctx);
3357 if (cur_chapter!=-1 && cur_chapter + 1 > opts->chapterrange[1])
3358 mpctx->stop_play = PT_NEXT_ENTRY;
3361 if (!mpctx->sh_audio && mpctx->d_audio->sh) {
3362 mpctx->sh_audio = mpctx->d_audio->sh;
3363 mpctx->sh_audio->ds = mpctx->d_audio;
3364 reinit_audio_chain(mpctx);
3367 /*========================== PLAY AUDIO ============================*/
3369 if (mpctx->sh_audio && !mpctx->paused
3370 && (!mpctx->restart_playback || !mpctx->sh_video)) {
3371 int status = fill_audio_out_buffers(mpctx);
3372 full_audio_buffers = status >= 0 && !mpctx->ao->untimed;
3373 if (status == -2)
3374 // at eof, all audio at least written to ao
3375 if (!mpctx->sh_video)
3376 mpctx->stop_play = AT_END_OF_FILE;
3380 if (!mpctx->sh_video) {
3381 mpctx->restart_playback = false;
3382 if (mpctx->step_frames) {
3383 mpctx->step_frames = 0;
3384 pause_player(mpctx);
3386 // handle audio-only case:
3387 double a_pos = 0, a_buf = 0;
3388 // sh_audio can be NULL due to video stream switching
3389 // TODO: handle this better
3390 if (mpctx->sh_audio) {
3391 a_buf = ao_get_delay(mpctx->ao);
3392 a_pos = written_audio_pts(mpctx) - mpctx->opts.playback_speed *
3393 a_buf;
3396 print_status(mpctx, a_pos, false);
3398 update_subtitles(mpctx, a_pos, mpctx->video_offset, false);
3399 update_osd_msg(mpctx);
3400 if (end_at.type == END_AT_TIME && end_at.pos < a_pos) {
3401 mpctx->stop_play = AT_END_OF_FILE;
3402 } else if (mpctx->timeline && mpctx->stop_play == AT_END_OF_FILE
3403 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts
3404 && mpctx->sh_audio) {
3405 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
3406 if (!opts->gapless_audio && p->source != (p+1)->source
3407 && a_buf > 0.05) {
3408 mpctx->stop_play = KEEP_PLAYING;
3409 mp_input_get_cmd(mpctx->input, (a_buf-.05) * 1000, true);
3410 } else {
3411 seek(mpctx, (struct seek_params){ .type = MPSEEK_ABSOLUTE,
3412 .amount = (p+1)->start },
3413 true);
3415 } else if (!mpctx->stop_play) {
3416 int sleep_time = 100;
3417 if (mpctx->sh_audio) {
3418 if (mpctx->ao->untimed)
3419 sleep_time = 0;
3420 else if (full_audio_buffers)
3421 sleep_time = FFMAX(20, a_buf * 1000 - 50);
3422 else
3423 sleep_time = 20;
3424 sleep_time = FFMIN(sleep_time, 100);
3426 mp_input_get_cmd(mpctx->input, sleep_time, true);
3428 } else {
3430 /*========================== PLAY VIDEO ============================*/
3432 vo_pts = mpctx->sh_video->timer * 90000.0;
3433 vo_fps = mpctx->sh_video->fps;
3435 bool blit_frame = mpctx->video_out->frame_loaded;
3436 if (!blit_frame || mpctx->hrseek_active) {
3437 double frame_time = update_video(mpctx);
3438 blit_frame = mpctx->video_out->frame_loaded;
3439 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "*** ftime=%5.3f ***\n", frame_time);
3440 if (mpctx->sh_video->vf_initialized < 0) {
3441 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
3442 "\nFATAL: Could not initialize video filters (-vf) "
3443 "or video output (-vo).\n");
3444 mpctx->stop_play = PT_NEXT_ENTRY;
3445 return;
3447 if (frame_time < 0)
3448 mpctx->stop_play = AT_END_OF_FILE;
3449 else if (!mpctx->restart_playback) {
3450 mpctx->time_frame += frame_time / opts->playback_speed;
3451 adjust_sync(mpctx, frame_time);
3454 if (mpctx->timeline) {
3455 struct timeline_part *next =
3456 mpctx->timeline + mpctx->timeline_part + 1;
3457 if (mpctx->sh_video->pts >= next->start
3458 || mpctx->stop_play == AT_END_OF_FILE
3459 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts) {
3460 seek(mpctx, (struct seek_params){ .type = MPSEEK_ABSOLUTE,
3461 .amount = next->start },
3462 true);
3463 return;
3467 // ==========================================================================
3469 current_module = "vo_check_events";
3470 vo_check_events(mpctx->video_out);
3472 #ifdef CONFIG_X11
3473 if (stop_xscreensaver) {
3474 current_module = "stop_xscreensaver";
3475 xscreensaver_heartbeat(mpctx->x11_state);
3477 #endif
3478 if (heartbeat_cmd) {
3479 static unsigned last_heartbeat;
3480 unsigned now = GetTimerMS();
3481 if (now - last_heartbeat > 30000) {
3482 last_heartbeat = now;
3483 system(heartbeat_cmd);
3487 bool frame_time_remaining = sleep_until_near_frame(mpctx,
3488 &mpctx->time_frame,
3489 full_audio_buffers,
3490 &aq_sleep_time);
3492 //====================== FLIP PAGE (VIDEO BLT): =========================
3494 current_module = "flip_page";
3495 if (!frame_time_remaining && blit_frame) {
3496 struct sh_video *sh_video = mpctx->sh_video;
3497 mpctx->video_pts = sh_video->pts;
3498 update_subtitles(mpctx, sh_video->pts, mpctx->video_offset, false);
3499 update_teletext(sh_video, mpctx->demuxer, 0);
3500 update_osd_msg(mpctx);
3501 struct vf_instance *vf = sh_video->vfilter;
3502 vf->control(vf, VFCTRL_DRAW_EOSD, mpctx->osd);
3503 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
3504 vo_osd_changed(0);
3506 mpctx->time_frame -= mpctx->video_out->flip_queue_offset;
3507 aq_sleep_time += mpctx->time_frame;
3508 // flag 256 means: libvo driver does its timing (dvb card)
3509 if (mpctx->time_frame > 0.001
3510 && !(mpctx->sh_video->output_flags & VFCAP_TIMER))
3511 mpctx->time_frame = timing_sleep(mpctx, mpctx->time_frame);
3512 mpctx->time_frame += mpctx->video_out->flip_queue_offset;
3514 unsigned int t2 = GetTimer();
3515 /* Playing with playback speed it's possible to get pathological
3516 * cases with mpctx->time_frame negative enough to cause an
3517 * overflow in pts_us calculation, thus the FFMAX. */
3518 double time_frame = FFMAX(mpctx->time_frame, -1);
3519 unsigned int pts_us = mpctx->last_time + time_frame * 1e6;
3520 int duration = -1;
3521 double pts2 = mpctx->video_out->next_pts2;
3522 if (pts2 != MP_NOPTS_VALUE && opts->correct_pts
3523 && !mpctx->restart_playback) {
3524 // expected A/V sync correction is ignored
3525 double diff = (pts2 - mpctx->video_pts);
3526 diff /= opts->playback_speed;
3527 if (mpctx->time_frame < 0)
3528 diff += mpctx->time_frame;
3529 if (diff < 0)
3530 diff = 0;
3531 if (diff > 10)
3532 diff = 10;
3533 duration = diff * 1e6;
3535 vo_flip_page(mpctx->video_out, pts_us | 1, duration);
3537 mpctx->last_vo_flip_duration = (GetTimer() - t2) * 0.000001;
3538 vout_time_usage += mpctx->last_vo_flip_duration;
3539 if (mpctx->video_out->driver->flip_page_timed) {
3540 // No need to adjust sync based on flip speed
3541 mpctx->last_vo_flip_duration = 0;
3542 // For print_status - VO call finishing early is OK for sync
3543 mpctx->time_frame -= get_relative_time(mpctx);
3545 if (mpctx->restart_playback) {
3546 mpctx->syncing_audio = true;
3547 if (mpctx->sh_audio && !mpctx->paused)
3548 fill_audio_out_buffers(mpctx);
3549 mpctx->restart_playback = false;
3550 mpctx->time_frame = 0;
3551 get_relative_time(mpctx);
3553 print_status(mpctx, MP_NOPTS_VALUE, true);
3554 } else
3555 print_status(mpctx, MP_NOPTS_VALUE, false);
3557 //============================ Auto QUALITY ============================
3559 /*Output quality adjustments:*/
3560 if (opts->auto_quality > 0) {
3561 current_module = "autoq";
3562 if (output_quality < opts->auto_quality && aq_sleep_time > 0)
3563 ++output_quality;
3564 else
3565 if (output_quality>1 && aq_sleep_time<0)
3566 --output_quality;
3567 else if (output_quality>0 && aq_sleep_time<-0.050f) // 50ms
3568 output_quality = 0;
3569 set_video_quality(mpctx->sh_video, output_quality);
3572 if (!frame_time_remaining && blit_frame) {
3573 if (play_n_frames >= 0) {
3574 --play_n_frames;
3575 if (play_n_frames <= 0)
3576 mpctx->stop_play = PT_NEXT_ENTRY;
3578 if (mpctx->step_frames > 0) {
3579 mpctx->step_frames--;
3580 if (mpctx->step_frames == 0)
3581 pause_player(mpctx);
3585 // FIXME: add size based support for -endpos
3586 if (end_at.type == END_AT_TIME &&
3587 !frame_time_remaining && end_at.pos <= mpctx->sh_video->pts)
3588 mpctx->stop_play = PT_NEXT_ENTRY;
3590 } // end if(mpctx->sh_video)
3592 #ifdef CONFIG_DVDNAV
3593 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
3594 nav_highlight_t hl;
3595 mp_dvdnav_get_highlight(mpctx->stream, &hl);
3596 if (!vo_spudec || !spudec_apply_palette_crop(vo_spudec, hl.palette, hl.sx, hl.sy, hl.ex, hl.ey)) {
3597 osd_set_nav_box(hl.sx, hl.sy, hl.ex, hl.ey);
3598 vo_osd_changed(OSDTYPE_DVDNAV);
3599 } else {
3600 osd_set_nav_box(0, 0, 0, 0);
3601 vo_osd_changed(OSDTYPE_DVDNAV);
3602 vo_osd_changed(OSDTYPE_SPU);
3605 if (mp_dvdnav_stream_has_changed(mpctx->stream)) {
3606 double ar = -1.0;
3607 if (mpctx->sh_video &&
3608 stream_control(mpctx->demuxer->stream,
3609 STREAM_CTRL_GET_ASPECT_RATIO, &ar)
3610 != STREAM_UNSUPPORTED)
3611 mpctx->sh_video->stream_aspect = ar;
3614 #endif
3616 //================= Keyboard events, SEEKing ====================
3618 current_module = "key_events";
3620 while (1) {
3621 mp_cmd_t *cmd;
3622 while ((cmd = mp_input_get_cmd(mpctx->input, 0, 1)) != NULL) {
3623 /* Allow running consecutive seek commands to combine them,
3624 * but execute the seek before running other commands.
3625 * If the user seeks continuously (keeps arrow key down)
3626 * try to finish showing a frame from one location before doing
3627 * another seek (which could lead to unchanging display). */
3628 if (mpctx->seek.type && cmd->id != MP_CMD_SEEK
3629 || mpctx->restart_playback && cmd->id == MP_CMD_SEEK
3630 && GetTimerMS() - mpctx->start_timestamp < 300)
3631 break;
3632 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
3633 run_command(mpctx, cmd);
3634 mp_cmd_free(cmd);
3635 if (mpctx->stop_play)
3636 break;
3638 if (!mpctx->paused || mpctx->stop_play || mpctx->seek.type
3639 || mpctx->restart_playback)
3640 break;
3641 if (mpctx->sh_video) {
3642 update_osd_msg(mpctx);
3643 int hack = vo_osd_changed(0);
3644 vo_osd_changed(hack);
3645 if (hack) {
3646 if (redraw_osd(mpctx->sh_video, mpctx->osd) < 0) {
3647 add_step_frame(mpctx);
3648 break;
3649 } else
3650 vo_osd_changed(0);
3653 pause_loop(mpctx);
3656 // handle -sstep
3657 if (step_sec > 0 && !mpctx->paused) {
3658 mpctx->osd_function = OSD_FFW;
3659 queue_seek(mpctx, MPSEEK_RELATIVE, step_sec, 0);
3662 edl_update(mpctx);
3664 /* Looping. */
3665 if (mpctx->stop_play==AT_END_OF_FILE && opts->loop_times>=0) {
3666 mp_msg(MSGT_CPLAYER, MSGL_V, "loop_times = %d\n", opts->loop_times);
3668 if (opts->loop_times>1)
3669 opts->loop_times--;
3670 else if (opts->loop_times==1)
3671 opts->loop_times = -1;
3672 play_n_frames = play_n_frames_mf;
3673 mpctx->stop_play = 0;
3674 queue_seek(mpctx, MPSEEK_ABSOLUTE, 0, 0);
3677 if (mpctx->seek.type) {
3678 seek(mpctx, mpctx->seek, false);
3679 mpctx->seek = (struct seek_params){0};
3684 static int read_keys(void *ctx, int fd)
3686 getch2(ctx);
3687 return mplayer_get_key(ctx, 0);
3690 static bool attachment_is_font(struct demux_attachment *att)
3692 if (!att->name || !att->type || !att->data || !att->data_size)
3693 return false;
3694 // match against MIME types
3695 if (strcmp(att->type, "application/x-truetype-font") == 0
3696 || strcmp(att->type, "application/x-font") == 0)
3697 return true;
3698 // fallback: match against file extension
3699 if (strlen(att->name) > 4) {
3700 char *ext = att->name + strlen(att->name) - 4;
3701 if (strcasecmp(ext, ".ttf") == 0 || strcasecmp(ext, ".ttc") == 0
3702 || strcasecmp(ext, ".otf") == 0)
3703 return true;
3705 return false;
3708 static int select_audio(demuxer_t *demuxer, int audio_id, char **audio_lang)
3710 if (audio_id == -1)
3711 audio_id = demuxer_audio_track_by_lang_and_default(demuxer, audio_lang);
3712 if (audio_id != -1) // -1 (automatic) is the default behaviour of demuxers
3713 demuxer_switch_audio(demuxer, audio_id);
3714 if (audio_id == -2) { // some demuxers don't yet know how to switch to no sound
3715 demuxer->audio->id = -2;
3716 demuxer->audio->sh = NULL;
3718 return demuxer->audio->id;
3721 static void print_version(const char* name)
3723 mp_msg(MSGT_CPLAYER, MSGL_INFO, MP_TITLE, name);
3725 /* Test for CPU capabilities (and corresponding OS support) for optimizing */
3726 GetCpuCaps(&gCpuCaps);
3727 #if ARCH_X86
3728 mp_msg(MSGT_CPLAYER, MSGL_V,
3729 "CPUflags: MMX: %d MMX2: %d 3DNow: %d 3DNowExt: %d SSE: %d SSE2: %d SSSE3: %d\n",
3730 gCpuCaps.hasMMX, gCpuCaps.hasMMX2,
3731 gCpuCaps.has3DNow, gCpuCaps.has3DNowExt,
3732 gCpuCaps.hasSSE, gCpuCaps.hasSSE2, gCpuCaps.hasSSSE3);
3733 #if CONFIG_RUNTIME_CPUDETECT
3734 mp_tmsg(MSGT_CPLAYER,MSGL_V, "Compiled with runtime CPU detection.\n");
3735 #else
3736 mp_tmsg(MSGT_CPLAYER,MSGL_V, "Compiled for x86 CPU with extensions:");
3737 if (HAVE_MMX)
3738 mp_msg(MSGT_CPLAYER,MSGL_V," MMX");
3739 if (HAVE_MMX2)
3740 mp_msg(MSGT_CPLAYER,MSGL_V," MMX2");
3741 if (HAVE_AMD3DNOW)
3742 mp_msg(MSGT_CPLAYER,MSGL_V," 3DNow");
3743 if (HAVE_AMD3DNOWEXT)
3744 mp_msg(MSGT_CPLAYER,MSGL_V," 3DNowExt");
3745 if (HAVE_SSE)
3746 mp_msg(MSGT_CPLAYER,MSGL_V," SSE");
3747 if (HAVE_SSE2)
3748 mp_msg(MSGT_CPLAYER,MSGL_V," SSE2");
3749 if (HAVE_SSSE3)
3750 mp_msg(MSGT_CPLAYER,MSGL_V," SSSE3");
3751 if (HAVE_CMOV)
3752 mp_msg(MSGT_CPLAYER,MSGL_V," CMOV");
3753 mp_msg(MSGT_CPLAYER,MSGL_V,"\n");
3754 #endif /* CONFIG_RUNTIME_CPUDETECT */
3755 #endif /* ARCH_X86 */
3758 #ifdef PTW32_STATIC_LIB
3759 static void detach_ptw32(void)
3761 pthread_win32_thread_detach_np();
3762 pthread_win32_process_detach_np();
3764 #endif
3766 /* This preprocessor directive is a hack to generate a mplayer-nomain.o object
3767 * file for some tools to link against. */
3768 #ifndef DISABLE_MAIN
3769 int main(int argc,char* argv[]){
3770 #ifdef PTW32_STATIC_LIB
3771 pthread_win32_process_attach_np();
3772 pthread_win32_thread_attach_np();
3773 atexit(detach_ptw32);
3774 #endif
3775 if (argc > 1 && !strcmp(argv[1], "-leak-report"))
3776 talloc_enable_leak_report();
3778 char * mem_ptr;
3780 // movie info:
3782 /* Flag indicating whether MPlayer should exit without playing anything. */
3783 int opt_exit = 0;
3784 int i;
3786 struct MPContext *mpctx = &(struct MPContext){
3787 .osd_function = OSD_PLAY,
3788 .begin_skip = MP_NOPTS_VALUE,
3789 .play_tree_step = 1,
3790 .global_sub_pos = -1,
3791 .set_of_sub_pos = -1,
3792 .file_format = DEMUXER_TYPE_UNKNOWN,
3793 .last_dvb_step = 1,
3796 InitTimer();
3797 srand(GetTimerMS());
3799 mp_msg_init();
3800 set_av_log_callback();
3802 #ifdef CONFIG_X11
3803 mpctx->x11_state = vo_x11_init_state();
3804 #endif
3805 struct MPOpts *opts = &mpctx->opts;
3806 set_default_mplayer_options(opts);
3807 // Create the config context and register the options
3808 mpctx->mconfig = m_config_new(opts, cfg_include);
3809 m_config_register_options(mpctx->mconfig,mplayer_opts);
3810 m_config_register_options(mpctx->mconfig, common_opts);
3811 mp_input_register_options(mpctx->mconfig);
3813 // Preparse the command line
3814 m_config_preparse_command_line(mpctx->mconfig,argc,argv);
3816 #if (defined(__MINGW32__) || defined(__CYGWIN__)) && defined(CONFIG_WIN32DLL)
3817 set_path_env();
3818 #endif
3820 #ifdef CONFIG_TV
3821 stream_tv_defaults.immediate = 1;
3822 #endif
3824 parse_cfgfiles(mpctx, mpctx->mconfig);
3826 mpctx->playtree = m_config_parse_mp_command_line(mpctx->mconfig, argc, argv);
3827 if(mpctx->playtree == NULL)
3828 opt_exit = 1;
3829 else {
3830 mpctx->playtree = play_tree_cleanup(mpctx->playtree);
3831 if(mpctx->playtree) {
3832 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,mpctx->mconfig);
3833 if(mpctx->playtree_iter) {
3834 if(play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
3835 play_tree_iter_free(mpctx->playtree_iter);
3836 mpctx->playtree_iter = NULL;
3838 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,1);
3842 mpctx->key_fifo = mp_fifo_create(opts);
3844 print_version("MPlayer2");
3846 #if defined(__MINGW32__) || defined(__CYGWIN__)
3848 HMODULE kernel32 = GetModuleHandle("Kernel32.dll");
3849 BOOL WINAPI (*setDEP)(DWORD) = NULL;
3850 BOOL WINAPI (*setDllDir)(LPCTSTR) = NULL;
3851 if (kernel32) {
3852 setDEP = GetProcAddress(kernel32, "SetProcessDEPPolicy");
3853 setDllDir = GetProcAddress(kernel32, "SetDllDirectoryA");
3855 if (setDEP) setDEP(3);
3856 if (setDllDir) setDllDir("");
3858 // stop Windows from showing all kinds of annoying error dialogs
3859 SetErrorMode(0x8003);
3860 // request 1ms timer resolution
3861 timeBeginPeriod(1);
3862 #endif
3864 #ifdef CONFIG_PRIORITY
3865 set_priority();
3866 #endif
3868 if (codec_path)
3869 set_codec_path(codec_path);
3871 if(opts->video_driver_list && strcmp(opts->video_driver_list[0],"help")==0){
3872 list_video_out();
3873 opt_exit = 1;
3876 if(opts->audio_driver_list && strcmp(opts->audio_driver_list[0],"help")==0){
3877 list_audio_out();
3878 opt_exit = 1;
3881 /* Check codecs.conf. */
3882 if(!codecs_file || !parse_codec_cfg(codecs_file)){
3883 if(!parse_codec_cfg(mem_ptr=get_path("codecs.conf"))){
3884 if(!parse_codec_cfg(MPLAYER_CONFDIR "/codecs.conf")){
3885 if(!parse_codec_cfg(NULL)){
3886 exit_player_with_rc(mpctx, EXIT_NONE, 0);
3888 mp_tmsg(MSGT_CPLAYER,MSGL_V,"Using built-in default codecs.conf.\n");
3891 free( mem_ptr ); // release the buffer created by get_path()
3894 if(audio_codec_list && strcmp(audio_codec_list[0],"help")==0){
3895 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available audio codecs:\n");
3896 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AUDIO_CODECS\n");
3897 list_codecs(1);
3898 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3899 opt_exit = 1;
3901 if(video_codec_list && strcmp(video_codec_list[0],"help")==0){
3902 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available video codecs:\n");
3903 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODECS\n");
3904 list_codecs(0);
3905 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3906 opt_exit = 1;
3908 if(video_fm_list && strcmp(video_fm_list[0],"help")==0){
3909 vfm_help();
3910 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3911 opt_exit = 1;
3913 if(audio_fm_list && strcmp(audio_fm_list[0],"help")==0){
3914 afm_help();
3915 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3916 opt_exit = 1;
3918 if(af_cfg.list && strcmp(af_cfg.list[0],"help")==0){
3919 af_help();
3920 printf("\n");
3921 opt_exit = 1;
3923 #ifdef CONFIG_X11
3924 if(vo_fstype_list && strcmp(vo_fstype_list[0],"help")==0){
3925 fstype_help();
3926 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3927 opt_exit = 1;
3929 #endif
3930 if((opts->demuxer_name && strcmp(opts->demuxer_name,"help")==0) ||
3931 (opts->audio_demuxer_name && strcmp(opts->audio_demuxer_name,"help")==0) ||
3932 (opts->sub_demuxer_name && strcmp(opts->sub_demuxer_name,"help")==0)){
3933 demuxer_help();
3934 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
3935 opt_exit = 1;
3937 if (opts->list_properties) {
3938 property_print_help();
3939 opt_exit = 1;
3942 if(opt_exit)
3943 exit_player(mpctx, EXIT_NONE);
3945 if (!mpctx->filename && !opts->player_idle_mode) {
3946 // no file/vcd/dvd -> show HELP:
3947 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", mp_gtext(help_text));
3948 exit_player_with_rc(mpctx, EXIT_NONE, 0);
3951 /* Display what configure line was used */
3952 mp_msg(MSGT_CPLAYER, MSGL_V, "Configuration: " CONFIGURATION "\n");
3954 // Many users forget to include command line in bugreports...
3955 if( mp_msg_test(MSGT_CPLAYER,MSGL_V) ){
3956 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "CommandLine:");
3957 for(i=1;i<argc;i++)mp_msg(MSGT_CPLAYER, MSGL_INFO," '%s'",argv[i]);
3958 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
3961 //------ load global data first ------
3963 mpctx->osd = osd_create();
3965 // check font
3966 #ifdef CONFIG_FREETYPE
3967 init_freetype();
3968 #endif
3969 #ifdef CONFIG_FONTCONFIG
3970 if(font_fontconfig <= 0)
3972 #endif
3973 #ifdef CONFIG_BITMAP_FONT
3974 if(font_name){
3975 vo_font=read_font_desc(font_name,font_factor,verbose>1);
3976 if(!vo_font) mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load bitmap font: %s\n",
3977 filename_recode(font_name));
3978 } else {
3979 // try default:
3980 vo_font=read_font_desc( mem_ptr=get_path("font/font.desc"),font_factor,verbose>1);
3981 free(mem_ptr); // release the buffer created by get_path()
3982 if(!vo_font)
3983 vo_font=read_font_desc(MPLAYER_DATADIR "/font/font.desc",font_factor,verbose>1);
3985 if (sub_font_name)
3986 mpctx->osd->sub_font = read_font_desc(sub_font_name, font_factor, verbose>1);
3987 else
3988 mpctx->osd->sub_font = vo_font;
3989 #endif
3990 #ifdef CONFIG_FONTCONFIG
3992 #endif
3994 #ifdef CONFIG_ASS
3995 ass_library = mp_ass_init();
3996 #endif
3998 #ifdef HAVE_RTC
3999 if(opts->rtc)
4001 char *rtc_device = opts->rtc_device;
4002 // seteuid(0); /* Can't hurt to try to get root here */
4003 if ((rtc_fd = open(rtc_device ? rtc_device : "/dev/rtc", O_RDONLY)) < 0)
4004 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Failed to open %s: %s (it should be readable by the user.)\n",
4005 rtc_device ? rtc_device : "/dev/rtc", strerror(errno));
4006 else {
4007 unsigned long irqp = 1024; /* 512 seemed OK. 128 is jerky. */
4009 if (ioctl(rtc_fd, RTC_IRQP_SET, irqp) < 0) {
4010 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Linux RTC init error in ioctl (rtc_irqp_set %lu): %s\n", irqp, strerror(errno));
4011 mp_tmsg(MSGT_CPLAYER, MSGL_HINT, "Try adding \"echo %lu > /proc/sys/dev/rtc/max-user-freq\" to your system startup scripts.\n", irqp);
4012 close (rtc_fd);
4013 rtc_fd = -1;
4014 } else if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
4015 /* variable only by the root */
4016 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC init error in ioctl (rtc_pie_on): %s\n", strerror(errno));
4017 close (rtc_fd);
4018 rtc_fd = -1;
4019 } else
4020 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Using Linux hardware RTC timing (%ldHz).\n", irqp);
4023 if(rtc_fd<0)
4024 #endif /* HAVE_RTC */
4025 mp_msg(MSGT_CPLAYER, MSGL_V, "Using %s timing\n",
4026 opts->softsleep ? "software" : timer_name);
4028 #ifdef HAVE_TERMCAP
4029 load_termcap(NULL); // load key-codes
4030 #endif
4032 // ========== Init keyboard FIFO (connection to libvo) ============
4034 // Init input system
4035 current_module = "init_input";
4036 mpctx->input = mp_input_init(&opts->input);
4037 mp_input_add_key_fd(mpctx->input, -1,0,mplayer_get_key,NULL, mpctx->key_fifo);
4038 if(slave_mode) {
4039 #if USE_FD0_CMD_SELECT
4040 int flags = fcntl(0, F_GETFL);
4041 if (flags != -1)
4042 fcntl(0, F_SETFL, flags | O_NONBLOCK);
4043 #endif
4044 mp_input_add_cmd_fd(mpctx->input, 0,USE_FD0_CMD_SELECT,MP_INPUT_SLAVE_CMD_FUNC,NULL);
4046 else if (opts->consolecontrols)
4047 mp_input_add_key_fd(mpctx->input, 0, 1, read_keys, NULL, mpctx->key_fifo);
4048 // Set the libstream interrupt callback
4049 stream_set_interrupt_callback(mp_input_check_interrupt, mpctx->input);
4051 #ifdef CONFIG_MENU
4052 if(use_menu) {
4053 if(menu_cfg && menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
4054 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
4055 else {
4056 menu_cfg = get_path("menu.conf");
4057 if(menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
4058 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
4059 else {
4060 if(menu_init(mpctx, mpctx->mconfig, mpctx->input,
4061 MPLAYER_CONFDIR "/menu.conf"))
4062 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", MPLAYER_CONFDIR"/menu.conf");
4063 else {
4064 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Menu init failed.\n");
4065 use_menu = 0;
4070 #endif
4072 current_module = NULL;
4074 /// Catch signals
4075 #ifndef __MINGW32__
4076 signal(SIGCHLD,child_sighandler);
4077 #endif
4079 #ifdef CONFIG_CRASH_DEBUG
4080 prog_path = argv[0];
4081 #endif
4082 //========= Catch terminate signals: ================
4083 // terminate requests:
4084 signal(SIGTERM,exit_sighandler); // kill
4085 signal(SIGHUP,exit_sighandler); // kill -HUP / xterm closed
4087 signal(SIGINT,exit_sighandler); // Interrupt from keyboard
4089 signal(SIGQUIT,exit_sighandler); // Quit from keyboard
4090 signal(SIGPIPE,exit_sighandler); // Some window managers cause this
4091 #ifdef CONFIG_SIGHANDLER
4092 // fatal errors:
4093 signal(SIGBUS,exit_sighandler); // bus error
4094 signal(SIGSEGV,exit_sighandler); // segfault
4095 signal(SIGILL,exit_sighandler); // illegal instruction
4096 signal(SIGFPE,exit_sighandler); // floating point exc.
4097 signal(SIGABRT,exit_sighandler); // abort()
4098 #ifdef CONFIG_CRASH_DEBUG
4099 if (crash_debug)
4100 signal(SIGTRAP,exit_sighandler);
4101 #endif
4102 #endif
4104 // ******************* Now, let's see the per-file stuff ********************
4106 play_next_file:
4108 // init global sub numbers
4109 mpctx->global_sub_size = 0;
4110 memset(mpctx->sub_counts, 0, sizeof(mpctx->sub_counts));
4112 if (mpctx->filename) {
4113 load_per_protocol_config (mpctx->mconfig, mpctx->filename);
4114 load_per_extension_config (mpctx->mconfig, mpctx->filename);
4115 load_per_file_config (mpctx->mconfig, mpctx->filename);
4118 if (opts->video_driver_list)
4119 load_per_output_config (mpctx->mconfig, PROFILE_CFG_VO, opts->video_driver_list[0]);
4120 if (opts->audio_driver_list)
4121 load_per_output_config (mpctx->mconfig, PROFILE_CFG_AO, opts->audio_driver_list[0]);
4123 // We must enable getch2 here to be able to interrupt network connection
4124 // or cache filling
4125 if (opts->consolecontrols && !slave_mode) {
4126 if(mpctx->initialized_flags&INITIALIZED_GETCH2)
4127 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"WARNING: getch2_init called twice!\n");
4128 else
4129 getch2_enable(); // prepare stdin for hotkeys...
4130 mpctx->initialized_flags|=INITIALIZED_GETCH2;
4131 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[init getch2]]]\n");
4134 // =================== GUI idle loop (STOP state) ===========================
4135 while (opts->player_idle_mode && !mpctx->filename) {
4136 play_tree_t * entry = NULL;
4137 mp_cmd_t * cmd;
4138 if (mpctx->video_out && mpctx->video_out->config_ok)
4139 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
4140 while (!(cmd = mp_input_get_cmd(mpctx->input, 0, 0))) { // wait for command
4141 if (mpctx->video_out)
4142 vo_check_events(mpctx->video_out);
4143 usec_sleep(20000);
4145 switch (cmd->id) {
4146 case MP_CMD_LOADFILE:
4147 // prepare a tree entry with the new filename
4148 entry = play_tree_new();
4149 play_tree_add_file(entry, cmd->args[0].v.s);
4150 // The entry is added to the main playtree after the switch().
4151 break;
4152 case MP_CMD_LOADLIST:
4153 entry = parse_playlist_file(mpctx->mconfig, cmd->args[0].v.s);
4154 break;
4155 case MP_CMD_QUIT:
4156 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
4157 break;
4158 case MP_CMD_VO_FULLSCREEN:
4159 case MP_CMD_GET_PROPERTY:
4160 case MP_CMD_SET_PROPERTY:
4161 case MP_CMD_STEP_PROPERTY:
4162 run_command(mpctx, cmd);
4163 break;
4166 mp_cmd_free(cmd);
4168 if (entry) { // user entered a command that gave a valid entry
4169 if (mpctx->playtree) // the playtree is always a node with one child. let's clear it
4170 play_tree_free_list(mpctx->playtree->child, 1);
4171 else mpctx->playtree=play_tree_new(); // .. or make a brand new playtree
4173 if (!mpctx->playtree) continue; // couldn't make playtree! wait for next command
4175 play_tree_set_child(mpctx->playtree, entry);
4177 /* Make iterator start at the top the of tree. */
4178 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree, mpctx->mconfig);
4179 if (!mpctx->playtree_iter) continue;
4181 // find the first real item in the tree
4182 if (play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
4183 // no items!
4184 play_tree_iter_free(mpctx->playtree_iter);
4185 mpctx->playtree_iter = NULL;
4186 continue; // wait for next command
4188 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, 1);
4191 //---------------------------------------------------------------------------
4193 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
4194 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL);
4196 if (mpctx->filename) {
4197 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nPlaying %s.\n",
4198 filename_recode(mpctx->filename));
4199 if(use_filename_title && opts->vo_wintitle == NULL)
4200 opts->vo_wintitle = strdup(mp_basename(mpctx->filename));
4203 if (edl_filename) {
4204 if (edl_records) free_edl(edl_records);
4205 next_edl_record = edl_records = edl_parse_file();
4207 if (edl_output_filename) {
4208 if (edl_fd) fclose(edl_fd);
4209 if ((edl_fd = fopen(edl_output_filename, "w")) == NULL)
4211 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Can't open EDL file [%s] for writing.\n",
4212 filename_recode(edl_output_filename));
4216 //==================== Open VOB-Sub ============================
4218 current_module="vobsub";
4219 if (opts->vobsub_name){
4220 vo_vobsub=vobsub_open(opts->vobsub_name,spudec_ifo,1,&vo_spudec);
4221 if(vo_vobsub==NULL)
4222 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load subtitles: %s\n",
4223 filename_recode(opts->vobsub_name));
4224 } else if (opts->sub_auto && mpctx->filename){
4225 char **vob = find_vob_subtitles(opts, mpctx->filename);
4226 for (int i = 0; i < MP_TALLOC_ELEMS(vob); i++) {
4227 vo_vobsub = vobsub_open(vob[i], spudec_ifo, 0, &vo_spudec);
4228 if (vo_vobsub)
4229 break;
4231 talloc_free(vob);
4233 if(vo_vobsub){
4234 mpctx->initialized_flags|=INITIALIZED_VOBSUB;
4235 vobsub_set_from_lang(vo_vobsub, opts->sub_lang);
4236 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
4238 // setup global sub numbering
4239 mpctx->sub_counts[SUB_SOURCE_VOBSUB] = vobsub_get_indexes_count(vo_vobsub);
4242 //============ Open & Sync STREAM --- fork cache2 ====================
4244 mpctx->stream=NULL;
4245 mpctx->demuxer=NULL;
4246 mpctx->d_audio=NULL;
4247 mpctx->d_video=NULL;
4248 mpctx->d_sub = NULL;
4249 mpctx->sh_audio=NULL;
4250 mpctx->sh_video=NULL;
4252 current_module="open_stream";
4253 mpctx->stream = open_stream(mpctx->filename, opts, &mpctx->file_format);
4254 if(!mpctx->stream) { // error...
4255 mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY);
4256 goto goto_next_file;
4258 mpctx->initialized_flags|=INITIALIZED_STREAM;
4260 if(mpctx->file_format == DEMUXER_TYPE_PLAYLIST) {
4261 mp_msg(MSGT_CPLAYER, MSGL_ERR, "\nThis looks like a playlist, but "
4262 "playlist support will not be used automatically.\n"
4263 "MPlayer's playlist code is unsafe and should only be used with "
4264 "trusted sources.\nPlayback will probably fail.\n\n");
4265 #if 0
4266 play_tree_t* entry;
4267 // Handle playlist
4268 current_module="handle_playlist";
4269 mp_msg(MSGT_CPLAYER,MSGL_V,"Parsing playlist %s...\n",
4270 filename_recode(mpctx->filename));
4271 entry = parse_playtree(mpctx->stream, mpctx->mconfig, 0);
4272 mpctx->eof=playtree_add_playlist(mpctx, entry);
4273 goto goto_next_file;
4274 #endif
4276 mpctx->stream->start_pos+=seek_to_byte;
4278 if(stream_dump_type==5){
4279 unsigned char buf[4096];
4280 int len;
4281 FILE *f;
4282 current_module="dumpstream";
4283 stream_reset(mpctx->stream);
4284 stream_seek(mpctx->stream,mpctx->stream->start_pos);
4285 f=fopen(opts->stream_dump_name,"wb");
4286 if(!f){
4287 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
4288 exit_player(mpctx, EXIT_ERROR);
4290 if (opts->chapterrange[0] > 1) {
4291 int chapter = opts->chapterrange[0] - 1;
4292 stream_control(mpctx->stream, STREAM_CTRL_SEEK_TO_CHAPTER, &chapter);
4294 while(!mpctx->stream->eof && !async_quit_request){
4295 len=stream_read(mpctx->stream,buf,4096);
4296 if(len>0) {
4297 if(fwrite(buf,len,1,f) != 1) {
4298 mp_tmsg(MSGT_GLOBAL,MSGL_FATAL,"%s: Error writing file.\n",opts->stream_dump_name);
4299 exit_player(mpctx, EXIT_ERROR);
4302 if (opts->chapterrange[1] > 0) {
4303 int chapter = -1;
4304 if (stream_control(mpctx->stream, STREAM_CTRL_GET_CURRENT_CHAPTER,
4305 &chapter) == STREAM_OK
4306 && chapter + 1 > opts->chapterrange[1])
4307 break;
4310 if(fclose(f)) {
4311 mp_tmsg(MSGT_GLOBAL,MSGL_FATAL,"%s: Error writing file.\n",opts->stream_dump_name);
4312 exit_player(mpctx, EXIT_ERROR);
4314 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Stream dump complete.\n");
4315 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4318 #ifdef CONFIG_DVDREAD
4319 if(mpctx->stream->type==STREAMTYPE_DVD){
4320 current_module="dvd lang->id";
4321 if(opts->audio_lang && opts->audio_id==-1) opts->audio_id=dvd_aid_from_lang(mpctx->stream,opts->audio_lang);
4322 if(opts->sub_lang && opts->sub_id==-1) opts->sub_id=dvd_sid_from_lang(mpctx->stream,opts->sub_lang);
4323 // setup global sub numbering
4324 mpctx->sub_counts[SUB_SOURCE_DEMUX] = dvd_number_of_subs(mpctx->stream);
4325 current_module=NULL;
4327 #endif
4329 #ifdef CONFIG_DVDNAV
4330 if(mpctx->stream->type==STREAMTYPE_DVDNAV){
4331 current_module="dvdnav lang->id";
4332 if(opts->audio_lang && opts->audio_id==-1) opts->audio_id=mp_dvdnav_aid_from_lang(mpctx->stream,opts->audio_lang);
4333 dvdsub_lang_id = -3;
4334 if(opts->sub_lang && opts->sub_id==-1)
4335 dvdsub_lang_id = opts->sub_id = mp_dvdnav_sid_from_lang(mpctx->stream,opts->sub_lang);
4336 // setup global sub numbering
4337 mpctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(mpctx->stream);
4338 current_module=NULL;
4340 #endif
4342 // CACHE2: initial prefill: 20% later: 5% (should be set by -cacheopts)
4343 goto_enable_cache:
4344 if(stream_cache_size>0){
4345 int res;
4346 float stream_cache_min_percent = opts->stream_cache_min_percent;
4347 float stream_cache_seek_min_percent = opts->stream_cache_seek_min_percent;
4348 current_module="enable_cache";
4349 res = stream_enable_cache(mpctx->stream,stream_cache_size*1024,
4350 stream_cache_size*1024*(stream_cache_min_percent / 100.0),
4351 stream_cache_size*1024*(stream_cache_seek_min_percent / 100.0));
4352 if(res == 0)
4353 if((mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY))) goto goto_next_file;
4356 //============ Open DEMUXERS --- DETECT file type =======================
4357 current_module="demux_open";
4359 mpctx->demuxer=demux_open(opts, mpctx->stream,mpctx->file_format,opts->audio_id,opts->video_id,opts->sub_id,mpctx->filename);
4361 // HACK to get MOV Reference Files working
4363 if (mpctx->demuxer && mpctx->demuxer->type==DEMUXER_TYPE_PLAYLIST)
4365 unsigned char* playlist_entry;
4366 play_tree_t *list = NULL, *entry = NULL;
4368 current_module="handle_demux_playlist";
4369 while (ds_get_packet(mpctx->demuxer->video,&playlist_entry)>0)
4371 char *temp;
4372 const char *bname;
4374 mp_msg(MSGT_CPLAYER,MSGL_V,"Adding file %s to element entry.\n",
4375 filename_recode(playlist_entry));
4377 bname=mp_basename(playlist_entry);
4378 if ((strlen(bname)>10) && !strncmp(bname,"qt",2) && !strncmp(bname+3,"gateQT",6))
4379 continue;
4381 if (!strcmp(playlist_entry, mpctx->filename)) // ignoring self-reference
4382 continue;
4384 entry = play_tree_new();
4386 if (mpctx->filename && !strcmp(mp_basename(playlist_entry),playlist_entry)) // add reference path of current file
4388 temp=malloc((strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))+strlen(playlist_entry)+1));
4389 if (temp)
4391 strncpy(temp, mpctx->filename, strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename)));
4392 temp[strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))]='\0';
4393 strcat(temp, playlist_entry);
4394 if (!strcmp(temp, mpctx->filename)) {
4395 free(temp);
4396 continue;
4398 play_tree_add_file(entry,temp);
4399 mp_msg(MSGT_CPLAYER,MSGL_V,"Resolving reference to %s.\n",temp);
4400 free(temp);
4403 else
4404 play_tree_add_file(entry,playlist_entry);
4406 if(!list)
4407 list = entry;
4408 else
4409 play_tree_append_entry(list,entry);
4411 free_demuxer(mpctx->demuxer);
4412 mpctx->demuxer = NULL;
4414 if (list)
4416 entry = play_tree_new();
4417 play_tree_set_child(entry,list);
4418 mpctx->stop_play = playtree_add_playlist(mpctx, entry);
4419 goto goto_next_file;
4423 if(!mpctx->demuxer) {
4424 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Failed to recognize file format.\n");
4425 goto goto_next_file;
4428 if (mpctx->demuxer->matroska_data.ordered_chapters)
4429 build_ordered_chapter_timeline(mpctx);
4431 if (mpctx->demuxer->type == DEMUXER_TYPE_EDL)
4432 build_edl_timeline(mpctx);
4434 if (mpctx->timeline) {
4435 mpctx->timeline_part = 0;
4436 mpctx->demuxer = mpctx->timeline[0].source->demuxer;
4438 int part_count = mpctx->num_timeline_parts;
4439 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline contains %d parts from %d "
4440 "sources. Total length %.3f seconds.\n", part_count,
4441 mpctx->num_sources, mpctx->timeline[part_count].start);
4442 mp_msg(MSGT_CPLAYER, MSGL_V, "Source files:\n");
4443 for (int i = 0; i < mpctx->num_sources; i++)
4444 mp_msg(MSGT_CPLAYER, MSGL_V, "%d: %s\n", i,
4445 filename_recode(mpctx->sources[i].demuxer->filename));
4446 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline parts: (number, start, "
4447 "source_start, source):\n");
4448 for (int i = 0; i < part_count; i++) {
4449 struct timeline_part *p = mpctx->timeline + i;
4450 mp_msg(MSGT_CPLAYER, MSGL_V, "%3d %9.3f %9.3f %3td\n", i, p->start,
4451 p->source_start, p->source - mpctx->sources);
4453 mp_msg(MSGT_CPLAYER, MSGL_V, "END %9.3f\n",
4454 mpctx->timeline[part_count].start);
4457 if (!mpctx->sources) {
4458 mpctx->sources = talloc_ptrtype(NULL, mpctx->sources);
4459 *mpctx->sources = (struct content_source){.stream = mpctx->stream,
4460 .demuxer = mpctx->demuxer};
4461 mpctx->num_sources = 1;
4464 mpctx->initialized_flags|=INITIALIZED_DEMUXER;
4466 #ifdef CONFIG_ASS
4467 if (opts->ass_enabled && ass_library) {
4468 for (int j = 0; j < mpctx->num_sources; j++) {
4469 struct demuxer *d = mpctx->sources[j].demuxer;
4470 for (int i = 0; i < d->num_attachments; i++) {
4471 struct demux_attachment *att = d->attachments + i;
4472 if (use_embedded_fonts && attachment_is_font(att))
4473 ass_add_font(ass_library, att->name, att->data, att->data_size);
4477 #endif
4479 current_module="demux_open2";
4481 mpctx->d_audio=mpctx->demuxer->audio;
4482 mpctx->d_video=mpctx->demuxer->video;
4483 mpctx->d_sub=mpctx->demuxer->sub;
4485 if (ts_prog) {
4486 int tmp = ts_prog;
4487 mp_property_do("switch_program", M_PROPERTY_SET, &tmp, mpctx);
4489 // select audio stream
4490 for (int i = 0; i < mpctx->num_sources; i++)
4491 select_audio(mpctx->sources[i].demuxer->audio->demuxer, opts->audio_id,
4492 opts->audio_lang);
4494 // DUMP STREAMS:
4495 if((stream_dump_type)&&(stream_dump_type<4)){
4496 FILE *f;
4497 demux_stream_t *ds=NULL;
4498 current_module="dump";
4499 // select stream to dump
4500 switch(stream_dump_type){
4501 case 1: ds=mpctx->d_audio;break;
4502 case 2: ds=mpctx->d_video;break;
4503 case 3: ds=mpctx->d_sub;break;
4505 if(!ds){
4506 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"dump: FATAL: Selected stream missing!\n");
4507 exit_player(mpctx, EXIT_ERROR);
4509 // disable other streams:
4510 if(mpctx->d_audio && mpctx->d_audio!=ds) {ds_free_packs(mpctx->d_audio); mpctx->d_audio->id=-2; }
4511 if(mpctx->d_video && mpctx->d_video!=ds) {ds_free_packs(mpctx->d_video); mpctx->d_video->id=-2; }
4512 if(mpctx->d_sub && mpctx->d_sub!=ds) {ds_free_packs(mpctx->d_sub); mpctx->d_sub->id=-2; }
4513 // let's dump it!
4514 f=fopen(opts->stream_dump_name,"wb");
4515 if(!f){
4516 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
4517 exit_player(mpctx, EXIT_ERROR);
4519 while(!ds->eof){
4520 unsigned char* start;
4521 int in_size=ds_get_packet(ds,&start);
4522 if( (mpctx->demuxer->file_format==DEMUXER_TYPE_AVI || mpctx->demuxer->file_format==DEMUXER_TYPE_ASF || mpctx->demuxer->file_format==DEMUXER_TYPE_MOV)
4523 && stream_dump_type==2) fwrite(&in_size,1,4,f);
4524 if(in_size>0) fwrite(start,in_size,1,f);
4525 if (opts->chapterrange[1] > 0) {
4526 int cur_chapter = demuxer_get_current_chapter(mpctx->demuxer, 0);
4527 if(cur_chapter!=-1 && cur_chapter+1 > opts->chapterrange[1])
4528 break;
4531 fclose(f);
4532 mp_tmsg(MSGT_CPLAYER ,MSGL_INFO, "Stream dump complete.\n");
4533 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4536 mpctx->sh_audio=mpctx->d_audio->sh;
4537 mpctx->sh_video=mpctx->d_video->sh;
4539 if(mpctx->sh_video){
4541 current_module="video_read_properties";
4542 if(!video_read_properties(mpctx->sh_video)) {
4543 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Video: Cannot read properties.\n");
4544 mpctx->sh_video=mpctx->d_video->sh=NULL;
4545 } else {
4546 mp_tmsg(MSGT_CPLAYER,MSGL_V,"[V] filefmt:%d fourcc:0x%X size:%dx%d fps:%5.3f ftime:=%6.4f\n",
4547 mpctx->demuxer->file_format,mpctx->sh_video->format, mpctx->sh_video->disp_w,mpctx->sh_video->disp_h,
4548 mpctx->sh_video->fps,mpctx->sh_video->frametime
4551 /* need to set fps here for output encoders to pick it up in their init */
4552 if(force_fps){
4553 mpctx->sh_video->fps=force_fps;
4554 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
4556 vo_fps = mpctx->sh_video->fps;
4558 if(!mpctx->sh_video->fps && !force_fps){
4559 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"FPS not specified in the header or invalid, use the -fps option.\n");
4560 mpctx->opts.correct_pts = 1;
4566 if(!mpctx->sh_video && !mpctx->sh_audio){
4567 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL, "No stream found.\n");
4568 #ifdef CONFIG_DVBIN
4569 if(mpctx->stream->type == STREAMTYPE_DVB)
4571 int dir;
4572 int v = mpctx->last_dvb_step;
4573 if(v > 0)
4574 dir = DVB_CHANNEL_HIGHER;
4575 else
4576 dir = DVB_CHANNEL_LOWER;
4578 if(dvb_step_channel(mpctx->stream, dir)) {
4579 mpctx->stop_play = PT_NEXT_ENTRY;
4580 mpctx->dvbin_reopen = 1;
4583 #endif
4584 goto goto_next_file; // exit_player(_("Fatal error"));
4587 /* display clip info */
4588 demux_info_print(mpctx->demuxer);
4590 //================== Read SUBTITLES (DVD & TEXT) ==========================
4591 if(vo_spudec==NULL &&
4592 (mpctx->stream->type==STREAMTYPE_DVD || mpctx->stream->type == STREAMTYPE_DVDNAV)){
4593 init_vo_spudec(mpctx);
4596 // after reading video params we should load subtitles because
4597 // we know fps so now we can adjust subtitle time to ~6 seconds AST
4598 // check .sub
4599 current_module="read_subtitles_file";
4600 double sub_fps = mpctx->sh_video ? mpctx->sh_video->fps : 25;
4601 if(opts->sub_name){
4602 for (i = 0; opts->sub_name[i] != NULL; ++i)
4603 add_subtitles(mpctx, opts->sub_name[i], sub_fps, 0);
4605 if(opts->sub_auto) { // auto load sub file ...
4606 char **tmp = find_text_subtitles(opts, mpctx->filename);
4607 int nsub = MP_TALLOC_ELEMS(tmp);
4608 for (int i = 0; i < nsub; i++)
4609 add_subtitles(mpctx, tmp[i], sub_fps, 1);
4610 talloc_free(tmp);
4612 if (mpctx->set_of_sub_size > 0)
4613 mpctx->sub_counts[SUB_SOURCE_SUBS] = mpctx->set_of_sub_size;
4615 if (select_subtitle(mpctx)) {
4616 if(mpctx->subdata)
4617 switch (stream_dump_type) {
4618 case 3: list_sub_file(mpctx->subdata); break;
4619 case 4: dump_mpsub(mpctx->subdata, mpctx->sh_video->fps); break;
4620 case 6: dump_srt(mpctx->subdata, mpctx->sh_video->fps); break;
4621 case 7: dump_microdvd(mpctx->subdata, mpctx->sh_video->fps); break;
4622 case 8: dump_jacosub(mpctx->subdata, mpctx->sh_video->fps); break;
4623 case 9: dump_sami(mpctx->subdata, mpctx->sh_video->fps); break;
4627 print_file_properties(mpctx, mpctx->filename);
4629 reinit_video_chain(mpctx);
4630 if (mpctx->sh_video) {
4631 if(mpctx->sh_video->output_flags & VFCAP_SPU && vo_spudec)
4632 spudec_set_hw_spu(vo_spudec,mpctx->video_out);
4633 #ifdef CONFIG_FREETYPE
4634 force_load_font = 1;
4635 #endif
4636 } else if (!mpctx->sh_audio)
4637 goto goto_next_file;
4639 //================== MAIN: ==========================
4640 current_module="main";
4642 if (opts->playing_msg) {
4643 char* msg = property_expand_string(mpctx, opts->playing_msg);
4644 mp_msg(MSGT_CPLAYER,MSGL_INFO,"%s",msg);
4645 free(msg);
4649 // Disable the term OSD in verbose mode
4650 if (verbose)
4651 opts->term_osd = 0;
4655 // Make sure old OSD does not stay around,
4656 // e.g. with -fixed-vo and same-resolution files
4657 clear_osd_msgs();
4658 update_osd_msg(mpctx);
4660 //================ SETUP AUDIO ==========================
4662 if(mpctx->sh_audio){
4663 reinit_audio_chain(mpctx);
4664 if (mpctx->sh_audio && mpctx->sh_audio->codec)
4665 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_CODEC=%s\n", mpctx->sh_audio->codec->name);
4668 current_module="av_init";
4670 if(mpctx->sh_video){
4671 mpctx->sh_video->timer=0;
4672 if (! ignore_start)
4673 audio_delay += mpctx->sh_video->stream_delay;
4675 if(mpctx->sh_audio){
4676 if (start_volume >= 0)
4677 mixer_setvolume(&mpctx->mixer, start_volume, start_volume);
4678 if (! ignore_start)
4679 audio_delay -= mpctx->sh_audio->stream_delay;
4680 mpctx->delay=-audio_delay;
4683 if(!mpctx->sh_audio){
4684 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Audio: no sound\n");
4685 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused audio chunks.\n",mpctx->d_audio->packs);
4686 ds_free_packs(mpctx->d_audio); // free buffered chunks
4687 //mpctx->d_audio->id=-2; // do not read audio chunks
4688 //uninit_player(mpctx, INITIALIZED_AO); // close device
4690 if(!mpctx->sh_video){
4691 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Video: no video\n");
4692 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused video chunks.\n",mpctx->d_video->packs);
4693 ds_free_packs(mpctx->d_video);
4694 mpctx->d_video->id=-2;
4695 //if(!fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
4698 if (!mpctx->sh_video && !mpctx->sh_audio)
4699 goto goto_next_file;
4701 //if(demuxer->file_format!=DEMUXER_TYPE_AVI) pts_from_bps=0; // it must be 0 for mpeg/asf!
4702 if(force_fps && mpctx->sh_video){
4703 vo_fps = mpctx->sh_video->fps=force_fps;
4704 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
4705 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"FPS forced to be %5.3f (ftime: %5.3f).\n",mpctx->sh_video->fps,mpctx->sh_video->frametime);
4708 mp_input_set_section(mpctx->input, NULL);
4709 //TODO: add desired (stream-based) sections here
4710 if (mpctx->stream->type==STREAMTYPE_TV) mp_input_set_section(mpctx->input, "tv");
4711 if (mpctx->stream->type==STREAMTYPE_DVDNAV) mp_input_set_section(mpctx->input, "dvdnav");
4713 //==================== START PLAYING =======================
4715 if(opts->loop_times>1) opts->loop_times--; else
4716 if(opts->loop_times==1) opts->loop_times = -1;
4718 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Starting playback...\n");
4720 total_time_usage_start=GetTimer();
4721 audio_time_usage=0; video_time_usage=0; vout_time_usage=0;
4722 total_frame_cnt=0; drop_frame_cnt=0; // fix for multifile fps benchmark
4723 play_n_frames=play_n_frames_mf;
4725 if(play_n_frames==0){
4726 mpctx->stop_play=PT_NEXT_ENTRY; goto goto_next_file;
4729 mpctx->time_frame = 0;
4730 mpctx->drop_message_shown = 0;
4731 mpctx->restart_playback = true;
4732 mpctx->video_pts = 0;
4733 mpctx->hrseek_active = false;
4734 mpctx->hrseek_framedrop = false;
4735 mpctx->step_frames = 0;
4736 mpctx->total_avsync_change = 0;
4737 mpctx->last_chapter_seek = -1;
4739 // If there's a timeline force an absolute seek to initialize state
4740 if (seek_to_sec || mpctx->timeline) {
4741 queue_seek(mpctx, MPSEEK_ABSOLUTE, seek_to_sec, 0);
4742 seek(mpctx, mpctx->seek, false);
4743 end_at.pos += seek_to_sec;
4745 if (opts->chapterrange[0] > 0) {
4746 double pts;
4747 if (seek_chapter(mpctx, opts->chapterrange[0]-1, &pts, NULL) >= 0
4748 && pts > -1.0) {
4749 queue_seek(mpctx, MPSEEK_ABSOLUTE, pts, 0);
4750 seek(mpctx, mpctx->seek, false);
4754 if (end_at.type == END_AT_SIZE) {
4755 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Option -endpos in MPlayer does not yet support size units.\n");
4756 end_at.type = END_AT_NONE;
4759 #ifdef CONFIG_DVDNAV
4760 mp_dvdnav_context_free(mpctx);
4761 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4762 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
4763 mp_dvdnav_cell_has_changed(mpctx->stream,1);
4765 #endif
4767 mpctx->seek = (struct seek_params){0};
4768 get_relative_time(mpctx); // reset current delta
4769 // Make sure VO knows current pause state
4770 if (mpctx->sh_video)
4771 vo_control(mpctx->video_out, mpctx->paused ? VOCTRL_PAUSE : VOCTRL_RESUME,
4772 NULL);
4774 while (!mpctx->stop_play)
4775 run_playloop(mpctx);
4777 mp_msg(MSGT_GLOBAL,MSGL_V,"EOF code: %d \n",mpctx->stop_play);
4779 #ifdef CONFIG_DVBIN
4780 if(mpctx->dvbin_reopen)
4782 mpctx->stop_play = 0;
4783 uninit_player(mpctx, INITIALIZED_ALL-(INITIALIZED_STREAM|INITIALIZED_GETCH2|(opts->fixed_vo?INITIALIZED_VO:0)));
4784 cache_uninit(mpctx->stream);
4785 mpctx->dvbin_reopen = 0;
4786 goto goto_enable_cache;
4788 #endif
4791 goto_next_file: // don't jump here after ao/vo/getch initialization!
4793 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\n");
4795 if (opts->benchmark) {
4796 double tot=video_time_usage+vout_time_usage+audio_time_usage;
4797 double total_time_usage;
4798 total_time_usage_start=GetTimer()-total_time_usage_start;
4799 total_time_usage = (float)total_time_usage_start*0.000001;
4800 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\nBENCHMARKs: VC:%8.3fs VO:%8.3fs A:%8.3fs Sys:%8.3fs = %8.3fs\n",
4801 video_time_usage,vout_time_usage,audio_time_usage,
4802 total_time_usage-tot,total_time_usage);
4803 if(total_time_usage>0.0)
4804 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARK%%: VC:%8.4f%% VO:%8.4f%% A:%8.4f%% Sys:%8.4f%% = %8.4f%%\n",
4805 100.0*video_time_usage/total_time_usage,
4806 100.0*vout_time_usage/total_time_usage,
4807 100.0*audio_time_usage/total_time_usage,
4808 100.0*(total_time_usage-tot)/total_time_usage,
4809 100.0);
4810 if(total_frame_cnt && frame_dropping)
4811 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARKn: disp: %d (%3.2f fps) drop: %d (%d%%) total: %d (%3.2f fps)\n",
4812 total_frame_cnt-drop_frame_cnt,
4813 (total_time_usage>0.5)?((total_frame_cnt-drop_frame_cnt)/total_time_usage):0,
4814 drop_frame_cnt,
4815 100*drop_frame_cnt/total_frame_cnt,
4816 total_frame_cnt,
4817 (total_time_usage>0.5)?(total_frame_cnt/total_time_usage):0);
4820 // time to uninit all, except global stuff:
4821 int uninitialize_parts = INITIALIZED_ALL;
4822 if (opts->fixed_vo)
4823 uninitialize_parts -= INITIALIZED_VO;
4824 if (opts->gapless_audio && mpctx->stop_play == AT_END_OF_FILE)
4825 uninitialize_parts -= INITIALIZED_AO;
4826 uninit_player(mpctx, uninitialize_parts);
4828 if(mpctx->set_of_sub_size > 0) {
4829 current_module="sub_free";
4830 for(i = 0; i < mpctx->set_of_sub_size; ++i) {
4831 sub_free(mpctx->set_of_subtitles[i]);
4832 #ifdef CONFIG_ASS
4833 if(mpctx->set_of_ass_tracks[i])
4834 ass_free_track( mpctx->set_of_ass_tracks[i] );
4835 #endif
4837 mpctx->set_of_sub_size = 0;
4839 mpctx->vo_sub_last = vo_sub=NULL;
4840 mpctx->subdata=NULL;
4841 #ifdef CONFIG_ASS
4842 mpctx->osd->ass_track = NULL;
4843 if(ass_library)
4844 ass_clear_fonts(ass_library);
4845 #endif
4847 if (!mpctx->stop_play) // In case some goto jumped here...
4848 mpctx->stop_play = PT_NEXT_ENTRY;
4850 int playtree_direction = 1;
4852 if(mpctx->stop_play == PT_NEXT_ENTRY || mpctx->stop_play == PT_PREV_ENTRY) {
4853 if(play_tree_iter_step(mpctx->playtree_iter,mpctx->play_tree_step,0) != PLAY_TREE_ITER_ENTRY) {
4854 play_tree_iter_free(mpctx->playtree_iter);
4855 mpctx->playtree_iter = NULL;
4857 mpctx->play_tree_step = 1;
4858 } else if(mpctx->stop_play == PT_UP_NEXT || mpctx->stop_play == PT_UP_PREV) {
4859 int direction = mpctx->stop_play == PT_UP_NEXT ? 1 : -1;
4860 if(mpctx->playtree_iter) {
4861 if(play_tree_iter_up_step(mpctx->playtree_iter,direction,0) != PLAY_TREE_ITER_ENTRY) {
4862 play_tree_iter_free(mpctx->playtree_iter);
4863 mpctx->playtree_iter = NULL;
4866 } else if (mpctx->stop_play == PT_STOP) {
4867 play_tree_iter_free(mpctx->playtree_iter);
4868 mpctx->playtree_iter = NULL;
4869 } else { // NEXT PREV SRC
4870 playtree_direction = mpctx->stop_play == PT_PREV_SRC ? -1 : 1;
4873 while(mpctx->playtree_iter != NULL) {
4874 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, playtree_direction);
4875 if(mpctx->filename == NULL) {
4876 if(play_tree_iter_step(mpctx->playtree_iter, playtree_direction, 0) != PLAY_TREE_ITER_ENTRY) {
4877 play_tree_iter_free(mpctx->playtree_iter);
4878 mpctx->playtree_iter = NULL;
4880 } else
4881 break;
4884 if (mpctx->playtree_iter != NULL || opts->player_idle_mode) {
4885 if(!mpctx->playtree_iter) mpctx->filename = NULL;
4886 mpctx->stop_play = 0;
4887 goto play_next_file;
4891 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4893 return 1;
4895 #endif /* DISABLE_MAIN */