options: move sub_name, sub_auto and vobsub_name to struct
[mplayer.git] / mplayer.c
blob645ce35e98987d98cc6d0bcb0d3111d5e6c91da0
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 "cfg-mplayer-def.h"
72 #include "libavutil/avstring.h"
74 #include "sub/subreader.h"
75 #include "sub/dec_sub.h"
77 #include "mp_osd.h"
78 #include "libvo/video_out.h"
80 #include "sub/font_load.h"
81 #include "sub/sub.h"
82 #include "ffmpeg_files/intreadwrite.h"
83 #include "sub/av_sub.h"
84 #include "libmpcodecs/dec_teletext.h"
85 #include "cpudetect.h"
86 #include "version.h"
88 #ifdef CONFIG_X11
89 #include "libvo/x11_common.h"
90 #endif
92 #include "libao2/audio_out.h"
94 #include "codec-cfg.h"
96 #include "edl.h"
98 #include "sub/spudec.h"
99 #include "sub/vobsub.h"
101 #include "osdep/getch2.h"
102 #include "osdep/timer.h"
104 #include "input/input.h"
106 int slave_mode=0;
107 int enable_mouse_movements=0;
108 float start_volume = -1;
110 #include "osdep/priority.h"
112 char *heartbeat_cmd;
114 #ifdef HAVE_RTC
115 #ifdef __linux__
116 #include <linux/rtc.h>
117 #else
118 #include <rtc.h>
119 #define RTC_IRQP_SET RTCIO_IRQP_SET
120 #define RTC_PIE_ON RTCIO_PIE_ON
121 #endif /* __linux__ */
122 #endif /* HAVE_RTC */
124 #include "stream/tv.h"
125 #include "stream/stream_radio.h"
126 #ifdef CONFIG_DVBIN
127 #include "stream/dvbin.h"
128 #endif
129 #include "stream/cache2.h"
131 //**************************************************************************//
132 // Playtree
133 //**************************************************************************//
134 #include "playtree.h"
135 #include "playtreeparser.h"
137 //**************************************************************************//
138 // Config
139 //**************************************************************************//
140 #include "parser-cfg.h"
141 #include "parser-mpcmd.h"
143 //**************************************************************************//
144 // Config file
145 //**************************************************************************//
147 static int cfg_inc_verbose(m_option_t *conf){ ++verbose; return 0;}
149 #include "path.h"
151 //**************************************************************************//
152 //**************************************************************************//
153 // Input media streaming & demultiplexer:
154 //**************************************************************************//
156 static int max_framesize=0;
158 #include "stream/stream.h"
159 #include "libmpdemux/demuxer.h"
160 #include "libmpdemux/stheader.h"
162 #ifdef CONFIG_DVDREAD
163 #include "stream/stream_dvd.h"
164 #endif
165 #include "stream/stream_dvdnav.h"
167 #include "libmpcodecs/dec_audio.h"
168 #include "libmpcodecs/dec_video.h"
169 #include "libmpcodecs/mp_image.h"
170 #include "libmpcodecs/vf.h"
171 #include "libmpcodecs/vd.h"
173 #include "mixer.h"
175 #include "mp_core.h"
176 #include "options.h"
177 #include "defaultopts.h"
179 static const char help_text[]=_(
180 "Usage: mplayer [options] [url|path/]filename\n"
181 "\n"
182 "Basic options: (complete list in the man page)\n"
183 " -vo <drv> select video output driver ('-vo help' for a list)\n"
184 " -ao <drv> select audio output driver ('-ao help' for a list)\n"
185 #ifdef CONFIG_VCD
186 " vcd://<trackno> play (S)VCD (Super Video CD) track (raw device, no mount)\n"
187 #endif
188 #ifdef CONFIG_DVDREAD
189 " dvd://<titleno> play DVD title from device instead of plain file\n"
190 #endif
191 " -alang/-slang select DVD audio/subtitle language (by 2-char country code)\n"
192 " -ss <position> seek to given (seconds or hh:mm:ss) position\n"
193 " -nosound do not play sound\n"
194 " -fs fullscreen playback (or -vm, -zoom, details in the man page)\n"
195 " -x <x> -y <y> set display resolution (for use with -vm or -zoom)\n"
196 " -sub <file> specify subtitle file to use (also see -subfps, -subdelay)\n"
197 " -playlist <file> specify playlist file\n"
198 " -vid x -aid y select video (x) and audio (y) stream to play\n"
199 " -fps x -srate y change video (x fps) and audio (y Hz) rate\n"
200 " -pp <quality> enable postprocessing filter (details in the man page)\n"
201 " -framedrop enable frame dropping (for slow machines)\n"
202 "\n"
203 "Basic keys: (complete list in the man page, also check input.conf)\n"
204 " <- or -> seek backward/forward 10 seconds\n"
205 " down or up seek backward/forward 1 minute\n"
206 " pgdown or pgup seek backward/forward 10 minutes\n"
207 " < or > step backward/forward in playlist\n"
208 " p or SPACE pause movie (press any key to continue)\n"
209 " q or ESC stop playing and quit program\n"
210 " + or - adjust audio delay by +/- 0.1 second\n"
211 " o cycle OSD mode: none / seekbar / seekbar + timer\n"
212 " * or / increase or decrease PCM volume\n"
213 " x or z adjust subtitle delay by +/- 0.1 second\n"
214 " r or t adjust subtitle position up/down, also see -vf expand\n"
215 "\n"
216 " * * * SEE THE MAN PAGE FOR DETAILS, FURTHER (ADVANCED) OPTIONS AND KEYS * * *\n"
217 "\n");
220 #define Exit_SIGILL_RTCpuSel _(\
221 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
222 " It may be a bug in our new runtime CPU-detection code...\n"\
223 " Please read DOCS/HTML/en/bugreports.html.\n")
225 #define Exit_SIGILL _(\
226 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
227 " It usually happens when you run it on a CPU different than the one it was\n"\
228 " compiled/optimized for.\n"\
229 " Verify this!\n")
231 #define Exit_SIGSEGV_SIGFPE _(\
232 "- MPlayer crashed by bad usage of CPU/FPU/RAM.\n"\
233 " Recompile MPlayer with --enable-debug and make a 'gdb' backtrace and\n"\
234 " disassembly. Details in DOCS/HTML/en/bugreports_what.html#bugreports_crash.\n")
236 #define Exit_SIGCRASH _(\
237 "- MPlayer crashed. This shouldn't happen.\n"\
238 " It can be a bug in the MPlayer code _or_ in your drivers _or_ in your\n"\
239 " gcc version. If you think it's MPlayer's fault, please read\n"\
240 " DOCS/HTML/en/bugreports.html and follow the instructions there. We can't and\n"\
241 " won't help unless you provide this information when reporting a possible bug.\n")
243 #define SystemTooSlow _("\n\n"\
244 " ************************************************\n"\
245 " **** Your system is too SLOW to play this! ****\n"\
246 " ************************************************\n\n"\
247 "Possible reasons, problems, workarounds:\n"\
248 "- Most common: broken/buggy _audio_ driver\n"\
249 " - Try -ao sdl or use the OSS emulation of ALSA.\n"\
250 " - Experiment with different values for -autosync, 30 is a good start.\n"\
251 "- Slow video output\n"\
252 " - Try a different -vo driver (-vo help for a list) or try -framedrop!\n"\
253 "- Slow CPU\n"\
254 " - Don't try to play a big DVD/DivX on a slow CPU! Try some of the lavdopts,\n"\
255 " e.g. -vfm ffmpeg -lavdopts lowres=1:fast:skiploopfilter=all.\n"\
256 "- Broken file\n"\
257 " - Try various combinations of -nobps -ni -forceidx -mc 0.\n"\
258 "- Slow media (NFS/SMB mounts, DVD, VCD etc)\n"\
259 " - Try -cache 8192.\n"\
260 "- Are you using -cache to play a non-interleaved AVI file?\n"\
261 " - Try -nocache.\n"\
262 "Read DOCS/HTML/en/video.html for tuning/speedup tips.\n"\
263 "If none of this helps you, read DOCS/HTML/en/bugreports.html.\n\n")
266 //**************************************************************************//
267 //**************************************************************************//
269 #include "mp_fifo.h"
271 // benchmark:
272 double video_time_usage=0;
273 double vout_time_usage=0;
274 static double audio_time_usage=0;
275 static int total_time_usage_start=0;
276 static int total_frame_cnt=0;
277 static int drop_frame_cnt=0; // total number of dropped frames
279 // options:
280 static int output_quality=0;
282 // seek:
283 static double seek_to_sec;
284 static off_t seek_to_byte=0;
285 static off_t step_sec=0;
287 static m_time_size_t end_at = { .type = END_AT_NONE, .pos = 0 };
289 // codecs:
290 char **audio_codec_list=NULL; // override audio codec
291 char **video_codec_list=NULL; // override video codec
292 char **audio_fm_list=NULL; // override audio codec family
293 char **video_fm_list=NULL; // override video codec family
295 // this dvdsub_id was selected via slang
296 // use this to allow dvdnav to follow -slang across stream resets,
297 // in particular the subtitle ID for a language changes
298 int dvdsub_lang_id;
299 int vobsub_id=-1;
300 static char* spudec_ifo=NULL;
301 int forced_subs_only=0;
302 int file_filter=1;
304 // cache2:
305 int stream_cache_size=-1;
307 // dump:
308 int stream_dump_type=0;
310 // A-V sync:
311 static float default_max_pts_correction=-1;//0.01f;
312 float audio_delay=0;
313 static int ignore_start=0;
315 double force_fps=0;
316 static int force_srate=0;
317 int frame_dropping=0; // option 0=no drop 1= drop vo 2= drop decode
318 static int play_n_frames=-1;
319 static int play_n_frames_mf=-1;
321 // sub:
322 char *font_name=NULL;
323 char *sub_font_name=NULL;
324 extern int font_fontconfig;
325 float font_factor=0.75;
326 float sub_delay=0;
327 float sub_fps=0;
328 int subcc_enabled=0;
329 int suboverlap_enabled = 1;
331 #include "sub/ass_mp.h"
333 char* current_module=NULL; // for debugging
336 // ---
338 #ifdef CONFIG_MENU
339 #include "m_struct.h"
340 #include "libmenu/menu.h"
341 static const vf_info_t* const libmenu_vfs[] = {
342 &vf_info_menu,
343 NULL
345 static vf_instance_t* vf_menu = NULL;
346 int use_menu = 0;
347 static char* menu_cfg = NULL;
348 static char* menu_root = "main";
349 #endif
352 edl_record_ptr edl_records = NULL; ///< EDL entries memory area
353 edl_record_ptr next_edl_record = NULL; ///< only for traversing edl_records
354 FILE* edl_fd = NULL; ///< fd to write to when in -edlout mode.
355 int use_filedir_conf;
356 int use_filename_title;
358 #include "mpcommon.h"
359 #include "command.h"
361 #include "metadata.h"
363 const void *mpctx_get_video_out(MPContext *mpctx)
365 return mpctx->video_out;
368 void *mpctx_get_demuxer(MPContext *mpctx)
370 return mpctx->demuxer;
373 void *mpctx_get_playtree_iter(MPContext *mpctx)
375 return mpctx->playtree_iter;
378 void *mpctx_get_mixer(MPContext *mpctx)
380 return &mpctx->mixer;
383 int mpctx_get_global_sub_size(MPContext *mpctx)
385 return mpctx->global_sub_size;
388 int mpctx_get_osd_function(MPContext *mpctx)
390 return mpctx->osd_function;
393 static float get_relative_time(struct MPContext *mpctx)
395 unsigned int new_time = GetTimer();
396 unsigned int delta = new_time - mpctx->last_time;
397 mpctx->last_time = new_time;
398 return delta * 0.000001;
401 static int is_valid_metadata_type(struct MPContext *mpctx, metadata_t type) {
402 switch (type)
404 /* check for valid video stream */
405 case META_VIDEO_CODEC:
406 case META_VIDEO_BITRATE:
407 case META_VIDEO_RESOLUTION:
409 if (!mpctx->sh_video)
410 return 0;
411 break;
414 /* check for valid audio stream */
415 case META_AUDIO_CODEC:
416 case META_AUDIO_BITRATE:
417 case META_AUDIO_SAMPLES:
419 if (!mpctx->sh_audio)
420 return 0;
421 break;
424 /* check for valid demuxer */
425 case META_INFO_TITLE:
426 case META_INFO_ARTIST:
427 case META_INFO_ALBUM:
428 case META_INFO_YEAR:
429 case META_INFO_COMMENT:
430 case META_INFO_TRACK:
431 case META_INFO_GENRE:
433 if (!mpctx->demuxer)
434 return 0;
435 break;
438 default:
439 break;
442 return 1;
445 static char *get_demuxer_info(struct MPContext *mpctx, char *tag) {
446 char **info = mpctx->demuxer->info;
447 int n;
449 if (!info || !tag)
450 return talloc_strdup(NULL, "");
452 for (n = 0; info[2*n] != NULL ; n++)
453 if (!strcasecmp (info[2*n], tag))
454 break;
456 return talloc_strdup(NULL, info[2*n+1] ? info[2*n+1] : "");
459 char *get_metadata(struct MPContext *mpctx, metadata_t type)
461 sh_audio_t * const sh_audio = mpctx->sh_audio;
462 sh_video_t * const sh_video = mpctx->sh_video;
464 if (!is_valid_metadata_type(mpctx, type))
465 return NULL;
467 switch (type) {
468 case META_NAME:
469 return talloc_strdup(NULL, mp_basename(mpctx->filename));
470 case META_VIDEO_CODEC:
471 if (sh_video->format == 0x10000001)
472 return talloc_strdup(NULL, "mpeg1");
473 else if (sh_video->format == 0x10000002)
474 return talloc_strdup(NULL, "mpeg2");
475 else if (sh_video->format == 0x10000004)
476 return talloc_strdup(NULL, "mpeg4");
477 else if (sh_video->format == 0x10000005)
478 return talloc_strdup(NULL, "h264");
479 else if (sh_video->format >= 0x20202020)
480 return talloc_asprintf(NULL, "%.4s", (char *) &sh_video->format);
481 else
482 return talloc_asprintf(NULL, "0x%08X", sh_video->format);
483 case META_VIDEO_BITRATE:
484 return talloc_asprintf(NULL, "%d kbps",
485 (int) (sh_video->i_bps * 8 / 1024));
486 case META_VIDEO_RESOLUTION:
487 return talloc_asprintf(NULL, "%d x %d", sh_video->disp_w,
488 sh_video->disp_h);
489 case META_AUDIO_CODEC:
490 if (sh_audio->codec && sh_audio->codec->name)
491 return talloc_strdup(NULL, sh_audio->codec->name);
492 return talloc_strdup(NULL, "");
493 case META_AUDIO_BITRATE:
494 return talloc_asprintf(NULL, "%d kbps",
495 (int) (sh_audio->i_bps * 8/1000));
496 case META_AUDIO_SAMPLES:
497 return talloc_asprintf(NULL, "%d Hz, %d ch.", sh_audio->samplerate,
498 sh_audio->channels);
500 /* check for valid demuxer */
501 case META_INFO_TITLE:
502 return get_demuxer_info(mpctx, "Title");
504 case META_INFO_ARTIST:
505 return get_demuxer_info(mpctx, "Artist");
507 case META_INFO_ALBUM:
508 return get_demuxer_info(mpctx, "Album");
510 case META_INFO_YEAR:
511 return get_demuxer_info(mpctx, "Year");
513 case META_INFO_COMMENT:
514 return get_demuxer_info(mpctx, "Comment");
516 case META_INFO_TRACK:
517 return get_demuxer_info(mpctx, "Track");
519 case META_INFO_GENRE:
520 return get_demuxer_info(mpctx, "Genre");
522 default:
523 break;
526 return talloc_strdup(NULL, "");
529 static void print_file_properties(struct MPContext *mpctx, const char *filename)
531 double start_pts = MP_NOPTS_VALUE;
532 double video_start_pts = MP_NOPTS_VALUE;
533 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_FILENAME=%s\n",
534 filename_recode(filename));
535 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_DEMUXER=%s\n", mpctx->demuxer->desc->name);
536 if (mpctx->sh_video) {
537 /* Assume FOURCC if all bytes >= 0x20 (' ') */
538 if (mpctx->sh_video->format >= 0x20202020)
539 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=%.4s\n", (char *)&mpctx->sh_video->format);
540 else
541 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=0x%08X\n", mpctx->sh_video->format);
542 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_BITRATE=%d\n", mpctx->sh_video->i_bps*8);
543 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_WIDTH=%d\n", mpctx->sh_video->disp_w);
544 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_HEIGHT=%d\n", mpctx->sh_video->disp_h);
545 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FPS=%5.3f\n", mpctx->sh_video->fps);
546 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_ASPECT=%1.4f\n", mpctx->sh_video->aspect);
547 video_start_pts = ds_get_next_pts(mpctx->d_video);
549 if (mpctx->sh_audio) {
550 /* Assume FOURCC if all bytes >= 0x20 (' ') */
551 if (mpctx->sh_audio->format >= 0x20202020)
552 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_FORMAT=%.4s\n", (char *)&mpctx->sh_audio->format);
553 else
554 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_FORMAT=%d\n", mpctx->sh_audio->format);
555 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_BITRATE=%d\n", mpctx->sh_audio->i_bps*8);
556 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_RATE=%d\n", mpctx->sh_audio->samplerate);
557 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_NCH=%d\n", mpctx->sh_audio->channels);
558 start_pts = ds_get_next_pts(mpctx->d_audio);
560 if (video_start_pts != MP_NOPTS_VALUE) {
561 if (start_pts == MP_NOPTS_VALUE || !mpctx->sh_audio ||
562 (mpctx->sh_video && video_start_pts < start_pts))
563 start_pts = video_start_pts;
565 if (start_pts != MP_NOPTS_VALUE)
566 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_START_TIME=%.2f\n", start_pts);
567 else
568 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_START_TIME=unknown\n");
569 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_LENGTH=%.2f\n", get_time_length(mpctx));
570 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_SEEKABLE=%d\n",
571 mpctx->stream->seek && (!mpctx->demuxer || mpctx->demuxer->seekable));
572 if (mpctx->demuxer) {
573 if (mpctx->demuxer->num_chapters == 0)
574 stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_NUM_CHAPTERS, &mpctx->demuxer->num_chapters);
575 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_CHAPTERS=%d\n", mpctx->demuxer->num_chapters);
579 /// step size of mixer changes
580 int volstep = 3;
582 #ifdef CONFIG_DVDNAV
583 static void mp_dvdnav_context_free(MPContext *ctx){
584 if (ctx->nav_smpi) free_mp_image(ctx->nav_smpi);
585 ctx->nav_smpi = NULL;
586 free(ctx->nav_buffer);
587 ctx->nav_buffer = NULL;
588 ctx->nav_start = NULL;
589 ctx->nav_in_size = 0;
591 #endif
593 static void uninit_subs(struct demuxer *demuxer)
595 for (int i = 0; i < MAX_S_STREAMS; i++) {
596 struct sh_sub *sh = demuxer->s_streams[i];
597 if (sh && sh->initialized)
598 sub_uninit(sh);
602 void uninit_player(struct MPContext *mpctx, unsigned int mask){
603 mask &= mpctx->initialized_flags;
605 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n*** uninit(0x%X)\n",mask);
607 if(mask&INITIALIZED_ACODEC){
608 mpctx->initialized_flags&=~INITIALIZED_ACODEC;
609 current_module="uninit_acodec";
610 if(mpctx->sh_audio) uninit_audio(mpctx->sh_audio);
611 mpctx->sh_audio=NULL;
612 mpctx->mixer.afilter = NULL;
615 if (mask & INITIALIZED_SUB) {
616 mpctx->initialized_flags &= ~INITIALIZED_SUB;
617 if (mpctx->d_sub->sh)
618 sub_switchoff(mpctx->d_sub->sh, mpctx->osd);
621 if(mask&INITIALIZED_VCODEC){
622 mpctx->initialized_flags&=~INITIALIZED_VCODEC;
623 current_module="uninit_vcodec";
624 if(mpctx->sh_video) uninit_video(mpctx->sh_video);
625 mpctx->sh_video=NULL;
626 #ifdef CONFIG_MENU
627 vf_menu=NULL;
628 #endif
631 if(mask&INITIALIZED_DEMUXER){
632 mpctx->initialized_flags&=~INITIALIZED_DEMUXER;
633 current_module="free_demuxer";
634 if (mpctx->num_sources) {
635 mpctx->demuxer = mpctx->sources[0].demuxer;
636 for (int i = 1; i < mpctx->num_sources; i++) {
637 uninit_subs(mpctx->sources[i].demuxer);
638 free_stream(mpctx->sources[i].stream);
639 free_demuxer(mpctx->sources[i].demuxer);
642 talloc_free(mpctx->sources);
643 mpctx->sources = NULL;
644 mpctx->num_sources = 0;
645 talloc_free(mpctx->timeline);
646 mpctx->timeline = NULL;
647 mpctx->num_timeline_parts = 0;
648 talloc_free(mpctx->chapters);
649 mpctx->chapters = NULL;
650 mpctx->num_chapters = 0;
651 mpctx->video_offset = 0;
652 if(mpctx->demuxer){
653 mpctx->stream=mpctx->demuxer->stream;
654 uninit_subs(mpctx->demuxer);
655 free_demuxer(mpctx->demuxer);
657 mpctx->demuxer=NULL;
660 // kill the cache process:
661 if(mask&INITIALIZED_STREAM){
662 mpctx->initialized_flags&=~INITIALIZED_STREAM;
663 current_module="uninit_stream";
664 if(mpctx->stream) free_stream(mpctx->stream);
665 mpctx->stream=NULL;
668 if(mask&INITIALIZED_VO){
669 mpctx->initialized_flags&=~INITIALIZED_VO;
670 current_module="uninit_vo";
671 vo_destroy(mpctx->video_out);
672 mpctx->video_out=NULL;
673 #ifdef CONFIG_DVDNAV
674 mp_dvdnav_context_free(mpctx);
675 #endif
678 // Must be after libvo uninit, as few vo drivers (svgalib) have tty code.
679 if(mask&INITIALIZED_GETCH2){
680 mpctx->initialized_flags&=~INITIALIZED_GETCH2;
681 current_module="uninit_getch2";
682 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[uninit getch2]]]\n");
683 // restore terminal:
684 getch2_disable();
687 if(mask&INITIALIZED_VOBSUB){
688 mpctx->initialized_flags&=~INITIALIZED_VOBSUB;
689 current_module="uninit_vobsub";
690 if(vo_vobsub) vobsub_close(vo_vobsub);
691 vo_vobsub=NULL;
694 if (mask&INITIALIZED_SPUDEC){
695 mpctx->initialized_flags&=~INITIALIZED_SPUDEC;
696 current_module="uninit_spudec";
697 spudec_free(vo_spudec);
698 vo_spudec=NULL;
701 if(mask&INITIALIZED_AO){
702 mpctx->initialized_flags&=~INITIALIZED_AO;
703 current_module="uninit_ao";
704 if (mpctx->edl_muted) mixer_mute(&mpctx->mixer);
705 if (mpctx->ao)
706 ao_uninit(mpctx->ao, mpctx->stop_play != AT_END_OF_FILE);
707 mpctx->ao = NULL;
710 current_module=NULL;
713 void exit_player_with_rc(struct MPContext *mpctx, enum exit_reason how, int rc)
715 if (mpctx->user_muted && !mpctx->edl_muted) mixer_mute(&mpctx->mixer);
716 uninit_player(mpctx, INITIALIZED_ALL);
717 #if defined(__MINGW32__) || defined(__CYGWIN__)
718 timeEndPeriod(1);
719 #endif
720 #ifdef CONFIG_X11
721 vo_uninit(mpctx->x11_state); // Close the X11 connection (if any is open).
722 #endif
724 current_module="uninit_input";
725 mp_input_uninit(mpctx->input);
726 #ifdef CONFIG_MENU
727 if (use_menu)
728 menu_uninit();
729 #endif
731 #ifdef CONFIG_FREETYPE
732 current_module="uninit_font";
733 if (mpctx->osd && mpctx->osd->sub_font != vo_font)
734 free_font_desc(mpctx->osd->sub_font);
735 free_font_desc(vo_font);
736 vo_font = NULL;
737 done_freetype();
738 #endif
739 osd_free(mpctx->osd);
741 #ifdef CONFIG_ASS
742 ass_library_done(ass_library);
743 ass_library = NULL;
744 #endif
746 current_module="exit_player";
748 // free mplayer config
749 if(mpctx->mconfig)
750 m_config_free(mpctx->mconfig);
751 mpctx->mconfig = NULL;
753 if(mpctx->playtree_iter)
754 play_tree_iter_free(mpctx->playtree_iter);
755 mpctx->playtree_iter = NULL;
756 if(mpctx->playtree)
757 play_tree_free(mpctx->playtree, 1);
758 mpctx->playtree = NULL;
760 talloc_free(mpctx->key_fifo);
762 free(edl_records); // free mem allocated for EDL
763 edl_records = NULL;
764 switch(how) {
765 case EXIT_QUIT:
766 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Quit");
767 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=QUIT\n");
768 break;
769 case EXIT_EOF:
770 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","End of file");
771 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=EOF\n");
772 break;
773 case EXIT_ERROR:
774 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Fatal error");
775 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=ERROR\n");
776 break;
777 default:
778 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=NONE\n");
780 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"max framesize was %d bytes\n",max_framesize);
782 exit(rc);
785 static void exit_player(struct MPContext *mpctx, enum exit_reason how)
787 exit_player_with_rc(mpctx, how, 1);
790 #ifndef __MINGW32__
791 static void child_sighandler(int x){
792 pid_t pid;
793 while((pid=waitpid(-1,NULL,WNOHANG)) > 0);
795 #endif
797 #ifdef CONFIG_CRASH_DEBUG
798 static char *prog_path;
799 static int crash_debug = 0;
800 #endif
802 static void exit_sighandler(int x){
803 static int sig_count=0;
804 #ifdef CONFIG_CRASH_DEBUG
805 if (!crash_debug || x != SIGTRAP)
806 #endif
807 ++sig_count;
808 if(sig_count==5)
810 /* We're crashing bad and can't uninit cleanly :(
811 * by popular request, we make one last (dirty)
812 * effort to restore the user's
813 * terminal. */
814 getch2_disable();
815 exit(1);
817 if(sig_count==6) exit(1);
818 if(sig_count>6){
819 // can't stop :(
820 #ifndef __MINGW32__
821 kill(getpid(),SIGKILL);
822 #endif
824 mp_msg(MSGT_CPLAYER, MSGL_FATAL, "\n");
825 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,
826 "\nMPlayer interrupted by signal %d in module: %s\n", x,
827 current_module ? current_module : "unknown");
828 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SIGNAL=%d\n", x);
829 if(sig_count<=1)
830 switch(x){
831 case SIGINT:
832 case SIGPIPE:
833 case SIGQUIT:
834 case SIGTERM:
835 case SIGKILL:
836 async_quit_request = 1;
837 return; // killed from keyboard (^C) or killed [-9]
838 case SIGILL:
839 #if CONFIG_RUNTIME_CPUDETECT
840 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL_RTCpuSel);
841 #else
842 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL);
843 #endif
844 case SIGFPE:
845 case SIGSEGV:
846 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGSEGV_SIGFPE);
847 default:
848 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGCRASH);
849 #ifdef CONFIG_CRASH_DEBUG
850 if (crash_debug) {
851 int gdb_pid;
852 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forking...\n");
853 gdb_pid = fork();
854 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forked...\n");
855 if (gdb_pid == 0) { // We are the child
856 char spid[20];
857 snprintf(spid, sizeof(spid), "%i", getppid());
858 getch2_disable(); // allow terminal to work properly with gdb
859 if (execlp("gdb", "gdb", prog_path, spid, "-ex", "bt", NULL) == -1)
860 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't start gdb\n");
861 } else if (gdb_pid < 0)
862 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't fork\n");
863 else {
864 waitpid(gdb_pid, NULL, 0);
866 if (x == SIGTRAP) return;
868 #endif
870 getch2_disable();
871 exit(1);
874 #include "cfg-mplayer.h"
876 static int cfg_include(m_option_t *conf, char *filename)
878 return m_config_parse_config_file(conf->priv, filename);
881 static void parse_cfgfiles(struct MPContext *mpctx, m_config_t* conf)
883 struct MPOpts *opts = &mpctx->opts;
884 char *conffile;
885 int conffile_fd;
886 if (!(opts->noconfig & 2) &&
887 m_config_parse_config_file(conf, MPLAYER_CONFDIR "/mplayer.conf") < 0)
888 exit_player(mpctx, EXIT_NONE);
889 if ((conffile = get_path("")) == NULL) {
890 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"Cannot find HOME directory.\n");
891 } else {
892 #ifdef __MINGW32__
893 mkdir(conffile);
894 #else
895 mkdir(conffile, 0777);
896 #endif
897 free(conffile);
898 if ((conffile = get_path("config")) == NULL) {
899 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"get_path(\"config\") problem\n");
900 } else {
901 if ((conffile_fd = open(conffile, O_CREAT | O_EXCL | O_WRONLY, 0666)) != -1) {
902 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Creating config file: %s\n", conffile);
903 write(conffile_fd, default_config, strlen(default_config));
904 close(conffile_fd);
906 if (!(opts->noconfig & 1) &&
907 m_config_parse_config_file(conf, conffile) < 0)
908 exit_player(mpctx, EXIT_NONE);
909 free(conffile);
914 #define PROFILE_CFG_PROTOCOL "protocol."
916 static void load_per_protocol_config (m_config_t* conf, const char *const file)
918 char *str;
919 char protocol[strlen (PROFILE_CFG_PROTOCOL) + strlen (file) + 1];
920 m_profile_t *p;
922 /* does filename actually uses a protocol ? */
923 str = strstr (file, "://");
924 if (!str)
925 return;
927 sprintf (protocol, "%s%s", PROFILE_CFG_PROTOCOL, file);
928 protocol[strlen (PROFILE_CFG_PROTOCOL)+strlen(file)-strlen(str)] = '\0';
929 p = m_config_get_profile (conf, protocol);
930 if (p)
932 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading protocol-related profile '%s'\n", protocol);
933 m_config_set_profile(conf,p);
937 #define PROFILE_CFG_EXTENSION "extension."
939 static void load_per_extension_config (m_config_t* conf, const char *const file)
941 char *str;
942 char extension[strlen (PROFILE_CFG_EXTENSION) + 8];
943 m_profile_t *p;
945 /* does filename actually have an extension ? */
946 str = strrchr (file, '.');
947 if (!str)
948 return;
950 sprintf (extension, PROFILE_CFG_EXTENSION);
951 strncat (extension, ++str, 7);
952 p = m_config_get_profile (conf, extension);
953 if (p)
955 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", extension);
956 m_config_set_profile(conf,p);
960 #define PROFILE_CFG_VO "vo."
961 #define PROFILE_CFG_AO "ao."
963 static void load_per_output_config (m_config_t* conf, char *cfg, char *out)
965 char profile[strlen (cfg) + strlen (out) + 1];
966 m_profile_t *p;
968 sprintf (profile, "%s%s", cfg, out);
969 p = m_config_get_profile (conf, profile);
970 if (p)
972 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", profile);
973 m_config_set_profile(conf,p);
978 * Tries to load a config file
979 * @return 0 if file was not found, 1 otherwise
981 static int try_load_config(m_config_t *conf, const char *file)
983 struct stat st;
984 if (stat(file, &st))
985 return 0;
986 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Loading config '%s'\n", file);
987 m_config_parse_config_file (conf, file);
988 return 1;
991 static void load_per_file_config (m_config_t* conf, const char *const file)
993 char *confpath;
994 char cfg[PATH_MAX];
995 const char *name;
997 if (strlen(file) > PATH_MAX - 14) {
998 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Filename is too long, can not load file or directory specific config files\n");
999 return;
1001 sprintf (cfg, "%s.conf", file);
1003 name = mp_basename(cfg);
1004 if (use_filedir_conf) {
1005 char dircfg[PATH_MAX];
1006 strcpy(dircfg, cfg);
1007 strcpy(dircfg + (name - cfg), "mplayer.conf");
1008 try_load_config(conf, dircfg);
1010 if (try_load_config(conf, cfg))
1011 return;
1014 if ((confpath = get_path (name)) != NULL)
1016 try_load_config(conf, confpath);
1018 free (confpath);
1022 /* When libmpdemux performs a blocking operation (network connection or
1023 * cache filling) if the operation fails we use this function to check
1024 * if it was interrupted by the user.
1025 * The function returns a new value for eof. */
1026 static int libmpdemux_was_interrupted(struct MPContext *mpctx, int stop_play)
1028 mp_cmd_t* cmd;
1029 if((cmd = mp_input_get_cmd(mpctx->input, 0, 0)) != NULL) {
1030 switch(cmd->id) {
1031 case MP_CMD_QUIT:
1032 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
1033 case MP_CMD_PLAY_TREE_STEP: {
1034 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_ENTRY : PT_PREV_ENTRY;
1035 mpctx->play_tree_step = (cmd->args[0].v.i == 0) ? 1 : cmd->args[0].v.i;
1036 } break;
1037 case MP_CMD_PLAY_TREE_UP_STEP: {
1038 stop_play = (cmd->args[0].v.i > 0) ? PT_UP_NEXT : PT_UP_PREV;
1039 } break;
1040 case MP_CMD_PLAY_ALT_SRC_STEP: {
1041 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_SRC : PT_PREV_SRC;
1042 } break;
1044 mp_cmd_free(cmd);
1046 return stop_play;
1049 static int playtree_add_playlist(struct MPContext *mpctx, play_tree_t* entry)
1051 play_tree_add_bpf(entry,mpctx->filename);
1054 if(!entry) {
1055 entry = mpctx->playtree_iter->tree;
1056 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1057 return PT_NEXT_ENTRY;
1059 if(mpctx->playtree_iter->tree == entry ) { // Loop with a single file
1060 if(play_tree_iter_up_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1061 return PT_NEXT_ENTRY;
1064 play_tree_remove(entry,1,1);
1065 return PT_NEXT_SRC;
1067 play_tree_insert_entry(mpctx->playtree_iter->tree,entry);
1068 play_tree_set_params_from(entry,mpctx->playtree_iter->tree);
1069 entry = mpctx->playtree_iter->tree;
1070 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1071 return PT_NEXT_ENTRY;
1073 play_tree_remove(entry,1,1);
1075 return PT_NEXT_SRC;
1078 void add_subtitles(struct MPContext *mpctx, char *filename, float fps, int noerr)
1080 struct MPOpts *opts = &mpctx->opts;
1081 sub_data *subd = NULL;
1082 struct ass_track *asst = NULL;
1083 bool is_native_ass = false;
1085 if (filename == NULL || mpctx->set_of_sub_size >= MAX_SUBTITLE_FILES)
1086 return;
1088 #ifdef CONFIG_ASS
1089 if (opts->ass_enabled) {
1090 #ifdef CONFIG_ICONV
1091 asst = mp_ass_read_stream(ass_library, filename, sub_cp);
1092 #else
1093 asst = mp_ass_read_stream(ass_library, filename, 0);
1094 #endif
1095 is_native_ass = asst;
1096 if (!asst) {
1097 subd = sub_read_file(filename, fps, &mpctx->opts);
1098 if (subd) {
1099 asst = mp_ass_read_subdata(ass_library, subd, fps);
1100 sub_free(subd);
1101 subd = NULL;
1104 } else
1105 #endif
1106 subd = sub_read_file(filename, fps, &mpctx->opts);
1109 if (!asst && !subd) {
1110 mp_tmsg(MSGT_CPLAYER, noerr ? MSGL_WARN : MSGL_ERR,
1111 "Cannot load subtitles: %s\n", filename_recode(filename));
1112 return;
1115 mpctx->set_of_ass_tracks[mpctx->set_of_sub_size] = asst;
1116 mpctx->set_of_subtitles[mpctx->set_of_sub_size] = subd;
1117 mpctx->track_was_native_ass[mpctx->set_of_sub_size] = is_native_ass;
1118 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_ID=%d\n", mpctx->set_of_sub_size);
1119 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_FILENAME=%s\n",
1120 filename_recode(filename));
1121 ++mpctx->set_of_sub_size;
1122 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "SUB: Added subtitle file (%d): %s\n", mpctx->set_of_sub_size,
1123 filename_recode(filename));
1126 void init_vo_spudec(struct MPContext *mpctx)
1128 spudec_free(vo_spudec);
1129 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
1130 vo_spudec = NULL;
1132 // we currently can't work without video stream
1133 if (!mpctx->sh_video)
1134 return;
1136 if (spudec_ifo) {
1137 unsigned int palette[16], width, height;
1138 current_module="spudec_init_vobsub";
1139 if (vobsub_parse_ifo(NULL,spudec_ifo, palette, &width, &height, 1, -1, NULL) >= 0)
1140 vo_spudec=spudec_new_scaled(palette, width, height, NULL, 0);
1143 #ifdef CONFIG_DVDREAD
1144 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVD) {
1145 current_module="spudec_init_dvdread";
1146 vo_spudec=spudec_new_scaled(((dvd_priv_t *)(mpctx->stream->priv))->cur_pgc->palette,
1147 mpctx->sh_video->disp_w, mpctx->sh_video->disp_h,
1148 NULL, 0);
1150 #endif
1152 #ifdef CONFIG_DVDNAV
1153 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVDNAV) {
1154 unsigned int *palette = mp_dvdnav_get_spu_clut(mpctx->stream);
1155 current_module="spudec_init_dvdnav";
1156 vo_spudec=spudec_new_scaled(palette, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, NULL, 0);
1158 #endif
1160 if (vo_spudec==NULL) {
1161 sh_sub_t *sh = mpctx->d_sub->sh;
1162 current_module="spudec_init_normal";
1163 vo_spudec=spudec_new_scaled(NULL, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, sh->extradata, sh->extradata_len);
1164 spudec_set_font_factor(vo_spudec,font_factor);
1167 if (vo_spudec!=NULL) {
1168 mpctx->initialized_flags|=INITIALIZED_SPUDEC;
1169 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
1174 * In Mac OS X the SDL-lib is built upon Cocoa. The easiest way to
1175 * make it all work is to use the builtin SDL-bootstrap code, which
1176 * will be done automatically by replacing our main() if we include SDL.h.
1178 #if defined(__APPLE__) && defined(CONFIG_SDL)
1179 #ifdef CONFIG_SDL_SDL_H
1180 #include <SDL/SDL.h>
1181 #else
1182 #include <SDL.h>
1183 #endif
1184 #endif
1187 * \brief append a formatted string
1188 * \param buf buffer to print into
1189 * \param pos position of terminating 0 in buf
1190 * \param len maximum number of characters in buf, not including terminating 0
1191 * \param format printf format string
1193 static void saddf(char *buf, unsigned *pos, int len, const char *format, ...)
1195 va_list va;
1196 va_start(va, format);
1197 *pos += vsnprintf(&buf[*pos], len - *pos, format, va);
1198 va_end(va);
1199 if (*pos >= len ) {
1200 buf[len] = 0;
1201 *pos = len;
1206 * \brief append time in the hh:mm:ss.f format
1207 * \param buf buffer to print into
1208 * \param pos position of terminating 0 in buf
1209 * \param len maximum number of characters in buf, not including terminating 0
1210 * \param time time value to convert/append
1212 static void sadd_hhmmssf(char *buf, unsigned *pos, int len, float time) {
1213 int64_t tenths = 10 * time;
1214 int f1 = tenths % 10;
1215 int ss = (tenths / 10) % 60;
1216 int mm = (tenths / 600) % 60;
1217 int hh = tenths / 36000;
1218 if (time <= 0) {
1219 saddf(buf, pos, len, "unknown");
1220 return;
1222 if (hh > 0)
1223 saddf(buf, pos, len, "%2d:", hh);
1224 if (hh > 0 || mm > 0)
1225 saddf(buf, pos, len, "%02d:", mm);
1226 saddf(buf, pos, len, "%02d.%1d", ss, f1);
1229 static void print_status(struct MPContext *mpctx, double a_pos, bool at_frame)
1231 struct MPOpts *opts = &mpctx->opts;
1232 sh_video_t * const sh_video = mpctx->sh_video;
1234 if (mpctx->sh_audio && a_pos == MP_NOPTS_VALUE)
1235 a_pos = playing_audio_pts(mpctx);
1236 if (mpctx->sh_audio && sh_video && at_frame) {
1237 mpctx->last_av_difference = a_pos - mpctx->video_pts - audio_delay;
1238 if (mpctx->time_frame > 0)
1239 mpctx->last_av_difference += mpctx->time_frame * opts->playback_speed;
1240 if (mpctx->last_av_difference > 0.5 && drop_frame_cnt > 50
1241 && !mpctx->drop_message_shown) {
1242 mp_tmsg(MSGT_AVSYNC,MSGL_WARN,SystemTooSlow);
1243 mpctx->drop_message_shown = true;
1246 if (opts->quiet)
1247 return;
1250 int width;
1251 char *line;
1252 unsigned pos = 0;
1253 get_screen_size();
1254 if (screen_width > 0)
1255 width = screen_width;
1256 else
1257 width = 80;
1258 #if defined(__MINGW32__) || defined(__CYGWIN__) || defined(__OS2__)
1259 /* Windows command line is broken (MinGW's rxvt works, but we
1260 * should not depend on that). */
1261 width--;
1262 #endif
1263 line = malloc(width + 1); // one additional char for the terminating null
1265 // Audio time
1266 if (mpctx->sh_audio) {
1267 saddf(line, &pos, width, "A:%6.1f ", a_pos);
1268 if (!sh_video) {
1269 float len = get_time_length(mpctx);
1270 saddf(line, &pos, width, "(");
1271 sadd_hhmmssf(line, &pos, width, a_pos);
1272 saddf(line, &pos, width, ") of %.1f (", len);
1273 sadd_hhmmssf(line, &pos, width, len);
1274 saddf(line, &pos, width, ") ");
1278 // Video time
1279 if (sh_video)
1280 saddf(line, &pos, width, "V:%6.1f ", mpctx->video_pts);
1282 // A-V sync
1283 if (mpctx->sh_audio && sh_video)
1284 saddf(line, &pos, width, "A-V:%7.3f ct:%7.3f ",
1285 mpctx->last_av_difference, mpctx->total_avsync_change);
1287 // Video stats
1288 if (sh_video)
1289 saddf(line, &pos, width, "%3d/%3d ",
1290 (int)sh_video->num_frames,
1291 (int)sh_video->num_frames_decoded);
1293 // CPU usage
1294 if (sh_video) {
1295 if (sh_video->timer > 0.5)
1296 saddf(line, &pos, width, "%2d%% %2d%% %4.1f%% ",
1297 (int)(100.0*video_time_usage*opts->playback_speed/(double)sh_video->timer),
1298 (int)(100.0*vout_time_usage*opts->playback_speed/(double)sh_video->timer),
1299 (100.0*audio_time_usage*opts->playback_speed/(double)sh_video->timer));
1300 else
1301 saddf(line, &pos, width, "??%% ??%% ??,?%% ");
1302 } else if (mpctx->sh_audio) {
1303 if (mpctx->delay > 0.5)
1304 saddf(line, &pos, width, "%4.1f%% ",
1305 100.0*audio_time_usage/(double)mpctx->delay);
1306 else
1307 saddf(line, &pos, width, "??,?%% ");
1310 // VO stats
1311 if (sh_video)
1312 saddf(line, &pos, width, "%d %d ", drop_frame_cnt, output_quality);
1314 #ifdef CONFIG_STREAM_CACHE
1315 // cache stats
1316 if (stream_cache_size > 0)
1317 saddf(line, &pos, width, "%d%% ", cache_fill_status(mpctx->stream));
1318 #endif
1320 // other
1321 if (opts->playback_speed != 1)
1322 saddf(line, &pos, width, "%4.2fx ", opts->playback_speed);
1324 // end
1325 if (erase_to_end_of_line) {
1326 line[pos] = 0;
1327 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s%s\r", line, erase_to_end_of_line);
1328 } else {
1329 memset(&line[pos], ' ', width - pos);
1330 line[width] = 0;
1331 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s\r", line);
1333 free(line);
1337 * \brief build a chain of audio filters that converts the input format
1338 * to the ao's format, taking into account the current playback_speed.
1339 * sh_audio describes the requested input format of the chain.
1340 * ao describes the requested output format of the chain.
1342 static int build_afilter_chain(struct MPContext *mpctx)
1344 struct sh_audio *sh_audio = mpctx->sh_audio;
1345 struct ao *ao = mpctx->ao;
1346 struct MPOpts *opts = &mpctx->opts;
1347 int new_srate;
1348 int result;
1349 if (!sh_audio)
1351 mpctx->mixer.afilter = NULL;
1352 return 0;
1354 if(af_control_any_rev(sh_audio->afilter,
1355 AF_CONTROL_PLAYBACK_SPEED | AF_CONTROL_SET,
1356 &opts->playback_speed)) {
1357 new_srate = sh_audio->samplerate;
1358 } else {
1359 new_srate = sh_audio->samplerate * opts->playback_speed;
1360 if (new_srate != ao->samplerate) {
1361 // limits are taken from libaf/af_resample.c
1362 if (new_srate < 8000)
1363 new_srate = 8000;
1364 if (new_srate > 192000)
1365 new_srate = 192000;
1366 opts->playback_speed = (float)new_srate / (float)sh_audio->samplerate;
1369 result = init_audio_filters(sh_audio, new_srate,
1370 &ao->samplerate, &ao->channels, &ao->format);
1371 mpctx->mixer.afilter = sh_audio->afilter;
1372 return result;
1376 typedef struct mp_osd_msg mp_osd_msg_t;
1377 struct mp_osd_msg {
1378 /// Previous message on the stack.
1379 mp_osd_msg_t* prev;
1380 /// Message text.
1381 char msg[128];
1382 int id,level,started;
1383 /// Display duration in ms.
1384 unsigned time;
1387 /// OSD message stack.
1388 static mp_osd_msg_t* osd_msg_stack = NULL;
1391 * \brief Add a message on the OSD message stack
1393 * If a message with the same id is already present in the stack
1394 * it is pulled on top of the stack, otherwise a new message is created.
1397 static void set_osd_msg_va(int id, int level, int time, const char *fmt,
1398 va_list ap)
1400 mp_osd_msg_t *msg,*last=NULL;
1401 int r;
1403 // look if the id is already in the stack
1404 for(msg = osd_msg_stack ; msg && msg->id != id ;
1405 last = msg, msg = msg->prev);
1406 // not found: alloc it
1407 if(!msg) {
1408 msg = calloc(1,sizeof(mp_osd_msg_t));
1409 msg->prev = osd_msg_stack;
1410 osd_msg_stack = msg;
1411 } else if(last) { // found, but it's not on top of the stack
1412 last->prev = msg->prev;
1413 msg->prev = osd_msg_stack;
1414 osd_msg_stack = msg;
1416 // write the msg
1417 r = vsnprintf(msg->msg, 128, fmt, ap);
1418 if(r >= 128) msg->msg[127] = 0;
1419 // set id and time
1420 msg->id = id;
1421 msg->level = level;
1422 msg->time = time;
1426 void set_osd_msg(int id, int level, int time, const char *fmt, ...)
1428 va_list ap;
1429 va_start(ap, fmt);
1430 set_osd_msg_va(id, level, time, fmt, ap);
1431 va_end(ap);
1434 void set_osd_tmsg(int id, int level, int time, const char *fmt, ...)
1436 va_list ap;
1437 va_start(ap, fmt);
1438 set_osd_msg_va(id, level, time, mp_gtext(fmt), ap);
1439 va_end(ap);
1444 * \brief Remove a message from the OSD stack
1446 * This function can be used to get rid of a message right away.
1450 void rm_osd_msg(int id) {
1451 mp_osd_msg_t *msg,*last=NULL;
1453 // Search for the msg
1454 for(msg = osd_msg_stack ; msg && msg->id != id ;
1455 last = msg, msg = msg->prev);
1456 if(!msg) return;
1458 // Detach it from the stack and free it
1459 if(last)
1460 last->prev = msg->prev;
1461 else
1462 osd_msg_stack = msg->prev;
1463 free(msg);
1467 * \brief Remove all messages from the OSD stack
1471 static void clear_osd_msgs(void) {
1472 mp_osd_msg_t* msg = osd_msg_stack, *prev = NULL;
1473 while(msg) {
1474 prev = msg->prev;
1475 free(msg);
1476 msg = prev;
1478 osd_msg_stack = NULL;
1482 * \brief Get the current message from the OSD stack.
1484 * This function decrements the message timer and destroys the old ones.
1485 * The message that should be displayed is returned (if any).
1489 static mp_osd_msg_t* get_osd_msg(struct MPContext *mpctx)
1491 struct MPOpts *opts = &mpctx->opts;
1492 mp_osd_msg_t *msg,*prev,*last = NULL;
1493 static unsigned last_update = 0;
1494 unsigned now = GetTimerMS();
1495 unsigned diff;
1496 char hidden_dec_done = 0;
1498 if (mpctx->osd_visible) {
1499 // 36000000 means max timed visibility is 1 hour into the future, if
1500 // the difference is greater assume it's wrapped around from below 0
1501 if (mpctx->osd_visible - now > 36000000) {
1502 mpctx->osd_visible = 0;
1503 vo_osd_progbar_type = -1; // disable
1504 vo_osd_changed(OSDTYPE_PROGBAR);
1505 mpctx->osd_function = mpctx->paused ? OSD_PAUSE : OSD_PLAY;
1508 if (mpctx->osd_show_percentage_until - now > 36000000)
1509 mpctx->osd_show_percentage_until = 0;
1511 if(!last_update) last_update = now;
1512 diff = now >= last_update ? now - last_update : 0;
1514 last_update = now;
1516 // Look for the first message in the stack with high enough level.
1517 for(msg = osd_msg_stack ; msg ; last = msg, msg = prev) {
1518 prev = msg->prev;
1519 if (msg->level > opts->osd_level && hidden_dec_done)
1520 continue;
1521 // The message has a high enough level or it is the first hidden one
1522 // in both cases we decrement the timer or kill it.
1523 if(!msg->started || msg->time > diff) {
1524 if(msg->started) msg->time -= diff;
1525 else msg->started = 1;
1526 // display it
1527 if (msg->level <= opts->osd_level)
1528 return msg;
1529 hidden_dec_done = 1;
1530 continue;
1532 // kill the message
1533 free(msg);
1534 if(last) {
1535 last->prev = prev;
1536 msg = last;
1537 } else {
1538 osd_msg_stack = prev;
1539 msg = NULL;
1542 // Nothing found
1543 return NULL;
1547 * \brief Display the OSD bar.
1549 * Display the OSD bar or fall back on a simple message.
1553 void set_osd_bar(struct MPContext *mpctx, int type,const char* name,double min,double max,double val) {
1554 struct MPOpts *opts = &mpctx->opts;
1555 if (opts->osd_level < 1)
1556 return;
1558 if(mpctx->sh_video) {
1559 mpctx->osd_visible = (GetTimerMS() + 1000) | 1;
1560 vo_osd_progbar_type = type;
1561 vo_osd_progbar_value = 256*(val-min)/(max-min);
1562 vo_osd_changed(OSDTYPE_PROGBAR);
1563 return;
1566 set_osd_msg(OSD_MSG_BAR, 1, opts->osd_duration, "%s: %d %%",
1567 name, ROUND(100*(val-min)/(max-min)));
1571 * \brief Display text subtitles on the OSD
1573 void set_osd_subtitle(struct MPContext *mpctx, subtitle *subs)
1575 int i;
1576 vo_sub = subs;
1577 vo_osd_changed(OSDTYPE_SUBTITLE);
1578 if (!mpctx->sh_video) {
1579 // reverse order, since newest set_osd_msg is displayed first
1580 for (i = SUB_MAX_TEXT - 1; i >= 0; i--) {
1581 if (!subs || i >= subs->lines || !subs->text[i])
1582 rm_osd_msg(OSD_MSG_SUB_BASE + i);
1583 else {
1584 // HACK: currently display time for each sub line except the last is set to 2 seconds.
1585 int display_time = i == subs->lines - 1 ? 180000 : 2000;
1586 set_osd_msg(OSD_MSG_SUB_BASE + i, 1, display_time, "%s", subs->text[i]);
1593 * \brief Update the OSD message line.
1595 * This function displays the current message on the vo OSD or on the term.
1596 * If the stack is empty and the OSD level is high enough the timer
1597 * is displayed (only on the vo OSD).
1601 static void update_osd_msg(struct MPContext *mpctx)
1603 struct MPOpts *opts = &mpctx->opts;
1604 mp_osd_msg_t *msg;
1605 struct osd_state *osd = mpctx->osd;
1606 char osd_text_timer[128];
1608 if (mpctx->add_osd_seek_info) {
1609 double percentage = get_percent_pos(mpctx);
1610 set_osd_bar(mpctx, 0, "Position", 0, 100, percentage);
1611 if (mpctx->sh_video)
1612 mpctx->osd_show_percentage_until = (GetTimerMS() + 1000) | 1;
1613 mpctx->add_osd_seek_info = false;
1616 // Look if we have a msg
1617 if((msg = get_osd_msg(mpctx))) {
1618 if (strcmp(osd->osd_text, msg->msg)) {
1619 strncpy(osd->osd_text, msg->msg, 127);
1620 if(mpctx->sh_video) vo_osd_changed(OSDTYPE_OSD); else
1621 if(opts->term_osd)
1622 mp_msg(MSGT_CPLAYER,MSGL_STATUS, "%s%s\n", opts->term_osd_esc,
1623 msg->msg);
1625 return;
1628 if(mpctx->sh_video) {
1629 // fallback on the timer
1630 if (opts->osd_level >= 2) {
1631 int len = get_time_length(mpctx);
1632 int percentage = -1;
1633 char percentage_text[10];
1634 int pts = get_current_time(mpctx);
1636 if (mpctx->osd_show_percentage_until)
1637 percentage = get_percent_pos(mpctx);
1639 if (percentage >= 0)
1640 snprintf(percentage_text, 9, " (%d%%)", percentage);
1641 else
1642 percentage_text[0] = 0;
1644 if (opts->osd_level == 3)
1645 snprintf(osd_text_timer, 63,
1646 "%c %02d:%02d:%02d / %02d:%02d:%02d%s",
1647 mpctx->osd_function,pts/3600,(pts/60)%60,pts%60,
1648 len/3600,(len/60)%60,len%60,percentage_text);
1649 else
1650 snprintf(osd_text_timer, 63, "%c %02d:%02d:%02d%s",
1651 mpctx->osd_function,pts/3600,(pts/60)%60,
1652 pts%60,percentage_text);
1653 } else
1654 osd_text_timer[0]=0;
1656 if (strcmp(osd->osd_text, osd_text_timer)) {
1657 strncpy(osd->osd_text, osd_text_timer, 63);
1658 vo_osd_changed(OSDTYPE_OSD);
1660 return;
1663 // Clear the term osd line
1664 if (opts->term_osd && osd->osd_text[0]) {
1665 osd->osd_text[0] = 0;
1666 printf("%s\n", opts->term_osd_esc);
1670 ///@}
1671 // OSDMsgStack
1674 void reinit_audio_chain(struct MPContext *mpctx)
1676 struct MPOpts *opts = &mpctx->opts;
1677 struct ao *ao;
1678 if (!mpctx->sh_audio)
1679 return;
1680 if (!(mpctx->initialized_flags & INITIALIZED_ACODEC)) {
1681 current_module="init_audio_codec";
1682 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1683 if(!init_best_audio_codec(mpctx->sh_audio,audio_codec_list,audio_fm_list)){
1684 goto init_error;
1686 mpctx->initialized_flags|=INITIALIZED_ACODEC;
1687 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1691 current_module="af_preinit";
1692 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1693 mpctx->initialized_flags |= INITIALIZED_AO;
1694 mpctx->ao = ao_create();
1695 mpctx->ao->samplerate = force_srate;
1696 mpctx->ao->format = opts->audio_output_format;
1698 ao = mpctx->ao;
1700 // first init to detect best values
1701 if(!init_audio_filters(mpctx->sh_audio, // preliminary init
1702 // input:
1703 mpctx->sh_audio->samplerate,
1704 // output:
1705 &ao->samplerate, &ao->channels, &ao->format)) {
1706 mp_tmsg(MSGT_CPLAYER,MSGL_ERR, "Error at audio filter chain "
1707 "pre-init!\n");
1708 exit_player(mpctx, EXIT_ERROR);
1710 if (!ao->initialized) {
1711 current_module="ao2_init";
1712 ao->buffersize = opts->ao_buffersize;
1713 ao_init(ao, opts->audio_driver_list);
1714 if (!ao->initialized) {
1715 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Could not open/initialize audio device -> no sound.\n");
1716 goto init_error;
1718 mp_msg(MSGT_CPLAYER,MSGL_INFO,"AO: [%s] %dHz %dch %s (%d bytes per sample)\n",
1719 ao->driver->info->short_name,
1720 ao->samplerate, ao->channels,
1721 af_fmt2str_short(ao->format),
1722 af_fmt2bits(ao->format)/8 );
1723 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Description: %s\nAO: Author: %s\n",
1724 ao->driver->info->name, ao->driver->info->author);
1725 if (strlen(ao->driver->info->comment) > 0)
1726 mp_msg(MSGT_CPLAYER, MSGL_V, "AO: Comment: %s\n",
1727 ao->driver->info->comment);
1730 // init audio filters:
1731 current_module="af_init";
1732 if (!build_afilter_chain(mpctx)) {
1733 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Couldn't find matching filter/ao format!\n");
1734 goto init_error;
1736 mpctx->mixer.ao = ao;
1737 mpctx->mixer.volstep = volstep;
1738 mpctx->syncing_audio = true;
1739 return;
1741 init_error:
1742 uninit_player(mpctx, INITIALIZED_ACODEC|INITIALIZED_AO); // close codec and possibly AO
1743 mpctx->sh_audio=mpctx->d_audio->sh=NULL; // -> nosound
1744 mpctx->d_audio->id = -2;
1748 ///@}
1749 // Command2Property
1752 // Return pts value corresponding to the end point of audio written to the
1753 // ao so far.
1754 static double written_audio_pts(struct MPContext *mpctx)
1756 sh_audio_t *sh_audio = mpctx->sh_audio;
1757 demux_stream_t *d_audio = mpctx->d_audio;
1758 double buffered_output;
1759 // first calculate the end pts of audio that has been output by decoder
1760 double a_pts = sh_audio->pts;
1761 if (a_pts != MP_NOPTS_VALUE)
1762 // Good, decoder supports new way of calculating audio pts.
1763 // sh_audio->pts is the timestamp of the latest input packet with
1764 // known pts that the decoder has decoded. sh_audio->pts_bytes is
1765 // the amount of bytes the decoder has written after that timestamp.
1766 a_pts += sh_audio->pts_bytes / (double) sh_audio->o_bps;
1767 else {
1768 // Decoder doesn't support new way of calculating pts (or we're
1769 // being called before it has decoded anything with known timestamp).
1770 // Use the old method of audio pts calculation: take the timestamp
1771 // of last packet with known pts the decoder has read data from,
1772 // and add amount of bytes read after the beginning of that packet
1773 // divided by input bps. This will be inaccurate if the input/output
1774 // ratio is not constant for every audio packet or if it is constant
1775 // but not accurately known in sh_audio->i_bps.
1777 a_pts = d_audio->pts;
1778 // ds_tell_pts returns bytes read after last timestamp from
1779 // demuxing layer, decoder might use sh_audio->a_in_buffer for bytes
1780 // it has read but not decoded
1781 if (sh_audio->i_bps)
1782 a_pts += (ds_tell_pts(d_audio) - sh_audio->a_in_buffer_len) /
1783 (double)sh_audio->i_bps;
1785 // Now a_pts hopefully holds the pts for end of audio from decoder.
1786 // Substract data in buffers between decoder and audio out.
1788 // Decoded but not filtered
1789 a_pts -= sh_audio->a_buffer_len / (double)sh_audio->o_bps;
1791 // Data buffered in audio filters, measured in bytes of "missing" output
1792 buffered_output = af_calc_delay(sh_audio->afilter);
1794 // Data that was ready for ao but was buffered because ao didn't fully
1795 // accept everything to internal buffers yet
1796 buffered_output += sh_audio->a_out_buffer_len;
1798 // Filters divide audio length by playback_speed, so multiply by it
1799 // to get the length in original units without speedup or slowdown
1800 a_pts -= buffered_output * mpctx->opts.playback_speed / mpctx->ao->bps;
1802 return a_pts + mpctx->video_offset;
1805 // Return pts value corresponding to currently playing audio.
1806 double playing_audio_pts(struct MPContext *mpctx)
1808 return written_audio_pts(mpctx) - mpctx->opts.playback_speed *
1809 ao_get_delay(mpctx->ao);
1812 static bool is_av_sub(int type)
1814 return type == 'b' || type == 'p' || type == 'x';
1817 void update_subtitles(struct MPContext *mpctx, double refpts,
1818 double sub_offset, bool reset)
1820 struct MPOpts *opts = &mpctx->opts;
1821 struct sh_video *sh_video = mpctx->sh_video;
1822 struct demux_stream *d_sub = mpctx->d_sub;
1823 double curpts = refpts + sub_delay;
1824 unsigned char *packet=NULL;
1825 int len;
1826 struct sh_sub *sh_sub = d_sub->sh;
1827 int type = sh_sub ? sh_sub->type : 'v';
1828 static subtitle subs;
1829 if (reset) {
1830 if (sh_sub)
1831 sub_reset(sh_sub, mpctx->osd);
1832 sub_clear_text(&subs, MP_NOPTS_VALUE);
1833 if (vo_sub)
1834 set_osd_subtitle(mpctx, NULL);
1835 if (vo_spudec) {
1836 spudec_reset(vo_spudec);
1837 vo_osd_changed(OSDTYPE_SPU);
1839 #ifdef CONFIG_FFMPEG
1840 if (is_av_sub(type))
1841 reset_avsub(sh_sub);
1842 #endif
1843 return;
1845 // find sub
1846 if (mpctx->subdata) {
1847 if (sub_fps==0) sub_fps = sh_video ? sh_video->fps : 25;
1848 current_module = "find_sub";
1849 find_sub(mpctx, mpctx->subdata, curpts *
1850 (mpctx->subdata->sub_uses_time ? 100. : sub_fps));
1851 if (vo_sub)
1852 mpctx->vo_sub_last = vo_sub;
1855 // DVD sub:
1856 if (vobsub_id >= 0 || type == 'v') {
1857 int timestamp;
1858 current_module = "spudec";
1859 /* Get a sub packet from the DVD or a vobsub */
1860 while(1) {
1861 // Vobsub
1862 len = 0;
1863 if (vo_vobsub) {
1864 if (curpts >= 0) {
1865 len = vobsub_get_packet(vo_vobsub, curpts,
1866 (void**)&packet, &timestamp);
1867 if (len > 0) {
1868 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);
1871 } else {
1872 // DVD sub
1873 len = ds_get_packet_sub(d_sub, (unsigned char**)&packet);
1874 if (len > 0) {
1875 // XXX This is wrong, sh_video->pts can be arbitrarily
1876 // much behind demuxing position. Unfortunately using
1877 // d_video->pts which would have been the simplest
1878 // improvement doesn't work because mpeg specific hacks
1879 // in video.c set d_video->pts to 0.
1880 float x = d_sub->pts - refpts;
1881 if (x > -20 && x < 20) // prevent missing subs on pts reset
1882 timestamp = 90000*d_sub->pts;
1883 else timestamp = 90000*curpts;
1884 mp_dbg(MSGT_CPLAYER, MSGL_V, "\rDVD sub: len=%d "
1885 "v_pts=%5.3f s_pts=%5.3f ts=%d \n", len,
1886 refpts, d_sub->pts, timestamp);
1889 if (len<=0 || !packet) break;
1890 // create it only here, since with some broken demuxers we might
1891 // type = v but no DVD sub and we currently do not change the
1892 // "original frame size" ever after init, leading to wrong-sized
1893 // PGS subtitles.
1894 if (!vo_spudec)
1895 vo_spudec = spudec_new(NULL);
1896 if (vo_vobsub || timestamp >= 0)
1897 spudec_assemble(vo_spudec, packet, len, timestamp);
1899 } else if (is_text_sub(type) || is_av_sub(type) || type == 'd') {
1900 if (type == 'd' && !d_sub->demuxer->teletext) {
1901 tt_stream_props tsp = {0};
1902 void *ptr = &tsp;
1903 if (teletext_control(NULL, TV_VBI_CONTROL_START, &ptr) == VBI_CONTROL_TRUE)
1904 d_sub->demuxer->teletext = ptr;
1906 if (d_sub->non_interleaved)
1907 ds_get_next_pts(d_sub);
1909 while (d_sub->first) {
1910 double subpts = ds_get_next_pts(d_sub) + sub_offset;
1911 if (subpts > curpts) {
1912 // Libass handled subs can be fed to it in advance
1913 if (!opts->ass_enabled || !is_text_sub(type))
1914 break;
1915 // Try to avoid demuxing whole file at once
1916 if (d_sub->non_interleaved && subpts > curpts + 1)
1917 break;
1919 double duration = d_sub->first->duration;
1920 len = ds_get_packet_sub(d_sub, &packet);
1921 if (is_av_sub(type)) {
1922 #ifdef CONFIG_FFMPEG
1923 int ret = decode_avsub(sh_sub, packet, len, subpts, duration);
1924 if (ret < 0)
1925 mp_msg(MSGT_SPUDEC, MSGL_WARN, "lavc failed decoding "
1926 "subtitle\n");
1927 #endif
1928 continue;
1930 if (type == 'm') {
1931 if (len < 2) continue;
1932 len = FFMIN(len - 2, AV_RB16(packet));
1933 packet += 2;
1935 if (type == 'd') {
1936 if (d_sub->demuxer->teletext) {
1937 uint8_t *p = packet;
1938 p++;
1939 len--;
1940 while (len >= 46) {
1941 int sublen = p[1];
1942 if (p[0] == 2 || p[0] == 3)
1943 teletext_control(d_sub->demuxer->teletext,
1944 TV_VBI_CONTROL_DECODE_DVB, p + 2);
1945 p += sublen + 2;
1946 len -= sublen + 2;
1949 continue;
1951 if (sh_sub && sh_sub->active) {
1952 sub_decode(sh_sub, mpctx->osd, packet, len, subpts, duration);
1953 continue;
1955 if (subpts != MP_NOPTS_VALUE) {
1956 if (duration < 0)
1957 sub_clear_text(&subs, MP_NOPTS_VALUE);
1958 if (type == 'a') { // ssa/ass subs without libass => convert to plaintext
1959 int i;
1960 unsigned char* p = packet;
1961 for (i=0; i < 8 && *p != '\0'; p++)
1962 if (*p == ',')
1963 i++;
1964 if (*p == '\0') /* Broken line? */
1965 continue;
1966 len -= p - packet;
1967 packet = p;
1969 double endpts = MP_NOPTS_VALUE;
1970 if (subpts != MP_NOPTS_VALUE && duration >= 0)
1971 endpts = subpts + duration;
1972 sub_add_text(&subs, packet, len, endpts);
1973 set_osd_subtitle(mpctx, &subs);
1975 if (d_sub->non_interleaved)
1976 ds_get_next_pts(d_sub);
1978 if (!opts->ass_enabled)
1979 if (sub_clear_text(&subs, curpts))
1980 set_osd_subtitle(mpctx, &subs);
1982 if (vo_spudec) {
1983 spudec_heartbeat(vo_spudec, 90000*curpts);
1984 if (spudec_changed(vo_spudec))
1985 vo_osd_changed(OSDTYPE_SPU);
1988 current_module=NULL;
1991 static void update_teletext(sh_video_t *sh_video, demuxer_t *demuxer, int reset)
1993 int page_changed;
1995 if (!demuxer->teletext)
1996 return;
1998 //Also forcing page update when such ioctl is not supported or call error occured
1999 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_IS_CHANGED,&page_changed)!=VBI_CONTROL_TRUE)
2000 page_changed=1;
2002 if(!page_changed)
2003 return;
2005 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_GET_VBIPAGE,&vo_osd_teletext_page)!=VBI_CONTROL_TRUE)
2006 vo_osd_teletext_page=NULL;
2007 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_GET_HALF_PAGE,&vo_osd_teletext_half)!=VBI_CONTROL_TRUE)
2008 vo_osd_teletext_half=0;
2009 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_GET_MODE,&vo_osd_teletext_mode)!=VBI_CONTROL_TRUE)
2010 vo_osd_teletext_mode=0;
2011 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_GET_FORMAT,&vo_osd_teletext_format)!=VBI_CONTROL_TRUE)
2012 vo_osd_teletext_format=0;
2013 vo_osd_changed(OSDTYPE_TELETEXT);
2015 teletext_control(demuxer->teletext,TV_VBI_CONTROL_MARK_UNCHANGED,NULL);
2018 static int check_framedrop(struct MPContext *mpctx, double frame_time) {
2019 struct MPOpts *opts = &mpctx->opts;
2020 // check for frame-drop:
2021 current_module = "check_framedrop";
2022 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
2023 static int dropped_frames;
2024 float delay = opts->playback_speed * ao_get_delay(mpctx->ao);
2025 float d = delay-mpctx->delay;
2026 ++total_frame_cnt;
2027 // we should avoid dropping too many frames in sequence unless we
2028 // are too late. and we allow 100ms A-V delay here:
2029 if (d < -dropped_frames*frame_time-0.100 && !mpctx->paused
2030 && !mpctx->restart_playback) {
2031 ++drop_frame_cnt;
2032 ++dropped_frames;
2033 return frame_dropping;
2034 } else
2035 dropped_frames = 0;
2037 return 0;
2041 #ifdef HAVE_RTC
2042 int rtc_fd = -1;
2043 #endif
2045 static float timing_sleep(struct MPContext *mpctx, float time_frame)
2047 #ifdef HAVE_RTC
2048 if (rtc_fd >= 0){
2049 // -------- RTC -----------
2050 current_module="sleep_rtc";
2051 while (time_frame > 0.000) {
2052 unsigned long rtc_ts;
2053 if (read(rtc_fd, &rtc_ts, sizeof(rtc_ts)) <= 0)
2054 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC read error: %s\n", strerror(errno));
2055 time_frame -= get_relative_time(mpctx);
2057 } else
2058 #endif
2060 // assume kernel HZ=100 for softsleep, works with larger HZ but with
2061 // unnecessarily high CPU usage
2062 struct MPOpts *opts = &mpctx->opts;
2063 float margin = opts->softsleep ? 0.011 : 0;
2064 current_module = "sleep_timer";
2065 while (time_frame > margin) {
2066 usec_sleep(1000000 * (time_frame - margin));
2067 time_frame -= get_relative_time(mpctx);
2069 if (opts->softsleep){
2070 current_module = "sleep_soft";
2071 if (time_frame < 0)
2072 mp_tmsg(MSGT_AVSYNC, MSGL_WARN, "Warning! Softsleep underflow!\n");
2073 while (time_frame > 0)
2074 time_frame -= get_relative_time(mpctx); // burn the CPU
2077 return time_frame;
2080 static int select_subtitle(MPContext *mpctx)
2082 struct MPOpts *opts = &mpctx->opts;
2083 // find the best sub to use
2084 int id;
2085 int found = 0;
2086 mpctx->global_sub_pos = -1; // no subs by default
2087 if (vobsub_id >= 0) {
2088 // if user asks for a vobsub id, use that first.
2089 id = vobsub_id;
2090 found = mp_property_do("sub_vob", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
2093 if (!found && opts->sub_id >= 0) {
2094 // if user asks for a dvd sub id, use that next.
2095 id = opts->sub_id;
2096 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
2099 if (!found) {
2100 // if there are text subs to use, use those. (autosubs come last here)
2101 id = 0;
2102 found = mp_property_do("sub_file", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
2105 if (!found && opts->sub_id == -1) {
2106 // finally select subs by language and container hints
2107 if (opts->sub_id == -1)
2108 opts->sub_id =
2109 demuxer_sub_track_by_lang_and_default(mpctx->d_sub->demuxer,
2110 opts->sub_lang);
2111 if (opts->sub_id >= 0) {
2112 id = opts->sub_id;
2113 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
2116 return found;
2119 #ifdef CONFIG_DVDNAV
2120 #ifndef FF_B_TYPE
2121 #define FF_B_TYPE 3
2122 #endif
2123 /// store decoded video image
2124 static mp_image_t * mp_dvdnav_copy_mpi(mp_image_t *to_mpi,
2125 mp_image_t *from_mpi) {
2126 mp_image_t *mpi;
2128 /// Do not store B-frames
2129 if (from_mpi->pict_type == FF_B_TYPE)
2130 return to_mpi;
2132 if (to_mpi &&
2133 to_mpi->w == from_mpi->w &&
2134 to_mpi->h == from_mpi->h &&
2135 to_mpi->imgfmt == from_mpi->imgfmt)
2136 mpi = to_mpi;
2137 else {
2138 if (to_mpi)
2139 free_mp_image(to_mpi);
2140 if (from_mpi->w == 0 || from_mpi->h == 0)
2141 return NULL;
2142 mpi = alloc_mpi(from_mpi->w,from_mpi->h,from_mpi->imgfmt);
2145 copy_mpi(mpi,from_mpi);
2146 return mpi;
2149 static void mp_dvdnav_reset_stream (MPContext *ctx) {
2150 struct MPOpts *opts = &ctx->opts;
2151 if (ctx->sh_video) {
2152 /// clear video pts
2153 ctx->d_video->pts = 0.0f;
2154 ctx->sh_video->pts = 0.0f;
2155 ctx->sh_video->i_pts = 0.0f;
2156 ctx->sh_video->last_pts = 0.0f;
2157 ctx->sh_video->num_buffered_pts = 0;
2158 ctx->sh_video->num_frames = 0;
2159 ctx->sh_video->num_frames_decoded = 0;
2160 ctx->sh_video->timer = 0.0f;
2161 ctx->sh_video->stream_delay = 0.0f;
2162 ctx->sh_video->timer = 0;
2163 ctx->demuxer->stream_pts = MP_NOPTS_VALUE;
2166 if (ctx->sh_audio) {
2167 /// free audio packets and reset
2168 ds_free_packs(ctx->d_audio);
2169 audio_delay -= ctx->sh_audio->stream_delay;
2170 ctx->delay =- audio_delay;
2171 ao_reset(ctx->ao);
2172 resync_audio_stream(ctx->sh_audio);
2175 audio_delay = 0.0f;
2176 ctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(ctx->stream);
2177 if (opts->sub_lang && opts->sub_id == dvdsub_lang_id) {
2178 dvdsub_lang_id = mp_dvdnav_sid_from_lang(ctx->stream, opts->sub_lang);
2179 if (dvdsub_lang_id != opts->sub_id) {
2180 opts->sub_id = dvdsub_lang_id;
2181 select_subtitle(ctx);
2185 /// clear all EOF related flags
2186 ctx->d_video->eof = ctx->d_audio->eof = ctx->stream->eof = 0;
2189 /// Restore last decoded DVDNAV (still frame)
2190 static mp_image_t *mp_dvdnav_restore_smpi(struct MPContext *mpctx,
2191 int *in_size,
2192 unsigned char **start,
2193 mp_image_t *decoded_frame)
2195 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2196 return decoded_frame;
2198 /// a change occured in dvdnav stream
2199 if (mp_dvdnav_cell_has_changed(mpctx->stream,0)) {
2200 mp_dvdnav_read_wait(mpctx->stream, 1, 1);
2201 mp_dvdnav_context_free(mpctx);
2202 mp_dvdnav_reset_stream(mpctx);
2203 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
2204 mp_dvdnav_cell_has_changed(mpctx->stream,1);
2207 if (*in_size < 0) {
2208 float len;
2210 /// Display still frame, if any
2211 if (mpctx->nav_smpi && !mpctx->nav_buffer)
2212 decoded_frame = mpctx->nav_smpi;
2214 /// increment video frame : continue playing after still frame
2215 len = get_time_length(mpctx);
2216 if (mpctx->sh_video->pts >= len &&
2217 mpctx->sh_video->pts > 0.0 && len > 0.0) {
2218 mp_dvdnav_skip_still(mpctx->stream);
2219 mp_dvdnav_skip_wait(mpctx->stream);
2221 mpctx->sh_video->pts += 1 / mpctx->sh_video->fps;
2223 if (mpctx->nav_buffer) {
2224 *start = mpctx->nav_start;
2225 *in_size = mpctx->nav_in_size;
2226 if (mpctx->nav_start)
2227 memcpy(*start,mpctx->nav_buffer,mpctx->nav_in_size);
2231 return decoded_frame;
2234 /// Save last decoded DVDNAV (still frame)
2235 static void mp_dvdnav_save_smpi(struct MPContext *mpctx, int in_size,
2236 unsigned char *start,
2237 mp_image_t *decoded_frame)
2239 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2240 return;
2242 free(mpctx->nav_buffer);
2244 mpctx->nav_buffer = malloc(in_size);
2245 mpctx->nav_start = start;
2246 mpctx->nav_in_size = mpctx->nav_buffer ? in_size : -1;
2247 if (mpctx->nav_buffer)
2248 memcpy(mpctx->nav_buffer,start,in_size);
2250 if (decoded_frame && mpctx->nav_smpi != decoded_frame)
2251 mpctx->nav_smpi = mp_dvdnav_copy_mpi(mpctx->nav_smpi,decoded_frame);
2253 #endif /* CONFIG_DVDNAV */
2255 /* Modify video timing to match the audio timeline. There are two main
2256 * reasons this is needed. First, video and audio can start from different
2257 * positions at beginning of file or after a seek (MPlayer starts both
2258 * immediately even if they have different pts). Second, the file can have
2259 * audio timestamps that are inconsistent with the duration of the audio
2260 * packets, for example two consecutive timestamp values differing by
2261 * one second but only a packet with enough samples for half a second
2262 * of playback between them.
2264 static void adjust_sync(struct MPContext *mpctx, double frame_time)
2266 current_module = "av_sync";
2268 if (!mpctx->sh_audio || mpctx->syncing_audio)
2269 return;
2271 double a_pts = written_audio_pts(mpctx) - mpctx->delay;
2272 double v_pts = mpctx->sh_video->pts;
2273 double av_delay = a_pts - v_pts;
2274 // Try to sync vo_flip() so it will *finish* at given time
2275 av_delay += mpctx->last_vo_flip_duration;
2276 av_delay -= audio_delay; // This much pts difference is desired
2278 double change = av_delay * 0.1;
2279 double max_change = default_max_pts_correction >= 0 ?
2280 default_max_pts_correction : frame_time * 0.1;
2281 if (change < -max_change)
2282 change = -max_change;
2283 else if (change > max_change)
2284 change = max_change;
2285 mpctx->delay += change;
2286 mpctx->total_avsync_change += change;
2289 #define ASYNC_PLAY_DONE -3
2290 static int audio_start_sync(struct MPContext *mpctx, int playsize)
2292 struct ao *ao = mpctx->ao;
2293 struct MPOpts *opts = &mpctx->opts;
2294 sh_audio_t * const sh_audio = mpctx->sh_audio;
2295 int res;
2297 // Timing info may not be set without
2298 res = decode_audio(sh_audio, 1);
2299 if (res < 0)
2300 return res;
2302 int bytes;
2303 bool did_retry = false;
2304 while (1) {
2305 double written_pts = written_audio_pts(mpctx);
2306 double ptsdiff = written_pts - mpctx->video_pts - mpctx->delay
2307 - audio_delay;
2308 bytes = ptsdiff * ao->bps / mpctx->opts.playback_speed;
2309 bytes -= bytes % (ao->channels * af_fmt2bits(ao->format) / 8);
2311 // ogg demuxers give packets without timing
2312 if (written_pts <= 1 && sh_audio->pts == MP_NOPTS_VALUE) {
2313 if (!did_retry) {
2314 // Try to read more data to see packets that have pts
2315 int res = decode_audio(sh_audio, ao->bps);
2316 if (res < 0)
2317 return res;
2318 did_retry = true;
2319 continue;
2321 bytes = 0;
2324 if (fabs(ptsdiff) > 300) // pts reset or just broken?
2325 bytes = 0;
2327 if (bytes > 0)
2328 break;
2330 mpctx->syncing_audio = false;
2331 int a = FFMIN(-bytes, FFMAX(playsize, 20000));
2332 int res = decode_audio(sh_audio, a);
2333 bytes += sh_audio->a_out_buffer_len;
2334 if (bytes >= 0) {
2335 memmove(sh_audio->a_out_buffer,
2336 sh_audio->a_out_buffer +
2337 sh_audio->a_out_buffer_len - bytes,
2338 bytes);
2339 sh_audio->a_out_buffer_len = bytes;
2340 if (res < 0)
2341 return res;
2342 return decode_audio(sh_audio, playsize);
2344 sh_audio->a_out_buffer_len = 0;
2345 if (res < 0)
2346 return res;
2348 int fillbyte = 0;
2349 if ((ao->format & AF_FORMAT_SIGN_MASK) == AF_FORMAT_US)
2350 fillbyte = 0x80;
2351 if (bytes >= playsize) {
2352 /* This case could fall back to the one below with
2353 * bytes = playsize, but then silence would keep accumulating
2354 * in a_out_buffer if the AO accepts less data than it asks for
2355 * in playsize. */
2356 char *p = malloc(playsize);
2357 memset(p, fillbyte, playsize);
2358 playsize = ao_play(ao, p, playsize, 0);
2359 free(p);
2360 mpctx->delay += opts->playback_speed*playsize/(double)ao->bps;
2361 return ASYNC_PLAY_DONE;
2363 mpctx->syncing_audio = false;
2364 decode_audio_prepend_bytes(sh_audio, bytes, fillbyte);
2365 return decode_audio(sh_audio, playsize);
2368 static int fill_audio_out_buffers(struct MPContext *mpctx)
2370 struct MPOpts *opts = &mpctx->opts;
2371 struct ao *ao = mpctx->ao;
2372 unsigned int t;
2373 double tt;
2374 int playsize;
2375 int playflags=0;
2376 bool audio_eof = false;
2377 bool partial_fill = false;
2378 bool format_change = false;
2379 sh_audio_t * const sh_audio = mpctx->sh_audio;
2380 bool modifiable_audio_format = !(ao->format & AF_FORMAT_SPECIAL_MASK);
2381 int unitsize = ao->channels * af_fmt2bits(ao->format) / 8;
2383 current_module="play_audio";
2385 // all the current uses of ao->pts seem to be in aos that handle
2386 // sync completely wrong; there should be no need to use ao->pts
2387 // in get_space()
2388 ao->pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2389 playsize = ao_get_space(ao);
2391 // Fill buffer if needed:
2392 current_module="decode_audio";
2393 t = GetTimer();
2395 if (!opts->initial_audio_sync || !modifiable_audio_format)
2396 mpctx->syncing_audio = false;
2398 int res;
2399 if (mpctx->syncing_audio && mpctx->sh_video)
2400 res = audio_start_sync(mpctx, playsize);
2401 else
2402 res = decode_audio(sh_audio, playsize);
2403 if (res < 0) { // EOF, error or format change
2404 if (res == -2)
2405 format_change = true;
2406 else if (res == ASYNC_PLAY_DONE)
2407 return 0;
2408 else if (mpctx->d_audio->eof)
2409 audio_eof = true;
2411 t = GetTimer() - t;
2412 tt = t*0.000001f; audio_time_usage+=tt;
2413 if (mpctx->timeline && modifiable_audio_format) {
2414 double endpts = mpctx->timeline[mpctx->timeline_part + 1].start;
2415 double bytes = (endpts - written_audio_pts(mpctx) + audio_delay)
2416 * ao->bps / opts->playback_speed;
2417 if (playsize > bytes) {
2418 playsize = FFMAX(bytes, 0);
2419 playflags |= AOPLAY_FINAL_CHUNK;
2420 audio_eof = true;
2421 partial_fill = true;
2425 if (playsize > sh_audio->a_out_buffer_len) {
2426 partial_fill = true;
2427 playsize = sh_audio->a_out_buffer_len;
2428 if (audio_eof)
2429 playflags |= AOPLAY_FINAL_CHUNK;
2431 playsize -= playsize % unitsize;
2432 if (!playsize)
2433 return partial_fill && audio_eof ? -2 : -partial_fill;
2435 // play audio:
2436 current_module="play_audio";
2438 // Is this pts value actually useful for the aos that access it?
2439 // They're obviously badly broken in the way they handle av sync;
2440 // would not having access to this make them more broken?
2441 ao->pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2442 playsize = ao_play(ao, sh_audio->a_out_buffer, playsize, playflags);
2444 if (playsize > 0) {
2445 sh_audio->a_out_buffer_len -= playsize;
2446 memmove(sh_audio->a_out_buffer, &sh_audio->a_out_buffer[playsize],
2447 sh_audio->a_out_buffer_len);
2448 mpctx->delay += opts->playback_speed*playsize/(double)ao->bps;
2449 } else if (audio_eof && ao_get_delay(ao) < .04) {
2450 // Sanity check to avoid hanging in case current ao doesn't output
2451 // partial chunks and doesn't check for AOPLAY_FINAL_CHUNK
2452 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Audio output truncated at end.\n");
2453 sh_audio->a_out_buffer_len = 0;
2456 /* The format change isn't handled too gracefully. A more precise
2457 * implementation would require draining buffered old-format audio
2458 * while displaying video, then doing the output format switch.
2460 if (format_change) {
2461 uninit_player(mpctx, INITIALIZED_AO);
2462 reinit_audio_chain(mpctx);
2463 return -1;
2466 return -partial_fill;
2469 static int sleep_until_near_frame(struct MPContext *mpctx, float *time_frame,
2470 bool sync_to_audio, float *aq_sleep_time)
2472 struct MPOpts *opts = &mpctx->opts;
2473 double audio_limit = 2;
2474 current_module="calc_sleep_time";
2476 if (mpctx->restart_playback)
2477 return 0;
2479 *time_frame -= get_relative_time(mpctx); // reset timer
2481 if (sync_to_audio) {
2482 float delay = ao_get_delay(mpctx->ao);
2483 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "delay=%f\n", delay);
2485 if (opts->autosync) {
2487 * Adjust this raw delay value by calculating the expected
2488 * delay for this frame and generating a new value which is
2489 * weighted between the two. The higher autosync is, the
2490 * closer to the delay value gets to that which "-nosound"
2491 * would have used, and the longer it will take for A/V
2492 * sync to settle at the right value (but it eventually will.)
2493 * This settling time is very short for values below 100.
2495 float predicted = mpctx->delay / opts->playback_speed + *time_frame;
2496 float difference = delay - predicted;
2497 delay = predicted + difference / (float)opts->autosync;
2500 *time_frame = delay - mpctx->delay / opts->playback_speed;
2502 // delay = amount of audio buffered in soundcard/driver
2503 delay = FFMIN(delay, 0.5);
2504 delay = FFMAX(delay, 0.1);
2505 audio_limit = delay;
2506 } else {
2507 // If we're lagging more than 200 ms behind the right playback rate,
2508 // don't try to "catch up".
2509 // If benchmark is set always output frames as fast as possible
2510 // without sleeping.
2511 if (*time_frame < -0.2 || opts->benchmark)
2512 *time_frame = 0;
2515 double t = *time_frame - mpctx->video_out->flip_queue_offset;
2517 if (t <= 0.05)
2518 return 0;
2520 t -= 0.05;
2521 if (t > audio_limit * 0.6)
2522 t = audio_limit * 0.5;
2523 *aq_sleep_time += t;
2524 mp_input_get_cmd(mpctx->input, t * 1000 + 1, 1);
2525 return 1;
2528 int reinit_video_chain(struct MPContext *mpctx)
2530 struct MPOpts *opts = &mpctx->opts;
2531 sh_video_t * const sh_video = mpctx->sh_video;
2532 if (!sh_video)
2533 return 0;
2534 double ar=-1.0;
2535 //================== Init VIDEO (codec & libvo) ==========================
2536 if (!opts->fixed_vo || !(mpctx->initialized_flags & INITIALIZED_VO)) {
2537 current_module="preinit_libvo";
2539 //shouldn't we set dvideo->id=-2 when we fail?
2540 //if((mpctx->video_out->preinit(vo_subdevice))!=0){
2541 if(!(mpctx->video_out=init_best_video_out(opts, mpctx->x11_state, mpctx->key_fifo, mpctx->input))){
2542 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Error opening/initializing the selected video_out (-vo) device.\n");
2543 goto err_out;
2545 mpctx->initialized_flags|=INITIALIZED_VO;
2548 if(stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_ASPECT_RATIO, &ar) != STREAM_UNSUPPORTED)
2549 mpctx->sh_video->stream_aspect = ar;
2550 current_module="init_video_filters";
2552 char* vf_arg[] = { "_oldargs_", (char*)mpctx->video_out , NULL };
2553 sh_video->vfilter = vf_open_filter(opts, NULL,"vo",vf_arg);
2555 #ifdef CONFIG_MENU
2556 if(use_menu) {
2557 char* vf_arg[] = { "_oldargs_", menu_root, NULL };
2558 vf_menu = vf_open_plugin(opts,libmenu_vfs,sh_video->vfilter,"menu",vf_arg);
2559 if(!vf_menu) {
2560 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Can't open libmenu video filter with root menu %s.\n",menu_root);
2561 use_menu = 0;
2564 if(vf_menu)
2565 sh_video->vfilter = vf_menu;
2566 #endif
2568 #ifdef CONFIG_ASS
2569 if(opts->ass_enabled) {
2570 int i;
2571 int insert = 1;
2572 if (opts->vf_settings)
2573 for (i = 0; opts->vf_settings[i].name; ++i)
2574 if (strcmp(opts->vf_settings[i].name, "ass") == 0) {
2575 insert = 0;
2576 break;
2578 if (insert) {
2579 extern vf_info_t vf_info_ass;
2580 const vf_info_t* libass_vfs[] = {&vf_info_ass, NULL};
2581 char* vf_arg[] = {"auto", "1", NULL};
2582 int retcode = 0;
2583 struct vf_instance *vf_ass = vf_open_plugin_noerr(opts, libass_vfs,
2584 sh_video->vfilter,
2585 "ass", vf_arg,
2586 &retcode);
2587 if (vf_ass)
2588 sh_video->vfilter = vf_ass;
2589 else if (retcode == -1) // vf_ass open() returns -1 if there's VO EOSD
2590 mp_msg(MSGT_CPLAYER, MSGL_V, "[ass] vf_ass not needed\n");
2591 else
2592 mp_msg(MSGT_CPLAYER,MSGL_ERR, "ASS: cannot add video filter\n");
2595 #endif
2597 sh_video->vfilter = append_filters(sh_video->vfilter, opts->vf_settings);
2599 #ifdef CONFIG_ASS
2600 if (opts->ass_enabled)
2601 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_INIT_EOSD, ass_library);
2602 #endif
2604 current_module="init_video_codec";
2606 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2607 init_best_video_codec(sh_video,video_codec_list,video_fm_list);
2608 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2610 if(!sh_video->initialized){
2611 if(!opts->fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
2612 goto err_out;
2615 mpctx->initialized_flags|=INITIALIZED_VCODEC;
2617 if (sh_video->codec)
2618 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODEC=%s\n", sh_video->codec->name);
2620 sh_video->last_pts = MP_NOPTS_VALUE;
2621 sh_video->num_buffered_pts = 0;
2622 sh_video->next_frame_time = 0;
2624 if (opts->auto_quality > 0) {
2625 // Auto quality option enabled
2626 output_quality=get_video_quality_max(sh_video);
2627 if (opts->auto_quality > output_quality)
2628 opts->auto_quality = output_quality;
2629 else
2630 output_quality = opts->auto_quality;
2631 mp_msg(MSGT_CPLAYER,MSGL_V,"AutoQ: setting quality to %d.\n",output_quality);
2632 set_video_quality(sh_video,output_quality);
2635 // ========== Init display (sh_video->disp_w*sh_video->disp_h/out_fmt) ============
2637 current_module="init_vo";
2639 return 1;
2641 err_out:
2642 mpctx->sh_video = mpctx->d_video->sh = NULL;
2643 return 0;
2646 static double update_video_nocorrect_pts(struct MPContext *mpctx)
2648 struct sh_video *sh_video = mpctx->sh_video;
2649 double frame_time = 0;
2650 struct vo *video_out = mpctx->video_out;
2651 while (1) {
2652 current_module = "filter_video";
2653 // In nocorrect-pts mode there is no way to properly time these frames
2654 if (vo_get_buffered_frame(video_out, 0) >= 0)
2655 break;
2656 if (vf_output_queued_frame(sh_video->vfilter))
2657 break;
2658 unsigned char *packet = NULL;
2659 frame_time = sh_video->next_frame_time;
2660 if (mpctx->restart_playback)
2661 frame_time = 0;
2662 int in_size = video_read_frame(sh_video, &sh_video->next_frame_time,
2663 &packet, force_fps);
2664 if (in_size < 0) {
2665 #ifdef CONFIG_DVDNAV
2666 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
2667 if (mp_dvdnav_is_eof(mpctx->stream))
2668 return -1;
2669 if (mpctx->d_video)
2670 mpctx->d_video->eof = 0;
2671 if (mpctx->d_audio)
2672 mpctx->d_audio->eof = 0;
2673 mpctx->stream->eof = 0;
2674 } else
2675 #endif
2676 return -1;
2678 if (in_size > max_framesize)
2679 max_framesize = in_size;
2680 sh_video->timer += frame_time;
2681 if (mpctx->sh_audio)
2682 mpctx->delay -= frame_time;
2683 // video_read_frame can change fps (e.g. for ASF video)
2684 vo_fps = sh_video->fps;
2685 int framedrop_type = check_framedrop(mpctx, frame_time);
2686 current_module = "decode video";
2688 void *decoded_frame;
2689 #ifdef CONFIG_DVDNAV
2690 decoded_frame = mp_dvdnav_restore_smpi(mpctx, &in_size, &packet, NULL);
2691 if (in_size >= 0 && !decoded_frame)
2692 #endif
2693 decoded_frame = decode_video(sh_video, packet, in_size, framedrop_type,
2694 sh_video->pts);
2695 #ifdef CONFIG_DVDNAV
2696 // Save last still frame for future display
2697 mp_dvdnav_save_smpi(mpctx, in_size, packet, decoded_frame);
2698 #endif
2699 if (decoded_frame) {
2700 current_module = "filter video";
2701 filter_video(sh_video, decoded_frame, sh_video->pts);
2703 break;
2705 return frame_time;
2708 static void determine_frame_pts(struct MPContext *mpctx)
2710 struct sh_video *sh_video = mpctx->sh_video;
2711 struct MPOpts *opts = &mpctx->opts;
2713 if (opts->user_pts_assoc_mode) {
2714 sh_video->pts_assoc_mode = opts->user_pts_assoc_mode;
2715 } else if (sh_video->pts_assoc_mode == 0) {
2716 if (mpctx->d_video->demuxer->timestamp_type == TIMESTAMP_TYPE_PTS
2717 && sh_video->codec_reordered_pts != MP_NOPTS_VALUE)
2718 sh_video->pts_assoc_mode = 1;
2719 else
2720 sh_video->pts_assoc_mode = 2;
2721 } else {
2722 int probcount1 = sh_video->num_reordered_pts_problems;
2723 int probcount2 = sh_video->num_sorted_pts_problems;
2724 if (sh_video->pts_assoc_mode == 2) {
2725 int tmp = probcount1;
2726 probcount1 = probcount2;
2727 probcount2 = tmp;
2729 if (probcount1 >= probcount2 * 1.5 + 2) {
2730 sh_video->pts_assoc_mode = 3 - sh_video->pts_assoc_mode;
2731 mp_msg(MSGT_CPLAYER, MSGL_V, "Switching to pts association mode "
2732 "%d.\n", sh_video->pts_assoc_mode);
2735 sh_video->pts = sh_video->pts_assoc_mode == 1 ?
2736 sh_video->codec_reordered_pts : sh_video->sorted_pts;
2739 static double update_video(struct MPContext *mpctx)
2741 struct sh_video *sh_video = mpctx->sh_video;
2742 struct vo *video_out = mpctx->video_out;
2743 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_SET_OSD_OBJ,
2744 mpctx->osd); // hack for vf_expand
2745 if (!mpctx->opts.correct_pts)
2746 return update_video_nocorrect_pts(mpctx);
2748 double pts;
2750 while (1) {
2751 current_module = "filter_video";
2752 if (!mpctx->hrseek_active
2753 && vo_get_buffered_frame(video_out, false) >= 0)
2754 break;
2755 // XXX Time used in this call is not counted in any performance
2756 // timer now
2757 if (vf_output_queued_frame(sh_video->vfilter))
2758 break;
2759 unsigned char *packet = NULL;
2760 int in_size = ds_get_packet_pts(mpctx->d_video, &packet, &pts);
2761 if (pts != MP_NOPTS_VALUE)
2762 pts += mpctx->video_offset;
2763 bool hit_eof = false;
2764 if (in_size < 0) {
2765 // try to extract last frames in case of decoder lag
2766 in_size = 0;
2767 pts = MP_NOPTS_VALUE;
2768 hit_eof = true;
2770 if (in_size > max_framesize)
2771 max_framesize = in_size;
2772 current_module = "decode video";
2773 if (pts >= mpctx->hrseek_pts - .005)
2774 mpctx->hrseek_framedrop = false;
2775 int framedrop_type = mpctx->hrseek_framedrop ? 1 :
2776 check_framedrop(mpctx, sh_video->frametime);
2777 void *decoded_frame = decode_video(sh_video, packet, in_size,
2778 framedrop_type, pts);
2779 if (decoded_frame) {
2780 determine_frame_pts(mpctx);
2781 current_module = "filter video";
2782 filter_video(sh_video, decoded_frame, sh_video->pts);
2783 } else if (hit_eof) {
2784 if (vo_get_buffered_frame(video_out, true) < 0)
2785 return -1;
2787 break;
2790 if (!video_out->frame_loaded)
2791 return 0;
2793 pts = video_out->next_pts;
2794 if (pts == MP_NOPTS_VALUE) {
2795 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Video pts after filters MISSING\n");
2796 // Try to use decoder pts from before filters
2797 pts = sh_video->pts;
2798 if (pts == MP_NOPTS_VALUE)
2799 pts = sh_video->last_pts;
2801 if (mpctx->hrseek_active && pts < mpctx->hrseek_pts - .005) {
2802 vo_skip_frame(video_out);
2803 return 0;
2805 mpctx->hrseek_active = false;
2806 sh_video->pts = pts;
2807 if (sh_video->last_pts == MP_NOPTS_VALUE)
2808 sh_video->last_pts = sh_video->pts;
2809 else if (sh_video->last_pts > sh_video->pts) {
2810 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Decreasing video pts: %f < %f\n",
2811 sh_video->pts, sh_video->last_pts);
2812 /* If the difference in pts is small treat it as jitter around the
2813 * right value (possibly caused by incorrect timestamp ordering) and
2814 * just show this frame immediately after the last one.
2815 * Treat bigger differences as timestamp resets and start counting
2816 * timing of later frames from the position of this one. */
2817 if (sh_video->last_pts - sh_video->pts > 0.5)
2818 sh_video->last_pts = sh_video->pts;
2819 else
2820 sh_video->pts = sh_video->last_pts;
2822 double frame_time = sh_video->pts - sh_video->last_pts;
2823 sh_video->last_pts = sh_video->pts;
2824 sh_video->timer += frame_time;
2825 if (mpctx->sh_audio)
2826 mpctx->delay -= frame_time;
2827 return frame_time;
2830 void pause_player(struct MPContext *mpctx)
2832 if (mpctx->paused)
2833 return;
2834 mpctx->paused = 1;
2835 mpctx->step_frames = 0;
2836 mpctx->time_frame -= get_relative_time(mpctx);
2838 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2839 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2841 if (mpctx->ao && mpctx->sh_audio)
2842 ao_pause(mpctx->ao); // pause audio, keep data if possible
2845 void unpause_player(struct MPContext *mpctx)
2847 if (!mpctx->paused)
2848 return;
2849 mpctx->paused = 0;
2851 if (mpctx->ao && mpctx->sh_audio)
2852 ao_resume(mpctx->ao);
2853 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok
2854 && !mpctx->step_frames)
2855 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL); // resume video
2856 (void)get_relative_time(mpctx); // ignore time that passed during pause
2859 void add_step_frame(struct MPContext *mpctx)
2861 mpctx->step_frames++;
2862 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2863 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2864 unpause_player(mpctx);
2867 static void pause_loop(struct MPContext *mpctx)
2869 struct MPOpts *opts = &mpctx->opts;
2870 mp_cmd_t* cmd;
2871 #ifdef CONFIG_STREAM_CACHE
2872 int old_cache_fill = stream_cache_size > 0 ?
2873 cache_fill_status(mpctx->stream) : 0;
2874 #endif
2875 if (!opts->quiet) {
2876 if (opts->term_osd && !mpctx->sh_video) {
2877 set_osd_tmsg(OSD_MSG_PAUSE, 1, 0, " ===== PAUSE =====");
2878 update_osd_msg(mpctx);
2879 } else
2880 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "\n%s\r",
2881 mp_gtext(" ===== PAUSE ====="));
2882 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_PAUSED\n");
2885 while ( (cmd = mp_input_get_cmd(mpctx->input, 20, 1)) == NULL
2886 || cmd->id == MP_CMD_SET_MOUSE_POS || cmd->pausing == 4) {
2887 if (cmd) {
2888 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
2889 run_command(mpctx, cmd);
2890 mp_cmd_free(cmd);
2891 continue;
2893 if (mpctx->sh_video && mpctx->video_out)
2894 vo_check_events(mpctx->video_out);
2895 #ifdef CONFIG_MENU
2896 if (vf_menu)
2897 vf_menu_pause_update(vf_menu);
2898 #endif
2899 usec_sleep(20000);
2900 update_osd_msg(mpctx);
2901 int hack = vo_osd_changed(0);
2902 vo_osd_changed(hack);
2903 if (hack)
2904 break;
2905 #ifdef CONFIG_STREAM_CACHE
2906 if (!opts->quiet && stream_cache_size > 0) {
2907 int new_cache_fill = cache_fill_status(mpctx->stream);
2908 if (new_cache_fill != old_cache_fill) {
2909 if (opts->term_osd && !mpctx->sh_video) {
2910 set_osd_tmsg(OSD_MSG_PAUSE, 1, 0, "%s %d%%",
2911 mp_gtext(" ===== PAUSE ====="),
2912 new_cache_fill);
2913 update_osd_msg(mpctx);
2914 } else
2915 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "%s %d%%\r",
2916 mp_gtext(" ===== PAUSE ====="),
2917 new_cache_fill);
2918 old_cache_fill = new_cache_fill;
2921 #endif
2926 // Find the right mute status and record position for new file position
2927 static void edl_seek_reset(MPContext *mpctx)
2929 mpctx->edl_muted = 0;
2930 next_edl_record = edl_records;
2932 while (next_edl_record) {
2933 if (next_edl_record->start_sec >= get_current_time(mpctx))
2934 break;
2936 if (next_edl_record->action == EDL_MUTE)
2937 mpctx->edl_muted = !mpctx->edl_muted;
2938 next_edl_record = next_edl_record->next;
2940 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2941 mixer_mute(&mpctx->mixer);
2945 // Execute EDL command for the current position if one exists
2946 static void edl_update(MPContext *mpctx)
2948 if (!next_edl_record)
2949 return;
2951 if (!mpctx->sh_video) {
2952 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot use EDL without video, disabling.\n");
2953 free_edl(edl_records);
2954 next_edl_record = NULL;
2955 edl_records = NULL;
2956 return;
2959 if (get_current_time(mpctx) >= next_edl_record->start_sec) {
2960 if (next_edl_record->action == EDL_SKIP) {
2961 mpctx->osd_function = OSD_FFW;
2962 queue_seek(mpctx, MPSEEK_RELATIVE, next_edl_record->length_sec, 0);
2963 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_SKIP: start [%f], stop "
2964 "[%f], length [%f]\n", next_edl_record->start_sec,
2965 next_edl_record->stop_sec, next_edl_record->length_sec);
2967 else if (next_edl_record->action == EDL_MUTE) {
2968 mpctx->edl_muted = !mpctx->edl_muted;
2969 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2970 mixer_mute(&mpctx->mixer);
2971 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_MUTE: [%f]\n",
2972 next_edl_record->start_sec );
2974 next_edl_record = next_edl_record->next;
2978 static void reinit_decoders(struct MPContext *mpctx)
2980 reinit_video_chain(mpctx);
2981 reinit_audio_chain(mpctx);
2982 mp_property_do("sub", M_PROPERTY_SET, &(int){mpctx->global_sub_pos}, mpctx);
2985 static void seek_reset(struct MPContext *mpctx, bool reset_ao)
2987 if (mpctx->sh_video) {
2988 current_module = "seek_video_reset";
2989 resync_video_stream(mpctx->sh_video);
2990 mpctx->sh_video->timer = 0;
2991 vo_seek_reset(mpctx->video_out);
2992 mpctx->sh_video->timer = 0;
2993 mpctx->sh_video->num_buffered_pts = 0;
2994 mpctx->sh_video->last_pts = MP_NOPTS_VALUE;
2995 mpctx->delay = 0;
2996 mpctx->time_frame = 0;
2997 mpctx->restart_playback = true;
2998 // Not all demuxers set d_video->pts during seek, so this value
2999 // (which is used by at least vobsub and edl code below) may
3000 // be completely wrong (probably 0).
3001 mpctx->sh_video->pts = mpctx->d_video->pts + mpctx->video_offset;
3002 mpctx->video_pts = mpctx->sh_video->pts;
3003 update_subtitles(mpctx, mpctx->sh_video->pts, mpctx->video_offset,
3004 true);
3005 update_teletext(mpctx->sh_video, mpctx->demuxer, 1);
3008 if (mpctx->sh_audio) {
3009 current_module = "seek_audio_reset";
3010 resync_audio_stream(mpctx->sh_audio);
3011 if (reset_ao)
3012 // stop audio, throwing away buffered data
3013 ao_reset(mpctx->ao);
3014 mpctx->sh_audio->a_buffer_len = 0;
3015 mpctx->sh_audio->a_out_buffer_len = 0;
3016 if (!mpctx->sh_video)
3017 update_subtitles(mpctx, mpctx->sh_audio->pts,
3018 mpctx->video_offset, true);
3021 if (vo_vobsub && mpctx->sh_video) {
3022 current_module = "seek_vobsub_reset";
3023 vobsub_seek(vo_vobsub, mpctx->sh_video->pts);
3026 edl_seek_reset(mpctx);
3028 mpctx->hrseek_active = false;
3029 mpctx->hrseek_framedrop = false;
3030 mpctx->total_avsync_change = 0;
3031 audio_time_usage = 0; video_time_usage = 0; vout_time_usage = 0;
3032 drop_frame_cnt = 0;
3034 current_module = NULL;
3037 static bool timeline_set_part(struct MPContext *mpctx, int i)
3039 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
3040 struct timeline_part *n = mpctx->timeline + i;
3041 mpctx->timeline_part = i;
3042 mpctx->video_offset = n->start - n->source_start;
3043 if (n->source == p->source)
3044 return false;
3045 enum stop_play_reason orig_stop_play = mpctx->stop_play;
3046 if (!mpctx->sh_video && mpctx->stop_play == KEEP_PLAYING)
3047 mpctx->stop_play = AT_END_OF_FILE; // let audio uninit drain data
3048 uninit_player(mpctx, INITIALIZED_VCODEC | (mpctx->opts.fixed_vo ? 0 : INITIALIZED_VO) | (mpctx->opts.gapless_audio ? 0 : INITIALIZED_AO) | INITIALIZED_ACODEC | INITIALIZED_SUB);
3049 mpctx->stop_play = orig_stop_play;
3050 mpctx->demuxer = n->source->demuxer;
3051 mpctx->d_video = mpctx->demuxer->video;
3052 mpctx->d_audio = mpctx->demuxer->audio;
3053 mpctx->d_sub = mpctx->demuxer->sub;
3054 mpctx->sh_video = mpctx->d_video->sh;
3055 mpctx->sh_audio = mpctx->d_audio->sh;
3056 return true;
3059 // Given pts, switch playback to the corresponding part.
3060 // Return offset within that part.
3061 static double timeline_set_from_time(struct MPContext *mpctx, double pts,
3062 bool *need_reset)
3064 if (pts < 0)
3065 pts = 0;
3066 for (int i = 0; i < mpctx->num_timeline_parts; i++) {
3067 struct timeline_part *p = mpctx->timeline + i;
3068 if (pts < (p+1)->start) {
3069 *need_reset = timeline_set_part(mpctx, i);
3070 return pts - p->start + p->source_start;
3073 return -1;
3077 // return -1 if seek failed (non-seekable stream?), 0 otherwise
3078 static int seek(MPContext *mpctx, struct seek_params seek,
3079 bool timeline_fallthrough)
3081 struct MPOpts *opts = &mpctx->opts;
3083 current_module = "seek";
3084 if (mpctx->stop_play == AT_END_OF_FILE)
3085 mpctx->stop_play = KEEP_PLAYING;
3086 bool hr_seek = mpctx->demuxer->accurate_seek && opts->correct_pts;
3087 hr_seek &= seek.exact >= 0 && seek.type != MPSEEK_FACTOR;
3088 hr_seek &= opts->hr_seek == 0 && seek.type == MPSEEK_ABSOLUTE
3089 || opts->hr_seek > 0 || seek.exact > 0;
3090 if (seek.type == MPSEEK_FACTOR
3091 || seek.type == MPSEEK_ABSOLUTE
3092 && seek.amount < mpctx->last_chapter_pts
3093 || seek.amount < 0)
3094 mpctx->last_chapter_seek = -1;
3095 if (mpctx->timeline && seek.type == MPSEEK_FACTOR) {
3096 seek.amount *= mpctx->timeline[mpctx->num_timeline_parts].start;
3097 seek.type = MPSEEK_ABSOLUTE;
3099 if ((mpctx->demuxer->accurate_seek || mpctx->timeline)
3100 && seek.type == MPSEEK_RELATIVE) {
3101 seek.type = MPSEEK_ABSOLUTE;
3102 seek.direction = seek.amount > 0 ? 1 : -1;
3103 seek.amount += get_current_time(mpctx);
3106 /* At least the liba52 decoder wants to read from the input stream
3107 * during initialization, so reinit must be done after the demux_seek()
3108 * call that clears possible stream EOF. */
3109 bool need_reset = false;
3110 double demuxer_amount = seek.amount;
3111 if (mpctx->timeline) {
3112 demuxer_amount = timeline_set_from_time(mpctx, seek.amount,
3113 &need_reset);
3114 if (demuxer_amount == -1) {
3115 mpctx->stop_play = AT_END_OF_FILE;
3116 // Clear audio from current position
3117 if (mpctx->sh_audio) {
3118 ao_reset(mpctx->ao);
3119 mpctx->sh_audio->a_buffer_len = 0;
3120 mpctx->sh_audio->a_out_buffer_len = 0;
3122 return -1;
3125 int demuxer_style = 0;
3126 switch (seek.type) {
3127 case MPSEEK_FACTOR:
3128 demuxer_style |= SEEK_FACTOR; // fallthrough
3129 case MPSEEK_ABSOLUTE:
3130 demuxer_style |= SEEK_ABSOLUTE;
3132 if (hr_seek || seek.direction < 0)
3133 demuxer_style |= SEEK_BACKWARD;
3134 else if (seek.direction > 0)
3135 demuxer_style |= SEEK_FORWARD;
3137 int seekresult = demux_seek(mpctx->demuxer, demuxer_amount, audio_delay,
3138 demuxer_style);
3139 if (need_reset)
3140 reinit_decoders(mpctx);
3141 if (seekresult == 0)
3142 return -1;
3144 seek_reset(mpctx, !timeline_fallthrough);
3146 /* Use the target time as "current position" for further relative
3147 * seeks etc until a new video frame has been decoded */
3148 if (seek.type == MPSEEK_ABSOLUTE)
3149 mpctx->video_pts = seek.amount;
3151 if (hr_seek) {
3152 mpctx->hrseek_active = true;
3153 mpctx->hrseek_framedrop = true;
3154 mpctx->hrseek_pts = seek.amount;
3157 mpctx->start_timestamp = GetTimerMS();
3159 return 0;
3162 void queue_seek(struct MPContext *mpctx, enum seek_type type, double amount,
3163 int exact)
3165 struct seek_params *seek = &mpctx->seek;
3166 switch (type) {
3167 case MPSEEK_RELATIVE:
3168 if (seek->type == MPSEEK_FACTOR)
3169 return; // Well... not common enough to bother doing better
3170 seek->amount += amount;
3171 seek->exact = FFMAX(seek->exact, exact);
3172 if (seek->type == MPSEEK_NONE)
3173 seek->exact = exact;
3174 if (seek->type == MPSEEK_ABSOLUTE)
3175 return;
3176 if (seek->amount == 0) {
3177 *seek = (struct seek_params){0};
3178 return;
3180 seek->type = MPSEEK_RELATIVE;
3181 return;
3182 case MPSEEK_ABSOLUTE:
3183 case MPSEEK_FACTOR:
3184 *seek = (struct seek_params) {
3185 .type = type,
3186 .amount = amount,
3187 .exact = exact,
3189 return;
3190 case MPSEEK_NONE:
3191 *seek = (struct seek_params){0};
3192 return;
3194 abort();
3198 double get_time_length(struct MPContext *mpctx)
3200 if (mpctx->timeline)
3201 return mpctx->timeline[mpctx->num_timeline_parts].start;
3203 struct demuxer *demuxer = mpctx->demuxer;
3204 double get_time_ans;
3205 // <= 0 means DEMUXER_CTRL_NOTIMPL or DEMUXER_CTRL_DONTKNOW
3206 if (demux_control(demuxer, DEMUXER_CTRL_GET_TIME_LENGTH,
3207 (void *) &get_time_ans) > 0)
3208 return get_time_ans;
3210 struct sh_video *sh_video = mpctx->d_video->sh;
3211 struct sh_audio *sh_audio = mpctx->d_audio->sh;
3212 if (sh_video && sh_video->i_bps && sh_audio && sh_audio->i_bps)
3213 return (double) (demuxer->movi_end - demuxer->movi_start) /
3214 (sh_video->i_bps + sh_audio->i_bps);
3215 if (sh_video && sh_video->i_bps)
3216 return (double) (demuxer->movi_end - demuxer->movi_start) /
3217 sh_video->i_bps;
3218 if (sh_audio && sh_audio->i_bps)
3219 return (double) (demuxer->movi_end - demuxer->movi_start) /
3220 sh_audio->i_bps;
3221 return 0;
3224 /* If there are timestamps from stream level then use those (for example
3225 * DVDs can have consistent times there while the MPEG-level timestamps
3226 * reset). */
3227 double get_current_time(struct MPContext *mpctx)
3229 struct demuxer *demuxer = mpctx->demuxer;
3230 if (demuxer->stream_pts != MP_NOPTS_VALUE)
3231 return demuxer->stream_pts;
3232 struct sh_video *sh_video = demuxer->video->sh;
3233 if (sh_video)
3234 return mpctx->video_pts;
3235 return playing_audio_pts(mpctx);
3238 int get_percent_pos(struct MPContext *mpctx)
3240 struct demuxer *demuxer = mpctx->demuxer;
3241 int ans = 0;
3242 if (mpctx->timeline)
3243 ans = get_current_time(mpctx) * 100 /
3244 mpctx->timeline[mpctx->num_timeline_parts].start;
3245 else if (demux_control(demuxer, DEMUXER_CTRL_GET_PERCENT_POS, &ans) > 0)
3247 else {
3248 int len = (demuxer->movi_end - demuxer->movi_start) / 100;
3249 off_t pos = demuxer->filepos > 0 ?
3250 demuxer->filepos : stream_tell(demuxer->stream);
3251 if (len > 0)
3252 ans = (pos - demuxer->movi_start) / len;
3253 else
3254 ans = 0;
3256 if (ans < 0)
3257 ans = 0;
3258 if (ans > 100)
3259 ans = 100;
3260 return ans;
3263 // -2 is no chapters, -1 is before first chapter
3264 int get_current_chapter(struct MPContext *mpctx)
3266 double current_pts = get_current_time(mpctx);
3267 if (!mpctx->chapters)
3268 return FFMAX(mpctx->last_chapter_seek,
3269 demuxer_get_current_chapter(mpctx->demuxer, current_pts));
3271 int i;
3272 for (i = 1; i < mpctx->num_chapters; i++)
3273 if (current_pts < mpctx->chapters[i].start)
3274 break;
3275 return FFMAX(mpctx->last_chapter_seek, i - 1);
3278 // currently returns a string allocated with malloc, not talloc
3279 char *chapter_display_name(struct MPContext *mpctx, int chapter)
3281 if (!mpctx->chapters || !mpctx->sh_video)
3282 return demuxer_chapter_display_name(mpctx->demuxer, chapter);
3283 return strdup(mpctx->chapters[chapter].name);
3286 int seek_chapter(struct MPContext *mpctx, int chapter, double *seek_pts,
3287 char **chapter_name)
3289 mpctx->last_chapter_seek = -1;
3290 if (!mpctx->chapters || !mpctx->sh_video) {
3291 int res = demuxer_seek_chapter(mpctx->demuxer, chapter, seek_pts,
3292 chapter_name);
3293 if (res >= 0) {
3294 if (*seek_pts == -1)
3295 seek_reset(mpctx, true);
3296 else {
3297 mpctx->last_chapter_seek = res;
3298 mpctx->last_chapter_pts = *seek_pts;
3301 return res;
3304 if (chapter >= mpctx->num_chapters)
3305 return -1;
3306 if (chapter < 0)
3307 chapter = 0;
3308 *seek_pts = mpctx->chapters[chapter].start;
3309 mpctx->last_chapter_seek = chapter;
3310 mpctx->last_chapter_pts = *seek_pts;
3311 if (chapter_name)
3312 *chapter_name = talloc_strdup(NULL, mpctx->chapters[chapter].name);
3313 return chapter;
3317 static void run_playloop(struct MPContext *mpctx)
3319 struct MPOpts *opts = &mpctx->opts;
3320 float aq_sleep_time = 0;
3321 bool full_audio_buffers = false;
3323 if (opts->chapterrange[1] > 0) {
3324 int cur_chapter = get_current_chapter(mpctx);
3325 if (cur_chapter!=-1 && cur_chapter + 1 > opts->chapterrange[1])
3326 mpctx->stop_play = PT_NEXT_ENTRY;
3329 if (!mpctx->sh_audio && mpctx->d_audio->sh) {
3330 mpctx->sh_audio = mpctx->d_audio->sh;
3331 mpctx->sh_audio->ds = mpctx->d_audio;
3332 reinit_audio_chain(mpctx);
3335 /*========================== PLAY AUDIO ============================*/
3337 if (mpctx->sh_audio && !mpctx->paused
3338 && (!mpctx->restart_playback || !mpctx->sh_video)) {
3339 int status = fill_audio_out_buffers(mpctx);
3340 full_audio_buffers = status >= 0;
3341 if (status == -2)
3342 // at eof, all audio at least written to ao
3343 if (!mpctx->sh_video)
3344 mpctx->stop_play = AT_END_OF_FILE;
3348 if (!mpctx->sh_video) {
3349 mpctx->restart_playback = false;
3350 if (mpctx->step_frames) {
3351 mpctx->step_frames = 0;
3352 pause_player(mpctx);
3354 // handle audio-only case:
3355 double a_pos = 0;
3356 // sh_audio can be NULL due to video stream switching
3357 // TODO: handle this better
3358 if (mpctx->sh_audio)
3359 a_pos = playing_audio_pts(mpctx);
3361 print_status(mpctx, a_pos, false);
3363 update_subtitles(mpctx, a_pos, mpctx->video_offset, false);
3364 update_osd_msg(mpctx);
3365 if (end_at.type == END_AT_TIME && end_at.pos < a_pos) {
3366 mpctx->stop_play = AT_END_OF_FILE;
3367 } else if (mpctx->timeline && mpctx->stop_play == AT_END_OF_FILE
3368 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts
3369 && mpctx->sh_audio) {
3370 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
3371 double delay = ao_get_delay(mpctx->ao);
3372 if (!opts->gapless_audio && p->source != (p+1)->source
3373 && delay > 0.05) {
3374 mpctx->stop_play = KEEP_PLAYING;
3375 mp_input_get_cmd(mpctx->input, (delay-.05) * 1000, true);
3376 } else {
3377 seek(mpctx, (struct seek_params){ .type = MPSEEK_ABSOLUTE,
3378 .amount = (p+1)->start },
3379 true);
3381 } else if (!mpctx->stop_play) {
3382 int sleep_time = full_audio_buffers || !mpctx->sh_audio ? 100 : 20;
3383 mp_input_get_cmd(mpctx->input, sleep_time, true);
3385 } else {
3387 /*========================== PLAY VIDEO ============================*/
3389 vo_pts = mpctx->sh_video->timer * 90000.0;
3390 vo_fps = mpctx->sh_video->fps;
3392 bool blit_frame = mpctx->video_out->frame_loaded;
3393 if (!blit_frame || mpctx->hrseek_active) {
3394 double frame_time = update_video(mpctx);
3395 blit_frame = mpctx->video_out->frame_loaded;
3396 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "*** ftime=%5.3f ***\n", frame_time);
3397 if (mpctx->sh_video->vf_initialized < 0) {
3398 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
3399 "\nFATAL: Could not initialize video filters (-vf) "
3400 "or video output (-vo).\n");
3401 mpctx->stop_play = PT_NEXT_ENTRY;
3402 return;
3404 if (frame_time < 0)
3405 mpctx->stop_play = AT_END_OF_FILE;
3406 else if (!mpctx->restart_playback) {
3407 mpctx->time_frame += frame_time / opts->playback_speed;
3408 adjust_sync(mpctx, frame_time);
3411 if (mpctx->timeline) {
3412 struct timeline_part *next =
3413 mpctx->timeline + mpctx->timeline_part + 1;
3414 if (mpctx->sh_video->pts >= next->start
3415 || mpctx->stop_play == AT_END_OF_FILE
3416 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts) {
3417 seek(mpctx, (struct seek_params){ .type = MPSEEK_ABSOLUTE,
3418 .amount = next->start },
3419 true);
3420 return;
3424 // ==========================================================================
3426 current_module = "vo_check_events";
3427 vo_check_events(mpctx->video_out);
3429 #ifdef CONFIG_X11
3430 if (stop_xscreensaver) {
3431 current_module = "stop_xscreensaver";
3432 xscreensaver_heartbeat(mpctx->x11_state);
3434 #endif
3435 if (heartbeat_cmd) {
3436 static unsigned last_heartbeat;
3437 unsigned now = GetTimerMS();
3438 if (now - last_heartbeat > 30000) {
3439 last_heartbeat = now;
3440 system(heartbeat_cmd);
3444 bool frame_time_remaining = sleep_until_near_frame(mpctx,
3445 &mpctx->time_frame,
3446 full_audio_buffers,
3447 &aq_sleep_time);
3449 //====================== FLIP PAGE (VIDEO BLT): =========================
3451 current_module = "flip_page";
3452 if (!frame_time_remaining && blit_frame) {
3453 struct sh_video *sh_video = mpctx->sh_video;
3454 mpctx->video_pts = sh_video->pts;
3455 update_subtitles(mpctx, sh_video->pts, mpctx->video_offset, false);
3456 update_teletext(sh_video, mpctx->demuxer, 0);
3457 update_osd_msg(mpctx);
3458 struct vf_instance *vf = sh_video->vfilter;
3459 vf->control(vf, VFCTRL_DRAW_EOSD, mpctx->osd);
3460 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
3461 vo_osd_changed(0);
3463 mpctx->time_frame -= mpctx->video_out->flip_queue_offset;
3464 aq_sleep_time += mpctx->time_frame;
3465 // flag 256 means: libvo driver does its timing (dvb card)
3466 if (mpctx->time_frame > 0.001
3467 && !(mpctx->sh_video->output_flags & VFCAP_TIMER))
3468 mpctx->time_frame = timing_sleep(mpctx, mpctx->time_frame);
3469 mpctx->time_frame += mpctx->video_out->flip_queue_offset;
3471 unsigned int t2 = GetTimer();
3472 /* Playing with playback speed it's possible to get pathological
3473 * cases with mpctx->time_frame negative enough to cause an
3474 * overflow in pts_us calculation, thus the FFMAX. */
3475 double time_frame = FFMAX(mpctx->time_frame, -1);
3476 unsigned int pts_us = mpctx->last_time + time_frame * 1e6;
3477 int duration = -1;
3478 double pts2 = mpctx->video_out->next_pts2;
3479 if (pts2 != MP_NOPTS_VALUE && opts->correct_pts
3480 && !mpctx->restart_playback) {
3481 // expected A/V sync correction is ignored
3482 double diff = (pts2 - mpctx->video_pts);
3483 diff /= opts->playback_speed;
3484 if (mpctx->time_frame < 0)
3485 diff += mpctx->time_frame;
3486 if (diff < 0)
3487 diff = 0;
3488 if (diff > 10)
3489 diff = 10;
3490 duration = diff * 1e6;
3492 vo_flip_page(mpctx->video_out, pts_us | 1, duration);
3494 mpctx->last_vo_flip_duration = (GetTimer() - t2) * 0.000001;
3495 vout_time_usage += mpctx->last_vo_flip_duration;
3496 if (mpctx->video_out->driver->flip_page_timed) {
3497 // No need to adjust sync based on flip speed
3498 mpctx->last_vo_flip_duration = 0;
3499 // For print_status - VO call finishing early is OK for sync
3500 mpctx->time_frame -= get_relative_time(mpctx);
3502 if (mpctx->restart_playback) {
3503 mpctx->syncing_audio = true;
3504 if (mpctx->sh_audio && !mpctx->paused)
3505 fill_audio_out_buffers(mpctx);
3506 mpctx->restart_playback = false;
3507 mpctx->time_frame = 0;
3508 get_relative_time(mpctx);
3510 print_status(mpctx, MP_NOPTS_VALUE, true);
3511 } else
3512 print_status(mpctx, MP_NOPTS_VALUE, false);
3514 //============================ Auto QUALITY ============================
3516 /*Output quality adjustments:*/
3517 if (opts->auto_quality > 0) {
3518 current_module = "autoq";
3519 if (output_quality < opts->auto_quality && aq_sleep_time > 0)
3520 ++output_quality;
3521 else
3522 if (output_quality>1 && aq_sleep_time<0)
3523 --output_quality;
3524 else if (output_quality>0 && aq_sleep_time<-0.050f) // 50ms
3525 output_quality = 0;
3526 set_video_quality(mpctx->sh_video, output_quality);
3529 if (!frame_time_remaining && blit_frame) {
3530 if (play_n_frames >= 0) {
3531 --play_n_frames;
3532 if (play_n_frames <= 0)
3533 mpctx->stop_play = PT_NEXT_ENTRY;
3535 if (mpctx->step_frames > 0) {
3536 mpctx->step_frames--;
3537 if (mpctx->step_frames == 0)
3538 pause_player(mpctx);
3542 // FIXME: add size based support for -endpos
3543 if (end_at.type == END_AT_TIME &&
3544 !frame_time_remaining && end_at.pos <= mpctx->sh_video->pts)
3545 mpctx->stop_play = PT_NEXT_ENTRY;
3547 } // end if(mpctx->sh_video)
3549 #ifdef CONFIG_DVDNAV
3550 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
3551 nav_highlight_t hl;
3552 mp_dvdnav_get_highlight(mpctx->stream, &hl);
3553 if (!vo_spudec || !spudec_apply_palette_crop(vo_spudec, hl.palette, hl.sx, hl.sy, hl.ex, hl.ey)) {
3554 osd_set_nav_box(hl.sx, hl.sy, hl.ex, hl.ey);
3555 vo_osd_changed(OSDTYPE_DVDNAV);
3556 } else {
3557 osd_set_nav_box(0, 0, 0, 0);
3558 vo_osd_changed(OSDTYPE_DVDNAV);
3559 vo_osd_changed(OSDTYPE_SPU);
3562 if (mp_dvdnav_stream_has_changed(mpctx->stream)) {
3563 double ar = -1.0;
3564 if (mpctx->sh_video &&
3565 stream_control(mpctx->demuxer->stream,
3566 STREAM_CTRL_GET_ASPECT_RATIO, &ar)
3567 != STREAM_UNSUPPORTED)
3568 mpctx->sh_video->stream_aspect = ar;
3571 #endif
3573 //================= Keyboard events, SEEKing ====================
3575 current_module = "key_events";
3577 while (1) {
3578 mp_cmd_t *cmd;
3579 while ((cmd = mp_input_get_cmd(mpctx->input, 0, 1)) != NULL) {
3580 /* Allow running consecutive seek commands to combine them,
3581 * but execute the seek before running other commands.
3582 * If the user seeks continuously (keeps arrow key down)
3583 * try to finish showing a frame from one location before doing
3584 * another seek (which could lead to unchanging display). */
3585 if (mpctx->seek.type && cmd->id != MP_CMD_SEEK
3586 || mpctx->restart_playback && cmd->id == MP_CMD_SEEK
3587 && GetTimerMS() - mpctx->start_timestamp < 300)
3588 break;
3589 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
3590 run_command(mpctx, cmd);
3591 mp_cmd_free(cmd);
3592 if (mpctx->stop_play)
3593 break;
3595 if (!mpctx->paused || mpctx->stop_play || mpctx->seek.type
3596 || mpctx->restart_playback)
3597 break;
3598 if (mpctx->sh_video) {
3599 update_osd_msg(mpctx);
3600 int hack = vo_osd_changed(0);
3601 vo_osd_changed(hack);
3602 if (hack) {
3603 if (redraw_osd(mpctx->sh_video, mpctx->osd) < 0) {
3604 add_step_frame(mpctx);
3605 break;
3606 } else
3607 vo_osd_changed(0);
3610 pause_loop(mpctx);
3613 // handle -sstep
3614 if (step_sec > 0 && !mpctx->paused) {
3615 mpctx->osd_function = OSD_FFW;
3616 queue_seek(mpctx, MPSEEK_RELATIVE, step_sec, 0);
3619 edl_update(mpctx);
3621 /* Looping. */
3622 if (mpctx->stop_play==AT_END_OF_FILE && opts->loop_times>=0) {
3623 mp_msg(MSGT_CPLAYER, MSGL_V, "loop_times = %d\n", opts->loop_times);
3625 if (opts->loop_times>1)
3626 opts->loop_times--;
3627 else if (opts->loop_times==1)
3628 opts->loop_times = -1;
3629 play_n_frames = play_n_frames_mf;
3630 mpctx->stop_play = 0;
3631 queue_seek(mpctx, MPSEEK_ABSOLUTE, 0, 0);
3634 if (mpctx->seek.type) {
3635 seek(mpctx, mpctx->seek, false);
3636 mpctx->seek = (struct seek_params){0};
3641 static int read_keys(void *ctx, int fd)
3643 getch2(ctx);
3644 return mplayer_get_key(ctx, 0);
3647 static bool attachment_is_font(struct demux_attachment *att)
3649 if (!att->name || !att->type || !att->data || !att->data_size)
3650 return false;
3651 // match against MIME types
3652 if (strcmp(att->type, "application/x-truetype-font") == 0
3653 || strcmp(att->type, "application/x-font") == 0)
3654 return true;
3655 // fallback: match against file extension
3656 if (strlen(att->name) > 4) {
3657 char *ext = att->name + strlen(att->name) - 4;
3658 if (strcasecmp(ext, ".ttf") == 0 || strcasecmp(ext, ".ttc") == 0
3659 || strcasecmp(ext, ".otf") == 0)
3660 return true;
3662 return false;
3665 static int select_audio(demuxer_t *demuxer, int audio_id, char **audio_lang)
3667 if (audio_id == -1)
3668 audio_id = demuxer_audio_track_by_lang_and_default(demuxer, audio_lang);
3669 if (audio_id != -1) // -1 (automatic) is the default behaviour of demuxers
3670 demuxer_switch_audio(demuxer, audio_id);
3671 if (audio_id == -2) { // some demuxers don't yet know how to switch to no sound
3672 demuxer->audio->id = -2;
3673 demuxer->audio->sh = NULL;
3675 return demuxer->audio->id;
3678 static void print_version(const char* name)
3680 mp_msg(MSGT_CPLAYER, MSGL_INFO, MP_TITLE, name);
3682 /* Test for CPU capabilities (and corresponding OS support) for optimizing */
3683 GetCpuCaps(&gCpuCaps);
3684 #if ARCH_X86
3685 mp_msg(MSGT_CPLAYER, MSGL_V,
3686 "CPUflags: MMX: %d MMX2: %d 3DNow: %d 3DNowExt: %d SSE: %d SSE2: %d SSSE3: %d\n",
3687 gCpuCaps.hasMMX, gCpuCaps.hasMMX2,
3688 gCpuCaps.has3DNow, gCpuCaps.has3DNowExt,
3689 gCpuCaps.hasSSE, gCpuCaps.hasSSE2, gCpuCaps.hasSSSE3);
3690 #if CONFIG_RUNTIME_CPUDETECT
3691 mp_tmsg(MSGT_CPLAYER,MSGL_V, "Compiled with runtime CPU detection.\n");
3692 #else
3693 mp_tmsg(MSGT_CPLAYER,MSGL_V, "Compiled for x86 CPU with extensions:");
3694 if (HAVE_MMX)
3695 mp_msg(MSGT_CPLAYER,MSGL_V," MMX");
3696 if (HAVE_MMX2)
3697 mp_msg(MSGT_CPLAYER,MSGL_V," MMX2");
3698 if (HAVE_AMD3DNOW)
3699 mp_msg(MSGT_CPLAYER,MSGL_V," 3DNow");
3700 if (HAVE_AMD3DNOWEXT)
3701 mp_msg(MSGT_CPLAYER,MSGL_V," 3DNowExt");
3702 if (HAVE_SSE)
3703 mp_msg(MSGT_CPLAYER,MSGL_V," SSE");
3704 if (HAVE_SSE2)
3705 mp_msg(MSGT_CPLAYER,MSGL_V," SSE2");
3706 if (HAVE_SSSE3)
3707 mp_msg(MSGT_CPLAYER,MSGL_V," SSSE3");
3708 if (HAVE_CMOV)
3709 mp_msg(MSGT_CPLAYER,MSGL_V," CMOV");
3710 mp_msg(MSGT_CPLAYER,MSGL_V,"\n");
3711 #endif /* CONFIG_RUNTIME_CPUDETECT */
3712 #endif /* ARCH_X86 */
3715 #ifdef PTW32_STATIC_LIB
3716 static void detach_ptw32(void)
3718 pthread_win32_thread_detach_np();
3719 pthread_win32_process_detach_np();
3721 #endif
3723 /* This preprocessor directive is a hack to generate a mplayer-nomain.o object
3724 * file for some tools to link against. */
3725 #ifndef DISABLE_MAIN
3726 int main(int argc,char* argv[]){
3727 #ifdef PTW32_STATIC_LIB
3728 pthread_win32_process_attach_np();
3729 pthread_win32_thread_attach_np();
3730 atexit(detach_ptw32);
3731 #endif
3732 if (argc > 1 && !strcmp(argv[1], "-leak-report"))
3733 talloc_enable_leak_report();
3735 char * mem_ptr;
3737 // movie info:
3739 /* Flag indicating whether MPlayer should exit without playing anything. */
3740 int opt_exit = 0;
3741 int i;
3743 struct MPContext *mpctx = &(struct MPContext){
3744 .osd_function = OSD_PLAY,
3745 .begin_skip = MP_NOPTS_VALUE,
3746 .play_tree_step = 1,
3747 .global_sub_pos = -1,
3748 .set_of_sub_pos = -1,
3749 .file_format = DEMUXER_TYPE_UNKNOWN,
3750 .last_dvb_step = 1,
3753 InitTimer();
3754 srand(GetTimerMS());
3756 mp_msg_init();
3757 set_av_log_callback();
3759 #ifdef CONFIG_X11
3760 mpctx->x11_state = vo_x11_init_state();
3761 #endif
3762 struct MPOpts *opts = &mpctx->opts;
3763 set_default_mplayer_options(opts);
3764 // Create the config context and register the options
3765 mpctx->mconfig = m_config_new(opts, cfg_include);
3766 m_config_register_options(mpctx->mconfig,mplayer_opts);
3767 m_config_register_options(mpctx->mconfig, common_opts);
3768 mp_input_register_options(mpctx->mconfig);
3770 // Preparse the command line
3771 m_config_preparse_command_line(mpctx->mconfig,argc,argv);
3773 #if (defined(__MINGW32__) || defined(__CYGWIN__)) && defined(CONFIG_WIN32DLL)
3774 set_path_env();
3775 #endif
3777 #ifdef CONFIG_TV
3778 stream_tv_defaults.immediate = 1;
3779 #endif
3781 parse_cfgfiles(mpctx, mpctx->mconfig);
3783 mpctx->playtree = m_config_parse_mp_command_line(mpctx->mconfig, argc, argv);
3784 if(mpctx->playtree == NULL)
3785 opt_exit = 1;
3786 else {
3787 mpctx->playtree = play_tree_cleanup(mpctx->playtree);
3788 if(mpctx->playtree) {
3789 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,mpctx->mconfig);
3790 if(mpctx->playtree_iter) {
3791 if(play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
3792 play_tree_iter_free(mpctx->playtree_iter);
3793 mpctx->playtree_iter = NULL;
3795 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,1);
3799 mpctx->key_fifo = mp_fifo_create(opts);
3801 print_version("MPlayer2");
3803 #if defined(__MINGW32__) || defined(__CYGWIN__)
3805 HMODULE kernel32 = GetModuleHandle("Kernel32.dll");
3806 BOOL WINAPI (*setDEP)(DWORD) = NULL;
3807 BOOL WINAPI (*setDllDir)(LPCTSTR) = NULL;
3808 if (kernel32) {
3809 setDEP = GetProcAddress(kernel32, "SetProcessDEPPolicy");
3810 setDllDir = GetProcAddress(kernel32, "SetDllDirectoryA");
3812 if (setDEP) setDEP(3);
3813 if (setDllDir) setDllDir("");
3815 // stop Windows from showing all kinds of annoying error dialogs
3816 SetErrorMode(0x8003);
3817 // request 1ms timer resolution
3818 timeBeginPeriod(1);
3819 #endif
3821 #ifdef CONFIG_PRIORITY
3822 set_priority();
3823 #endif
3825 if (codec_path)
3826 set_codec_path(codec_path);
3828 if(opts->video_driver_list && strcmp(opts->video_driver_list[0],"help")==0){
3829 list_video_out();
3830 opt_exit = 1;
3833 if(opts->audio_driver_list && strcmp(opts->audio_driver_list[0],"help")==0){
3834 list_audio_out();
3835 opt_exit = 1;
3838 /* Check codecs.conf. */
3839 if(!codecs_file || !parse_codec_cfg(codecs_file)){
3840 if(!parse_codec_cfg(mem_ptr=get_path("codecs.conf"))){
3841 if(!parse_codec_cfg(MPLAYER_CONFDIR "/codecs.conf")){
3842 if(!parse_codec_cfg(NULL)){
3843 exit_player_with_rc(mpctx, EXIT_NONE, 0);
3845 mp_tmsg(MSGT_CPLAYER,MSGL_V,"Using built-in default codecs.conf.\n");
3848 free( mem_ptr ); // release the buffer created by get_path()
3851 if(audio_codec_list && strcmp(audio_codec_list[0],"help")==0){
3852 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available audio codecs:\n");
3853 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AUDIO_CODECS\n");
3854 list_codecs(1);
3855 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3856 opt_exit = 1;
3858 if(video_codec_list && strcmp(video_codec_list[0],"help")==0){
3859 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available video codecs:\n");
3860 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODECS\n");
3861 list_codecs(0);
3862 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3863 opt_exit = 1;
3865 if(video_fm_list && strcmp(video_fm_list[0],"help")==0){
3866 vfm_help();
3867 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3868 opt_exit = 1;
3870 if(audio_fm_list && strcmp(audio_fm_list[0],"help")==0){
3871 afm_help();
3872 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3873 opt_exit = 1;
3875 if(af_cfg.list && strcmp(af_cfg.list[0],"help")==0){
3876 af_help();
3877 printf("\n");
3878 opt_exit = 1;
3880 #ifdef CONFIG_X11
3881 if(vo_fstype_list && strcmp(vo_fstype_list[0],"help")==0){
3882 fstype_help();
3883 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3884 opt_exit = 1;
3886 #endif
3887 if((opts->demuxer_name && strcmp(opts->demuxer_name,"help")==0) ||
3888 (opts->audio_demuxer_name && strcmp(opts->audio_demuxer_name,"help")==0) ||
3889 (opts->sub_demuxer_name && strcmp(opts->sub_demuxer_name,"help")==0)){
3890 demuxer_help();
3891 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
3892 opt_exit = 1;
3894 if (opts->list_properties) {
3895 property_print_help();
3896 opt_exit = 1;
3899 if(opt_exit)
3900 exit_player(mpctx, EXIT_NONE);
3902 if (!mpctx->filename && !opts->player_idle_mode) {
3903 // no file/vcd/dvd -> show HELP:
3904 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", mp_gtext(help_text));
3905 exit_player_with_rc(mpctx, EXIT_NONE, 0);
3908 /* Display what configure line was used */
3909 mp_msg(MSGT_CPLAYER, MSGL_V, "Configuration: " CONFIGURATION "\n");
3911 // Many users forget to include command line in bugreports...
3912 if( mp_msg_test(MSGT_CPLAYER,MSGL_V) ){
3913 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "CommandLine:");
3914 for(i=1;i<argc;i++)mp_msg(MSGT_CPLAYER, MSGL_INFO," '%s'",argv[i]);
3915 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
3918 //------ load global data first ------
3920 mpctx->osd = osd_create();
3922 // check font
3923 #ifdef CONFIG_FREETYPE
3924 init_freetype();
3925 #endif
3926 #ifdef CONFIG_FONTCONFIG
3927 if(font_fontconfig <= 0)
3929 #endif
3930 #ifdef CONFIG_BITMAP_FONT
3931 if(font_name){
3932 vo_font=read_font_desc(font_name,font_factor,verbose>1);
3933 if(!vo_font) mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load bitmap font: %s\n",
3934 filename_recode(font_name));
3935 } else {
3936 // try default:
3937 vo_font=read_font_desc( mem_ptr=get_path("font/font.desc"),font_factor,verbose>1);
3938 free(mem_ptr); // release the buffer created by get_path()
3939 if(!vo_font)
3940 vo_font=read_font_desc(MPLAYER_DATADIR "/font/font.desc",font_factor,verbose>1);
3942 if (sub_font_name)
3943 mpctx->osd->sub_font = read_font_desc(sub_font_name, font_factor, verbose>1);
3944 else
3945 mpctx->osd->sub_font = vo_font;
3946 #endif
3947 #ifdef CONFIG_FONTCONFIG
3949 #endif
3951 #ifdef CONFIG_ASS
3952 ass_library = mp_ass_init();
3953 #endif
3955 #ifdef HAVE_RTC
3956 if(opts->rtc)
3958 char *rtc_device = opts->rtc_device;
3959 // seteuid(0); /* Can't hurt to try to get root here */
3960 if ((rtc_fd = open(rtc_device ? rtc_device : "/dev/rtc", O_RDONLY)) < 0)
3961 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Failed to open %s: %s (it should be readable by the user.)\n",
3962 rtc_device ? rtc_device : "/dev/rtc", strerror(errno));
3963 else {
3964 unsigned long irqp = 1024; /* 512 seemed OK. 128 is jerky. */
3966 if (ioctl(rtc_fd, RTC_IRQP_SET, irqp) < 0) {
3967 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Linux RTC init error in ioctl (rtc_irqp_set %lu): %s\n", irqp, strerror(errno));
3968 mp_tmsg(MSGT_CPLAYER, MSGL_HINT, "Try adding \"echo %lu > /proc/sys/dev/rtc/max-user-freq\" to your system startup scripts.\n", irqp);
3969 close (rtc_fd);
3970 rtc_fd = -1;
3971 } else if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
3972 /* variable only by the root */
3973 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC init error in ioctl (rtc_pie_on): %s\n", strerror(errno));
3974 close (rtc_fd);
3975 rtc_fd = -1;
3976 } else
3977 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Using Linux hardware RTC timing (%ldHz).\n", irqp);
3980 if(rtc_fd<0)
3981 #endif /* HAVE_RTC */
3982 mp_msg(MSGT_CPLAYER, MSGL_V, "Using %s timing\n",
3983 opts->softsleep ? "software" : timer_name);
3985 #ifdef HAVE_TERMCAP
3986 load_termcap(NULL); // load key-codes
3987 #endif
3989 // ========== Init keyboard FIFO (connection to libvo) ============
3991 // Init input system
3992 current_module = "init_input";
3993 mpctx->input = mp_input_init(&opts->input);
3994 mp_input_add_key_fd(mpctx->input, -1,0,mplayer_get_key,NULL, mpctx->key_fifo);
3995 if(slave_mode)
3996 mp_input_add_cmd_fd(mpctx->input, 0,USE_SELECT,MP_INPUT_SLAVE_CMD_FUNC,NULL);
3997 else if (opts->consolecontrols)
3998 mp_input_add_key_fd(mpctx->input, 0, 1, read_keys, NULL, mpctx->key_fifo);
3999 // Set the libstream interrupt callback
4000 stream_set_interrupt_callback(mp_input_check_interrupt, mpctx->input);
4002 #ifdef CONFIG_MENU
4003 if(use_menu) {
4004 if(menu_cfg && menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
4005 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
4006 else {
4007 menu_cfg = get_path("menu.conf");
4008 if(menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
4009 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
4010 else {
4011 if(menu_init(mpctx, mpctx->mconfig, mpctx->input,
4012 MPLAYER_CONFDIR "/menu.conf"))
4013 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", MPLAYER_CONFDIR"/menu.conf");
4014 else {
4015 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Menu init failed.\n");
4016 use_menu = 0;
4021 #endif
4023 current_module = NULL;
4025 /// Catch signals
4026 #ifndef __MINGW32__
4027 signal(SIGCHLD,child_sighandler);
4028 #endif
4030 #ifdef CONFIG_CRASH_DEBUG
4031 prog_path = argv[0];
4032 #endif
4033 //========= Catch terminate signals: ================
4034 // terminate requests:
4035 signal(SIGTERM,exit_sighandler); // kill
4036 signal(SIGHUP,exit_sighandler); // kill -HUP / xterm closed
4038 signal(SIGINT,exit_sighandler); // Interrupt from keyboard
4040 signal(SIGQUIT,exit_sighandler); // Quit from keyboard
4041 signal(SIGPIPE,exit_sighandler); // Some window managers cause this
4042 #ifdef CONFIG_SIGHANDLER
4043 // fatal errors:
4044 signal(SIGBUS,exit_sighandler); // bus error
4045 signal(SIGSEGV,exit_sighandler); // segfault
4046 signal(SIGILL,exit_sighandler); // illegal instruction
4047 signal(SIGFPE,exit_sighandler); // floating point exc.
4048 signal(SIGABRT,exit_sighandler); // abort()
4049 #ifdef CONFIG_CRASH_DEBUG
4050 if (crash_debug)
4051 signal(SIGTRAP,exit_sighandler);
4052 #endif
4053 #endif
4055 // ******************* Now, let's see the per-file stuff ********************
4057 play_next_file:
4059 // init global sub numbers
4060 mpctx->global_sub_size = 0;
4061 memset(mpctx->sub_counts, 0, sizeof(mpctx->sub_counts));
4063 if (mpctx->filename) {
4064 load_per_protocol_config (mpctx->mconfig, mpctx->filename);
4065 load_per_extension_config (mpctx->mconfig, mpctx->filename);
4066 load_per_file_config (mpctx->mconfig, mpctx->filename);
4069 if (opts->video_driver_list)
4070 load_per_output_config (mpctx->mconfig, PROFILE_CFG_VO, opts->video_driver_list[0]);
4071 if (opts->audio_driver_list)
4072 load_per_output_config (mpctx->mconfig, PROFILE_CFG_AO, opts->audio_driver_list[0]);
4074 // We must enable getch2 here to be able to interrupt network connection
4075 // or cache filling
4076 if (opts->consolecontrols && !slave_mode) {
4077 if(mpctx->initialized_flags&INITIALIZED_GETCH2)
4078 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"WARNING: getch2_init called twice!\n");
4079 else
4080 getch2_enable(); // prepare stdin for hotkeys...
4081 mpctx->initialized_flags|=INITIALIZED_GETCH2;
4082 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[init getch2]]]\n");
4085 // =================== GUI idle loop (STOP state) ===========================
4086 while (opts->player_idle_mode && !mpctx->filename) {
4087 play_tree_t * entry = NULL;
4088 mp_cmd_t * cmd;
4089 if (mpctx->video_out && mpctx->video_out->config_ok)
4090 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
4091 while (!(cmd = mp_input_get_cmd(mpctx->input, 0, 0))) { // wait for command
4092 if (mpctx->video_out)
4093 vo_check_events(mpctx->video_out);
4094 usec_sleep(20000);
4096 switch (cmd->id) {
4097 case MP_CMD_LOADFILE:
4098 // prepare a tree entry with the new filename
4099 entry = play_tree_new();
4100 play_tree_add_file(entry, cmd->args[0].v.s);
4101 // The entry is added to the main playtree after the switch().
4102 break;
4103 case MP_CMD_LOADLIST:
4104 entry = parse_playlist_file(mpctx->mconfig, cmd->args[0].v.s);
4105 break;
4106 case MP_CMD_QUIT:
4107 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
4108 break;
4109 case MP_CMD_VO_FULLSCREEN:
4110 case MP_CMD_GET_PROPERTY:
4111 case MP_CMD_SET_PROPERTY:
4112 case MP_CMD_STEP_PROPERTY:
4113 run_command(mpctx, cmd);
4114 break;
4117 mp_cmd_free(cmd);
4119 if (entry) { // user entered a command that gave a valid entry
4120 if (mpctx->playtree) // the playtree is always a node with one child. let's clear it
4121 play_tree_free_list(mpctx->playtree->child, 1);
4122 else mpctx->playtree=play_tree_new(); // .. or make a brand new playtree
4124 if (!mpctx->playtree) continue; // couldn't make playtree! wait for next command
4126 play_tree_set_child(mpctx->playtree, entry);
4128 /* Make iterator start at the top the of tree. */
4129 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree, mpctx->mconfig);
4130 if (!mpctx->playtree_iter) continue;
4132 // find the first real item in the tree
4133 if (play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
4134 // no items!
4135 play_tree_iter_free(mpctx->playtree_iter);
4136 mpctx->playtree_iter = NULL;
4137 continue; // wait for next command
4139 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, 1);
4142 //---------------------------------------------------------------------------
4144 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
4145 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL);
4147 if (mpctx->filename) {
4148 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nPlaying %s.\n",
4149 filename_recode(mpctx->filename));
4150 if(use_filename_title && opts->vo_wintitle == NULL)
4151 opts->vo_wintitle = strdup(mp_basename(mpctx->filename));
4154 if (edl_filename) {
4155 if (edl_records) free_edl(edl_records);
4156 next_edl_record = edl_records = edl_parse_file();
4158 if (edl_output_filename) {
4159 if (edl_fd) fclose(edl_fd);
4160 if ((edl_fd = fopen(edl_output_filename, "w")) == NULL)
4162 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Can't open EDL file [%s] for writing.\n",
4163 filename_recode(edl_output_filename));
4167 //==================== Open VOB-Sub ============================
4169 current_module="vobsub";
4170 if (opts->vobsub_name){
4171 vo_vobsub=vobsub_open(opts->vobsub_name,spudec_ifo,1,&vo_spudec);
4172 if(vo_vobsub==NULL)
4173 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load subtitles: %s\n",
4174 filename_recode(opts->vobsub_name));
4175 } else if (opts->sub_auto && mpctx->filename){
4176 /* try to autodetect vobsub from movie filename ::atmos */
4177 char *buf = strdup(mpctx->filename), *psub;
4178 char *pdot = strrchr(buf, '.');
4179 char *pslash = strrchr(buf, '/');
4180 #if defined(__MINGW32__) || defined(__CYGWIN__)
4181 if (!pslash) pslash = strrchr(buf, '\\');
4182 #endif
4183 if (pdot && (!pslash || pdot > pslash))
4184 *pdot = '\0';
4185 vo_vobsub=vobsub_open(buf,spudec_ifo,0,&vo_spudec);
4186 /* try from ~/.mplayer/sub */
4187 if(!vo_vobsub && (psub = get_path( "sub/" ))) {
4188 const char *bname = mp_basename(buf);
4189 int l;
4190 l = strlen(psub) + strlen(bname) + 1;
4191 psub = realloc(psub,l);
4192 strcat(psub,bname);
4193 vo_vobsub=vobsub_open(psub,spudec_ifo,0,&vo_spudec);
4194 free(psub);
4196 free(buf);
4198 if(vo_vobsub){
4199 mpctx->initialized_flags|=INITIALIZED_VOBSUB;
4200 vobsub_set_from_lang(vo_vobsub, opts->sub_lang);
4201 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
4203 // setup global sub numbering
4204 mpctx->sub_counts[SUB_SOURCE_VOBSUB] = vobsub_get_indexes_count(vo_vobsub);
4207 //============ Open & Sync STREAM --- fork cache2 ====================
4209 mpctx->stream=NULL;
4210 mpctx->demuxer=NULL;
4211 mpctx->d_audio=NULL;
4212 mpctx->d_video=NULL;
4213 mpctx->d_sub = NULL;
4214 mpctx->sh_audio=NULL;
4215 mpctx->sh_video=NULL;
4217 current_module="open_stream";
4218 mpctx->stream = open_stream(mpctx->filename, opts, &mpctx->file_format);
4219 if(!mpctx->stream) { // error...
4220 mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY);
4221 goto goto_next_file;
4223 mpctx->initialized_flags|=INITIALIZED_STREAM;
4225 if(mpctx->file_format == DEMUXER_TYPE_PLAYLIST) {
4226 mp_msg(MSGT_CPLAYER, MSGL_ERR, "\nThis looks like a playlist, but "
4227 "playlist support will not be used automatically.\n"
4228 "MPlayer's playlist code is unsafe and should only be used with "
4229 "trusted sources.\nPlayback will probably fail.\n\n");
4230 #if 0
4231 play_tree_t* entry;
4232 // Handle playlist
4233 current_module="handle_playlist";
4234 mp_msg(MSGT_CPLAYER,MSGL_V,"Parsing playlist %s...\n",
4235 filename_recode(mpctx->filename));
4236 entry = parse_playtree(mpctx->stream, mpctx->mconfig, 0);
4237 mpctx->eof=playtree_add_playlist(mpctx, entry);
4238 goto goto_next_file;
4239 #endif
4241 mpctx->stream->start_pos+=seek_to_byte;
4243 if(stream_dump_type==5){
4244 unsigned char buf[4096];
4245 int len;
4246 FILE *f;
4247 current_module="dumpstream";
4248 stream_reset(mpctx->stream);
4249 stream_seek(mpctx->stream,mpctx->stream->start_pos);
4250 f=fopen(opts->stream_dump_name,"wb");
4251 if(!f){
4252 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
4253 exit_player(mpctx, EXIT_ERROR);
4255 if (opts->chapterrange[0] > 1) {
4256 int chapter = opts->chapterrange[0] - 1;
4257 stream_control(mpctx->stream, STREAM_CTRL_SEEK_TO_CHAPTER, &chapter);
4259 while(!mpctx->stream->eof && !async_quit_request){
4260 len=stream_read(mpctx->stream,buf,4096);
4261 if(len>0) {
4262 if(fwrite(buf,len,1,f) != 1) {
4263 mp_tmsg(MSGT_GLOBAL,MSGL_FATAL,"%s: Error writing file.\n",opts->stream_dump_name);
4264 exit_player(mpctx, EXIT_ERROR);
4267 if (opts->chapterrange[1] > 0) {
4268 int chapter = -1;
4269 if (stream_control(mpctx->stream, STREAM_CTRL_GET_CURRENT_CHAPTER,
4270 &chapter) == STREAM_OK
4271 && chapter + 1 > opts->chapterrange[1])
4272 break;
4275 if(fclose(f)) {
4276 mp_tmsg(MSGT_GLOBAL,MSGL_FATAL,"%s: Error writing file.\n",opts->stream_dump_name);
4277 exit_player(mpctx, EXIT_ERROR);
4279 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Stream dump complete.\n");
4280 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4283 #ifdef CONFIG_DVDREAD
4284 if(mpctx->stream->type==STREAMTYPE_DVD){
4285 current_module="dvd lang->id";
4286 if(opts->audio_lang && opts->audio_id==-1) opts->audio_id=dvd_aid_from_lang(mpctx->stream,opts->audio_lang);
4287 if(opts->sub_lang && opts->sub_id==-1) opts->sub_id=dvd_sid_from_lang(mpctx->stream,opts->sub_lang);
4288 // setup global sub numbering
4289 mpctx->sub_counts[SUB_SOURCE_DEMUX] = dvd_number_of_subs(mpctx->stream);
4290 current_module=NULL;
4292 #endif
4294 #ifdef CONFIG_DVDNAV
4295 if(mpctx->stream->type==STREAMTYPE_DVDNAV){
4296 current_module="dvdnav lang->id";
4297 if(opts->audio_lang && opts->audio_id==-1) opts->audio_id=mp_dvdnav_aid_from_lang(mpctx->stream,opts->audio_lang);
4298 dvdsub_lang_id = -3;
4299 if(opts->sub_lang && opts->sub_id==-1)
4300 dvdsub_lang_id = opts->sub_id = mp_dvdnav_sid_from_lang(mpctx->stream,opts->sub_lang);
4301 // setup global sub numbering
4302 mpctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(mpctx->stream);
4303 current_module=NULL;
4305 #endif
4307 // CACHE2: initial prefill: 20% later: 5% (should be set by -cacheopts)
4308 goto_enable_cache:
4309 if(stream_cache_size>0){
4310 int res;
4311 float stream_cache_min_percent = opts->stream_cache_min_percent;
4312 float stream_cache_seek_min_percent = opts->stream_cache_seek_min_percent;
4313 current_module="enable_cache";
4314 res = stream_enable_cache(mpctx->stream,stream_cache_size*1024,
4315 stream_cache_size*1024*(stream_cache_min_percent / 100.0),
4316 stream_cache_size*1024*(stream_cache_seek_min_percent / 100.0));
4317 if(res == 0)
4318 if((mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY))) goto goto_next_file;
4321 //============ Open DEMUXERS --- DETECT file type =======================
4322 current_module="demux_open";
4324 mpctx->demuxer=demux_open(opts, mpctx->stream,mpctx->file_format,opts->audio_id,opts->video_id,opts->sub_id,mpctx->filename);
4326 // HACK to get MOV Reference Files working
4328 if (mpctx->demuxer && mpctx->demuxer->type==DEMUXER_TYPE_PLAYLIST)
4330 unsigned char* playlist_entry;
4331 play_tree_t *list = NULL, *entry = NULL;
4333 current_module="handle_demux_playlist";
4334 while (ds_get_packet(mpctx->demuxer->video,&playlist_entry)>0)
4336 char *temp;
4337 const char *bname;
4339 mp_msg(MSGT_CPLAYER,MSGL_V,"Adding file %s to element entry.\n",
4340 filename_recode(playlist_entry));
4342 bname=mp_basename(playlist_entry);
4343 if ((strlen(bname)>10) && !strncmp(bname,"qt",2) && !strncmp(bname+3,"gateQT",6))
4344 continue;
4346 if (!strcmp(playlist_entry, mpctx->filename)) // ignoring self-reference
4347 continue;
4349 entry = play_tree_new();
4351 if (mpctx->filename && !strcmp(mp_basename(playlist_entry),playlist_entry)) // add reference path of current file
4353 temp=malloc((strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))+strlen(playlist_entry)+1));
4354 if (temp)
4356 strncpy(temp, mpctx->filename, strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename)));
4357 temp[strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))]='\0';
4358 strcat(temp, playlist_entry);
4359 if (!strcmp(temp, mpctx->filename)) {
4360 free(temp);
4361 continue;
4363 play_tree_add_file(entry,temp);
4364 mp_msg(MSGT_CPLAYER,MSGL_V,"Resolving reference to %s.\n",temp);
4365 free(temp);
4368 else
4369 play_tree_add_file(entry,playlist_entry);
4371 if(!list)
4372 list = entry;
4373 else
4374 play_tree_append_entry(list,entry);
4376 free_demuxer(mpctx->demuxer);
4377 mpctx->demuxer = NULL;
4379 if (list)
4381 entry = play_tree_new();
4382 play_tree_set_child(entry,list);
4383 mpctx->stop_play = playtree_add_playlist(mpctx, entry);
4384 goto goto_next_file;
4388 if(!mpctx->demuxer) {
4389 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Failed to recognize file format.\n");
4390 goto goto_next_file;
4393 if (mpctx->demuxer->matroska_data.ordered_chapters)
4394 build_ordered_chapter_timeline(mpctx);
4396 if (mpctx->demuxer->type == DEMUXER_TYPE_EDL)
4397 build_edl_timeline(mpctx);
4399 if (mpctx->timeline) {
4400 mpctx->timeline_part = 0;
4401 mpctx->demuxer = mpctx->timeline[0].source->demuxer;
4403 int part_count = mpctx->num_timeline_parts;
4404 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline contains %d parts from %d "
4405 "sources. Total length %.3f seconds.\n", part_count,
4406 mpctx->num_sources, mpctx->timeline[part_count].start);
4407 mp_msg(MSGT_CPLAYER, MSGL_V, "Source files:\n");
4408 for (int i = 0; i < mpctx->num_sources; i++)
4409 mp_msg(MSGT_CPLAYER, MSGL_V, "%d: %s\n", i,
4410 filename_recode(mpctx->sources[i].demuxer->filename));
4411 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline parts: (number, start, "
4412 "source_start, source):\n");
4413 for (int i = 0; i < part_count; i++) {
4414 struct timeline_part *p = mpctx->timeline + i;
4415 mp_msg(MSGT_CPLAYER, MSGL_V, "%3d %9.3f %9.3f %3td\n", i, p->start,
4416 p->source_start, p->source - mpctx->sources);
4418 mp_msg(MSGT_CPLAYER, MSGL_V, "END %9.3f\n",
4419 mpctx->timeline[part_count].start);
4422 if (!mpctx->sources) {
4423 mpctx->sources = talloc_ptrtype(NULL, mpctx->sources);
4424 *mpctx->sources = (struct content_source){.stream = mpctx->stream,
4425 .demuxer = mpctx->demuxer};
4426 mpctx->num_sources = 1;
4429 mpctx->initialized_flags|=INITIALIZED_DEMUXER;
4431 #ifdef CONFIG_ASS
4432 if (opts->ass_enabled && ass_library) {
4433 for (int j = 0; j < mpctx->num_sources; j++) {
4434 struct demuxer *d = mpctx->sources[j].demuxer;
4435 for (int i = 0; i < d->num_attachments; i++) {
4436 struct demux_attachment *att = d->attachments + i;
4437 if (use_embedded_fonts && attachment_is_font(att))
4438 ass_add_font(ass_library, att->name, att->data, att->data_size);
4442 #endif
4444 current_module="demux_open2";
4446 mpctx->d_audio=mpctx->demuxer->audio;
4447 mpctx->d_video=mpctx->demuxer->video;
4448 mpctx->d_sub=mpctx->demuxer->sub;
4450 if (ts_prog) {
4451 int tmp = ts_prog;
4452 mp_property_do("switch_program", M_PROPERTY_SET, &tmp, mpctx);
4454 // select audio stream
4455 for (int i = 0; i < mpctx->num_sources; i++)
4456 select_audio(mpctx->sources[i].demuxer->audio->demuxer, opts->audio_id,
4457 opts->audio_lang);
4459 // DUMP STREAMS:
4460 if((stream_dump_type)&&(stream_dump_type<4)){
4461 FILE *f;
4462 demux_stream_t *ds=NULL;
4463 current_module="dump";
4464 // select stream to dump
4465 switch(stream_dump_type){
4466 case 1: ds=mpctx->d_audio;break;
4467 case 2: ds=mpctx->d_video;break;
4468 case 3: ds=mpctx->d_sub;break;
4470 if(!ds){
4471 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"dump: FATAL: Selected stream missing!\n");
4472 exit_player(mpctx, EXIT_ERROR);
4474 // disable other streams:
4475 if(mpctx->d_audio && mpctx->d_audio!=ds) {ds_free_packs(mpctx->d_audio); mpctx->d_audio->id=-2; }
4476 if(mpctx->d_video && mpctx->d_video!=ds) {ds_free_packs(mpctx->d_video); mpctx->d_video->id=-2; }
4477 if(mpctx->d_sub && mpctx->d_sub!=ds) {ds_free_packs(mpctx->d_sub); mpctx->d_sub->id=-2; }
4478 // let's dump it!
4479 f=fopen(opts->stream_dump_name,"wb");
4480 if(!f){
4481 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
4482 exit_player(mpctx, EXIT_ERROR);
4484 while(!ds->eof){
4485 unsigned char* start;
4486 int in_size=ds_get_packet(ds,&start);
4487 if( (mpctx->demuxer->file_format==DEMUXER_TYPE_AVI || mpctx->demuxer->file_format==DEMUXER_TYPE_ASF || mpctx->demuxer->file_format==DEMUXER_TYPE_MOV)
4488 && stream_dump_type==2) fwrite(&in_size,1,4,f);
4489 if(in_size>0) fwrite(start,in_size,1,f);
4490 if (opts->chapterrange[1] > 0) {
4491 int cur_chapter = demuxer_get_current_chapter(mpctx->demuxer, 0);
4492 if(cur_chapter!=-1 && cur_chapter+1 > opts->chapterrange[1])
4493 break;
4496 fclose(f);
4497 mp_tmsg(MSGT_CPLAYER ,MSGL_INFO, "Stream dump complete.\n");
4498 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4501 mpctx->sh_audio=mpctx->d_audio->sh;
4502 mpctx->sh_video=mpctx->d_video->sh;
4504 if(mpctx->sh_video){
4506 current_module="video_read_properties";
4507 if(!video_read_properties(mpctx->sh_video)) {
4508 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Video: Cannot read properties.\n");
4509 mpctx->sh_video=mpctx->d_video->sh=NULL;
4510 } else {
4511 mp_tmsg(MSGT_CPLAYER,MSGL_V,"[V] filefmt:%d fourcc:0x%X size:%dx%d fps:%5.3f ftime:=%6.4f\n",
4512 mpctx->demuxer->file_format,mpctx->sh_video->format, mpctx->sh_video->disp_w,mpctx->sh_video->disp_h,
4513 mpctx->sh_video->fps,mpctx->sh_video->frametime
4516 /* need to set fps here for output encoders to pick it up in their init */
4517 if(force_fps){
4518 mpctx->sh_video->fps=force_fps;
4519 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
4521 vo_fps = mpctx->sh_video->fps;
4523 if(!mpctx->sh_video->fps && !force_fps){
4524 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"FPS not specified in the header or invalid, use the -fps option.\n");
4525 mpctx->opts.correct_pts = 1;
4531 if(!mpctx->sh_video && !mpctx->sh_audio){
4532 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL, "No stream found.\n");
4533 #ifdef CONFIG_DVBIN
4534 if(mpctx->stream->type == STREAMTYPE_DVB)
4536 int dir;
4537 int v = mpctx->last_dvb_step;
4538 if(v > 0)
4539 dir = DVB_CHANNEL_HIGHER;
4540 else
4541 dir = DVB_CHANNEL_LOWER;
4543 if(dvb_step_channel(mpctx->stream, dir)) {
4544 mpctx->stop_play = PT_NEXT_ENTRY;
4545 mpctx->dvbin_reopen = 1;
4548 #endif
4549 goto goto_next_file; // exit_player(_("Fatal error"));
4552 /* display clip info */
4553 demux_info_print(mpctx->demuxer);
4555 //================== Read SUBTITLES (DVD & TEXT) ==========================
4556 if(vo_spudec==NULL &&
4557 (mpctx->stream->type==STREAMTYPE_DVD || mpctx->stream->type == STREAMTYPE_DVDNAV)){
4558 init_vo_spudec(mpctx);
4561 // after reading video params we should load subtitles because
4562 // we know fps so now we can adjust subtitle time to ~6 seconds AST
4563 // check .sub
4564 current_module="read_subtitles_file";
4565 double sub_fps = mpctx->sh_video ? mpctx->sh_video->fps : 25;
4566 if(opts->sub_name){
4567 for (i = 0; opts->sub_name[i] != NULL; ++i)
4568 add_subtitles(mpctx, opts->sub_name[i], sub_fps, 0);
4570 if(opts->sub_auto) { // auto load sub file ...
4571 char *psub = get_path( "sub/" );
4572 char **tmp = sub_filenames((psub ? psub : ""), mpctx->filename);
4573 int i = 0;
4574 free(psub); // release the buffer created by get_path() above
4575 while (tmp[i]) {
4576 add_subtitles(mpctx, tmp[i], sub_fps, 1);
4577 free(tmp[i++]);
4579 free(tmp);
4581 if (mpctx->set_of_sub_size > 0)
4582 mpctx->sub_counts[SUB_SOURCE_SUBS] = mpctx->set_of_sub_size;
4584 if (select_subtitle(mpctx)) {
4585 if(mpctx->subdata)
4586 switch (stream_dump_type) {
4587 case 3: list_sub_file(mpctx->subdata); break;
4588 case 4: dump_mpsub(mpctx->subdata, mpctx->sh_video->fps); break;
4589 case 6: dump_srt(mpctx->subdata, mpctx->sh_video->fps); break;
4590 case 7: dump_microdvd(mpctx->subdata, mpctx->sh_video->fps); break;
4591 case 8: dump_jacosub(mpctx->subdata, mpctx->sh_video->fps); break;
4592 case 9: dump_sami(mpctx->subdata, mpctx->sh_video->fps); break;
4596 print_file_properties(mpctx, mpctx->filename);
4598 reinit_video_chain(mpctx);
4599 if (mpctx->sh_video) {
4600 if(mpctx->sh_video->output_flags & VFCAP_SPU && vo_spudec)
4601 spudec_set_hw_spu(vo_spudec,mpctx->video_out);
4602 #ifdef CONFIG_FREETYPE
4603 force_load_font = 1;
4604 #endif
4605 } else if (!mpctx->sh_audio)
4606 goto goto_next_file;
4608 //================== MAIN: ==========================
4609 current_module="main";
4611 if (opts->playing_msg) {
4612 char* msg = property_expand_string(mpctx, opts->playing_msg);
4613 mp_msg(MSGT_CPLAYER,MSGL_INFO,"%s",msg);
4614 free(msg);
4618 // Disable the term OSD in verbose mode
4619 if (verbose)
4620 opts->term_osd = 0;
4624 // Make sure old OSD does not stay around,
4625 // e.g. with -fixed-vo and same-resolution files
4626 clear_osd_msgs();
4627 update_osd_msg(mpctx);
4629 //================ SETUP AUDIO ==========================
4631 if(mpctx->sh_audio){
4632 reinit_audio_chain(mpctx);
4633 if (mpctx->sh_audio && mpctx->sh_audio->codec)
4634 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_CODEC=%s\n", mpctx->sh_audio->codec->name);
4637 current_module="av_init";
4639 if(mpctx->sh_video){
4640 mpctx->sh_video->timer=0;
4641 if (! ignore_start)
4642 audio_delay += mpctx->sh_video->stream_delay;
4644 if(mpctx->sh_audio){
4645 if (start_volume >= 0)
4646 mixer_setvolume(&mpctx->mixer, start_volume, start_volume);
4647 if (! ignore_start)
4648 audio_delay -= mpctx->sh_audio->stream_delay;
4649 mpctx->delay=-audio_delay;
4652 if(!mpctx->sh_audio){
4653 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Audio: no sound\n");
4654 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused audio chunks.\n",mpctx->d_audio->packs);
4655 ds_free_packs(mpctx->d_audio); // free buffered chunks
4656 //mpctx->d_audio->id=-2; // do not read audio chunks
4657 //uninit_player(mpctx, INITIALIZED_AO); // close device
4659 if(!mpctx->sh_video){
4660 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Video: no video\n");
4661 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused video chunks.\n",mpctx->d_video->packs);
4662 ds_free_packs(mpctx->d_video);
4663 mpctx->d_video->id=-2;
4664 //if(!fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
4667 if (!mpctx->sh_video && !mpctx->sh_audio)
4668 goto goto_next_file;
4670 //if(demuxer->file_format!=DEMUXER_TYPE_AVI) pts_from_bps=0; // it must be 0 for mpeg/asf!
4671 if(force_fps && mpctx->sh_video){
4672 vo_fps = mpctx->sh_video->fps=force_fps;
4673 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
4674 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"FPS forced to be %5.3f (ftime: %5.3f).\n",mpctx->sh_video->fps,mpctx->sh_video->frametime);
4677 mp_input_set_section(mpctx->input, NULL);
4678 //TODO: add desired (stream-based) sections here
4679 if (mpctx->stream->type==STREAMTYPE_TV) mp_input_set_section(mpctx->input, "tv");
4680 if (mpctx->stream->type==STREAMTYPE_DVDNAV) mp_input_set_section(mpctx->input, "dvdnav");
4682 //==================== START PLAYING =======================
4684 if(opts->loop_times>1) opts->loop_times--; else
4685 if(opts->loop_times==1) opts->loop_times = -1;
4687 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Starting playback...\n");
4689 total_time_usage_start=GetTimer();
4690 audio_time_usage=0; video_time_usage=0; vout_time_usage=0;
4691 total_frame_cnt=0; drop_frame_cnt=0; // fix for multifile fps benchmark
4692 play_n_frames=play_n_frames_mf;
4694 if(play_n_frames==0){
4695 mpctx->stop_play=PT_NEXT_ENTRY; goto goto_next_file;
4698 mpctx->time_frame = 0;
4699 mpctx->drop_message_shown = 0;
4700 mpctx->restart_playback = true;
4701 mpctx->video_pts = 0;
4702 mpctx->hrseek_active = false;
4703 mpctx->hrseek_framedrop = false;
4704 mpctx->step_frames = 0;
4705 mpctx->total_avsync_change = 0;
4706 mpctx->last_chapter_seek = -1;
4708 // If there's a timeline force an absolute seek to initialize state
4709 if (seek_to_sec || mpctx->timeline) {
4710 queue_seek(mpctx, MPSEEK_ABSOLUTE, seek_to_sec, 0);
4711 seek(mpctx, mpctx->seek, false);
4712 end_at.pos += seek_to_sec;
4714 if (opts->chapterrange[0] > 0) {
4715 double pts;
4716 if (seek_chapter(mpctx, opts->chapterrange[0]-1, &pts, NULL) >= 0
4717 && pts > -1.0) {
4718 queue_seek(mpctx, MPSEEK_ABSOLUTE, pts, 0);
4719 seek(mpctx, mpctx->seek, false);
4723 if (end_at.type == END_AT_SIZE) {
4724 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Option -endpos in MPlayer does not yet support size units.\n");
4725 end_at.type = END_AT_NONE;
4728 #ifdef CONFIG_DVDNAV
4729 mp_dvdnav_context_free(mpctx);
4730 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4731 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
4732 mp_dvdnav_cell_has_changed(mpctx->stream,1);
4734 #endif
4736 mpctx->seek = (struct seek_params){0};
4737 get_relative_time(mpctx); // reset current delta
4738 // Make sure VO knows current pause state
4739 if (mpctx->sh_video)
4740 vo_control(mpctx->video_out, mpctx->paused ? VOCTRL_PAUSE : VOCTRL_RESUME,
4741 NULL);
4743 while (!mpctx->stop_play)
4744 run_playloop(mpctx);
4746 mp_msg(MSGT_GLOBAL,MSGL_V,"EOF code: %d \n",mpctx->stop_play);
4748 #ifdef CONFIG_DVBIN
4749 if(mpctx->dvbin_reopen)
4751 mpctx->stop_play = 0;
4752 uninit_player(mpctx, INITIALIZED_ALL-(INITIALIZED_STREAM|INITIALIZED_GETCH2|(opts->fixed_vo?INITIALIZED_VO:0)));
4753 cache_uninit(mpctx->stream);
4754 mpctx->dvbin_reopen = 0;
4755 goto goto_enable_cache;
4757 #endif
4760 goto_next_file: // don't jump here after ao/vo/getch initialization!
4762 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\n");
4764 if (opts->benchmark) {
4765 double tot=video_time_usage+vout_time_usage+audio_time_usage;
4766 double total_time_usage;
4767 total_time_usage_start=GetTimer()-total_time_usage_start;
4768 total_time_usage = (float)total_time_usage_start*0.000001;
4769 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\nBENCHMARKs: VC:%8.3fs VO:%8.3fs A:%8.3fs Sys:%8.3fs = %8.3fs\n",
4770 video_time_usage,vout_time_usage,audio_time_usage,
4771 total_time_usage-tot,total_time_usage);
4772 if(total_time_usage>0.0)
4773 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARK%%: VC:%8.4f%% VO:%8.4f%% A:%8.4f%% Sys:%8.4f%% = %8.4f%%\n",
4774 100.0*video_time_usage/total_time_usage,
4775 100.0*vout_time_usage/total_time_usage,
4776 100.0*audio_time_usage/total_time_usage,
4777 100.0*(total_time_usage-tot)/total_time_usage,
4778 100.0);
4779 if(total_frame_cnt && frame_dropping)
4780 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARKn: disp: %d (%3.2f fps) drop: %d (%d%%) total: %d (%3.2f fps)\n",
4781 total_frame_cnt-drop_frame_cnt,
4782 (total_time_usage>0.5)?((total_frame_cnt-drop_frame_cnt)/total_time_usage):0,
4783 drop_frame_cnt,
4784 100*drop_frame_cnt/total_frame_cnt,
4785 total_frame_cnt,
4786 (total_time_usage>0.5)?(total_frame_cnt/total_time_usage):0);
4789 // time to uninit all, except global stuff:
4790 int uninitialize_parts = INITIALIZED_ALL;
4791 if (opts->fixed_vo)
4792 uninitialize_parts -= INITIALIZED_VO;
4793 if (opts->gapless_audio && mpctx->stop_play == AT_END_OF_FILE)
4794 uninitialize_parts -= INITIALIZED_AO;
4795 uninit_player(mpctx, uninitialize_parts);
4797 if(mpctx->set_of_sub_size > 0) {
4798 current_module="sub_free";
4799 for(i = 0; i < mpctx->set_of_sub_size; ++i) {
4800 sub_free(mpctx->set_of_subtitles[i]);
4801 #ifdef CONFIG_ASS
4802 if(mpctx->set_of_ass_tracks[i])
4803 ass_free_track( mpctx->set_of_ass_tracks[i] );
4804 #endif
4806 mpctx->set_of_sub_size = 0;
4808 mpctx->vo_sub_last = vo_sub=NULL;
4809 mpctx->subdata=NULL;
4810 #ifdef CONFIG_ASS
4811 mpctx->osd->ass_track = NULL;
4812 if(ass_library)
4813 ass_clear_fonts(ass_library);
4814 #endif
4816 if (!mpctx->stop_play) // In case some goto jumped here...
4817 mpctx->stop_play = PT_NEXT_ENTRY;
4819 int playtree_direction = 1;
4821 if(mpctx->stop_play == PT_NEXT_ENTRY || mpctx->stop_play == PT_PREV_ENTRY) {
4822 if(play_tree_iter_step(mpctx->playtree_iter,mpctx->play_tree_step,0) != PLAY_TREE_ITER_ENTRY) {
4823 play_tree_iter_free(mpctx->playtree_iter);
4824 mpctx->playtree_iter = NULL;
4826 mpctx->play_tree_step = 1;
4827 } else if(mpctx->stop_play == PT_UP_NEXT || mpctx->stop_play == PT_UP_PREV) {
4828 int direction = mpctx->stop_play == PT_UP_NEXT ? 1 : -1;
4829 if(mpctx->playtree_iter) {
4830 if(play_tree_iter_up_step(mpctx->playtree_iter,direction,0) != PLAY_TREE_ITER_ENTRY) {
4831 play_tree_iter_free(mpctx->playtree_iter);
4832 mpctx->playtree_iter = NULL;
4835 } else if (mpctx->stop_play == PT_STOP) {
4836 play_tree_iter_free(mpctx->playtree_iter);
4837 mpctx->playtree_iter = NULL;
4838 } else { // NEXT PREV SRC
4839 playtree_direction = mpctx->stop_play == PT_PREV_SRC ? -1 : 1;
4842 while(mpctx->playtree_iter != NULL) {
4843 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, playtree_direction);
4844 if(mpctx->filename == NULL) {
4845 if(play_tree_iter_step(mpctx->playtree_iter, playtree_direction, 0) != PLAY_TREE_ITER_ENTRY) {
4846 play_tree_iter_free(mpctx->playtree_iter);
4847 mpctx->playtree_iter = NULL;
4849 } else
4850 break;
4853 if (mpctx->playtree_iter != NULL || opts->player_idle_mode) {
4854 if(!mpctx->playtree_iter) mpctx->filename = NULL;
4855 mpctx->stop_play = 0;
4856 goto play_next_file;
4860 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4862 return 1;
4864 #endif /* DISABLE_MAIN */