cleanup: find_subfiles.c: simplify declarations and allocations
[mplayer/greg.git] / mplayer.c
blobb80199976298596e40fddeb854367c282f253419
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/find_subfiles.h"
76 #include "sub/dec_sub.h"
78 #include "mp_osd.h"
79 #include "libvo/video_out.h"
81 #include "sub/font_load.h"
82 #include "sub/sub.h"
83 #include "ffmpeg_files/intreadwrite.h"
84 #include "sub/av_sub.h"
85 #include "libmpcodecs/dec_teletext.h"
86 #include "cpudetect.h"
87 #include "version.h"
89 #ifdef CONFIG_X11
90 #include "libvo/x11_common.h"
91 #endif
93 #include "libao2/audio_out.h"
95 #include "codec-cfg.h"
97 #include "edl.h"
99 #include "sub/spudec.h"
100 #include "sub/vobsub.h"
102 #include "osdep/getch2.h"
103 #include "osdep/timer.h"
105 #include "input/input.h"
107 int slave_mode=0;
108 int enable_mouse_movements=0;
109 float start_volume = -1;
111 #include "osdep/priority.h"
113 char *heartbeat_cmd;
115 #ifdef HAVE_RTC
116 #ifdef __linux__
117 #include <linux/rtc.h>
118 #else
119 #include <rtc.h>
120 #define RTC_IRQP_SET RTCIO_IRQP_SET
121 #define RTC_PIE_ON RTCIO_PIE_ON
122 #endif /* __linux__ */
123 #endif /* HAVE_RTC */
125 #include "stream/tv.h"
126 #include "stream/stream_radio.h"
127 #ifdef CONFIG_DVBIN
128 #include "stream/dvbin.h"
129 #endif
130 #include "stream/cache2.h"
132 //**************************************************************************//
133 // Playtree
134 //**************************************************************************//
135 #include "playtree.h"
136 #include "playtreeparser.h"
138 //**************************************************************************//
139 // Config
140 //**************************************************************************//
141 #include "parser-cfg.h"
142 #include "parser-mpcmd.h"
144 //**************************************************************************//
145 // Config file
146 //**************************************************************************//
148 static int cfg_inc_verbose(m_option_t *conf){ ++verbose; return 0;}
150 #include "path.h"
152 //**************************************************************************//
153 //**************************************************************************//
154 // Input media streaming & demultiplexer:
155 //**************************************************************************//
157 static int max_framesize=0;
159 #include "stream/stream.h"
160 #include "libmpdemux/demuxer.h"
161 #include "libmpdemux/stheader.h"
163 #ifdef CONFIG_DVDREAD
164 #include "stream/stream_dvd.h"
165 #endif
166 #include "stream/stream_dvdnav.h"
168 #include "libmpcodecs/dec_audio.h"
169 #include "libmpcodecs/dec_video.h"
170 #include "libmpcodecs/mp_image.h"
171 #include "libmpcodecs/vf.h"
172 #include "libmpcodecs/vd.h"
174 #include "mixer.h"
176 #include "mp_core.h"
177 #include "options.h"
178 #include "defaultopts.h"
180 static const char help_text[]=_(
181 "Usage: mplayer [options] [url|path/]filename\n"
182 "\n"
183 "Basic options: (complete list in the man page)\n"
184 " -vo <drv> select video output driver ('-vo help' for a list)\n"
185 " -ao <drv> select audio output driver ('-ao help' for a list)\n"
186 #ifdef CONFIG_VCD
187 " vcd://<trackno> play (S)VCD (Super Video CD) track (raw device, no mount)\n"
188 #endif
189 #ifdef CONFIG_DVDREAD
190 " dvd://<titleno> play DVD title from device instead of plain file\n"
191 #endif
192 " -alang/-slang select DVD audio/subtitle language (by 2-char country code)\n"
193 " -ss <position> seek to given (seconds or hh:mm:ss) position\n"
194 " -nosound do not play sound\n"
195 " -fs fullscreen playback (or -vm, -zoom, details in the man page)\n"
196 " -x <x> -y <y> set display resolution (for use with -vm or -zoom)\n"
197 " -sub <file> specify subtitle file to use (also see -subfps, -subdelay)\n"
198 " -playlist <file> specify playlist file\n"
199 " -vid x -aid y select video (x) and audio (y) stream to play\n"
200 " -fps x -srate y change video (x fps) and audio (y Hz) rate\n"
201 " -pp <quality> enable postprocessing filter (details in the man page)\n"
202 " -framedrop enable frame dropping (for slow machines)\n"
203 "\n"
204 "Basic keys: (complete list in the man page, also check input.conf)\n"
205 " <- or -> seek backward/forward 10 seconds\n"
206 " down or up seek backward/forward 1 minute\n"
207 " pgdown or pgup seek backward/forward 10 minutes\n"
208 " < or > step backward/forward in playlist\n"
209 " p or SPACE pause movie (press any key to continue)\n"
210 " q or ESC stop playing and quit program\n"
211 " + or - adjust audio delay by +/- 0.1 second\n"
212 " o cycle OSD mode: none / seekbar / seekbar + timer\n"
213 " * or / increase or decrease PCM volume\n"
214 " x or z adjust subtitle delay by +/- 0.1 second\n"
215 " r or t adjust subtitle position up/down, also see -vf expand\n"
216 "\n"
217 " * * * SEE THE MAN PAGE FOR DETAILS, FURTHER (ADVANCED) OPTIONS AND KEYS * * *\n"
218 "\n");
221 #define Exit_SIGILL_RTCpuSel _(\
222 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
223 " It may be a bug in our new runtime CPU-detection code...\n"\
224 " Please read DOCS/HTML/en/bugreports.html.\n")
226 #define Exit_SIGILL _(\
227 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
228 " It usually happens when you run it on a CPU different than the one it was\n"\
229 " compiled/optimized for.\n"\
230 " Verify this!\n")
232 #define Exit_SIGSEGV_SIGFPE _(\
233 "- MPlayer crashed by bad usage of CPU/FPU/RAM.\n"\
234 " Recompile MPlayer with --enable-debug and make a 'gdb' backtrace and\n"\
235 " disassembly. Details in DOCS/HTML/en/bugreports_what.html#bugreports_crash.\n")
237 #define Exit_SIGCRASH _(\
238 "- MPlayer crashed. This shouldn't happen.\n"\
239 " It can be a bug in the MPlayer code _or_ in your drivers _or_ in your\n"\
240 " gcc version. If you think it's MPlayer's fault, please read\n"\
241 " DOCS/HTML/en/bugreports.html and follow the instructions there. We can't and\n"\
242 " won't help unless you provide this information when reporting a possible bug.\n")
244 #define SystemTooSlow _("\n\n"\
245 " ************************************************\n"\
246 " **** Your system is too SLOW to play this! ****\n"\
247 " ************************************************\n\n"\
248 "Possible reasons, problems, workarounds:\n"\
249 "- Most common: broken/buggy _audio_ driver\n"\
250 " - Try -ao sdl or use the OSS emulation of ALSA.\n"\
251 " - Experiment with different values for -autosync, 30 is a good start.\n"\
252 "- Slow video output\n"\
253 " - Try a different -vo driver (-vo help for a list) or try -framedrop!\n"\
254 "- Slow CPU\n"\
255 " - Don't try to play a big DVD/DivX on a slow CPU! Try some of the lavdopts,\n"\
256 " e.g. -vfm ffmpeg -lavdopts lowres=1:fast:skiploopfilter=all.\n"\
257 "- Broken file\n"\
258 " - Try various combinations of -nobps -ni -forceidx -mc 0.\n"\
259 "- Slow media (NFS/SMB mounts, DVD, VCD etc)\n"\
260 " - Try -cache 8192.\n"\
261 "- Are you using -cache to play a non-interleaved AVI file?\n"\
262 " - Try -nocache.\n"\
263 "Read DOCS/HTML/en/video.html for tuning/speedup tips.\n"\
264 "If none of this helps you, read DOCS/HTML/en/bugreports.html.\n\n")
267 //**************************************************************************//
268 //**************************************************************************//
270 #include "mp_fifo.h"
272 // benchmark:
273 double video_time_usage=0;
274 double vout_time_usage=0;
275 static double audio_time_usage=0;
276 static int total_time_usage_start=0;
277 static int total_frame_cnt=0;
278 static int drop_frame_cnt=0; // total number of dropped frames
280 // options:
281 static int output_quality=0;
283 // seek:
284 static double seek_to_sec;
285 static off_t seek_to_byte=0;
286 static off_t step_sec=0;
288 static m_time_size_t end_at = { .type = END_AT_NONE, .pos = 0 };
290 // codecs:
291 char **audio_codec_list=NULL; // override audio codec
292 char **video_codec_list=NULL; // override video codec
293 char **audio_fm_list=NULL; // override audio codec family
294 char **video_fm_list=NULL; // override video codec family
296 // this dvdsub_id was selected via slang
297 // use this to allow dvdnav to follow -slang across stream resets,
298 // in particular the subtitle ID for a language changes
299 int dvdsub_lang_id;
300 int vobsub_id=-1;
301 static char* spudec_ifo=NULL;
302 int forced_subs_only=0;
303 int file_filter=1;
305 // cache2:
306 int stream_cache_size=-1;
308 // dump:
309 int stream_dump_type=0;
311 // A-V sync:
312 static float default_max_pts_correction=-1;//0.01f;
313 float audio_delay=0;
314 static int ignore_start=0;
316 double force_fps=0;
317 static int force_srate=0;
318 int frame_dropping=0; // option 0=no drop 1= drop vo 2= drop decode
319 static int play_n_frames=-1;
320 static int play_n_frames_mf=-1;
322 // sub:
323 char *font_name=NULL;
324 char *sub_font_name=NULL;
325 extern int font_fontconfig;
326 float font_factor=0.75;
327 float sub_delay=0;
328 float sub_fps=0;
329 int subcc_enabled=0;
330 int suboverlap_enabled = 1;
332 #include "sub/ass_mp.h"
334 char* current_module=NULL; // for debugging
337 // ---
339 #ifdef CONFIG_MENU
340 #include "m_struct.h"
341 #include "libmenu/menu.h"
342 static const vf_info_t* const libmenu_vfs[] = {
343 &vf_info_menu,
344 NULL
346 static vf_instance_t* vf_menu = NULL;
347 int use_menu = 0;
348 static char* menu_cfg = NULL;
349 static char* menu_root = "main";
350 #endif
353 edl_record_ptr edl_records = NULL; ///< EDL entries memory area
354 edl_record_ptr next_edl_record = NULL; ///< only for traversing edl_records
355 FILE* edl_fd = NULL; ///< fd to write to when in -edlout mode.
356 int use_filedir_conf;
357 int use_filename_title;
359 #include "mpcommon.h"
360 #include "command.h"
362 #include "metadata.h"
364 const void *mpctx_get_video_out(MPContext *mpctx)
366 return mpctx->video_out;
369 void *mpctx_get_demuxer(MPContext *mpctx)
371 return mpctx->demuxer;
374 void *mpctx_get_playtree_iter(MPContext *mpctx)
376 return mpctx->playtree_iter;
379 void *mpctx_get_mixer(MPContext *mpctx)
381 return &mpctx->mixer;
384 int mpctx_get_global_sub_size(MPContext *mpctx)
386 return mpctx->global_sub_size;
389 int mpctx_get_osd_function(MPContext *mpctx)
391 return mpctx->osd_function;
394 static float get_relative_time(struct MPContext *mpctx)
396 unsigned int new_time = GetTimer();
397 unsigned int delta = new_time - mpctx->last_time;
398 mpctx->last_time = new_time;
399 return delta * 0.000001;
402 static int is_valid_metadata_type(struct MPContext *mpctx, metadata_t type) {
403 switch (type)
405 /* check for valid video stream */
406 case META_VIDEO_CODEC:
407 case META_VIDEO_BITRATE:
408 case META_VIDEO_RESOLUTION:
410 if (!mpctx->sh_video)
411 return 0;
412 break;
415 /* check for valid audio stream */
416 case META_AUDIO_CODEC:
417 case META_AUDIO_BITRATE:
418 case META_AUDIO_SAMPLES:
420 if (!mpctx->sh_audio)
421 return 0;
422 break;
425 /* check for valid demuxer */
426 case META_INFO_TITLE:
427 case META_INFO_ARTIST:
428 case META_INFO_ALBUM:
429 case META_INFO_YEAR:
430 case META_INFO_COMMENT:
431 case META_INFO_TRACK:
432 case META_INFO_GENRE:
434 if (!mpctx->demuxer)
435 return 0;
436 break;
439 default:
440 break;
443 return 1;
446 static char *get_demuxer_info(struct MPContext *mpctx, char *tag) {
447 char **info = mpctx->demuxer->info;
448 int n;
450 if (!info || !tag)
451 return talloc_strdup(NULL, "");
453 for (n = 0; info[2*n] != NULL ; n++)
454 if (!strcasecmp (info[2*n], tag))
455 break;
457 return talloc_strdup(NULL, info[2*n+1] ? info[2*n+1] : "");
460 char *get_metadata(struct MPContext *mpctx, metadata_t type)
462 sh_audio_t * const sh_audio = mpctx->sh_audio;
463 sh_video_t * const sh_video = mpctx->sh_video;
465 if (!is_valid_metadata_type(mpctx, type))
466 return NULL;
468 switch (type) {
469 case META_NAME:
470 return talloc_strdup(NULL, mp_basename(mpctx->filename));
471 case META_VIDEO_CODEC:
472 if (sh_video->format == 0x10000001)
473 return talloc_strdup(NULL, "mpeg1");
474 else if (sh_video->format == 0x10000002)
475 return talloc_strdup(NULL, "mpeg2");
476 else if (sh_video->format == 0x10000004)
477 return talloc_strdup(NULL, "mpeg4");
478 else if (sh_video->format == 0x10000005)
479 return talloc_strdup(NULL, "h264");
480 else if (sh_video->format >= 0x20202020)
481 return talloc_asprintf(NULL, "%.4s", (char *) &sh_video->format);
482 else
483 return talloc_asprintf(NULL, "0x%08X", sh_video->format);
484 case META_VIDEO_BITRATE:
485 return talloc_asprintf(NULL, "%d kbps",
486 (int) (sh_video->i_bps * 8 / 1024));
487 case META_VIDEO_RESOLUTION:
488 return talloc_asprintf(NULL, "%d x %d", sh_video->disp_w,
489 sh_video->disp_h);
490 case META_AUDIO_CODEC:
491 if (sh_audio->codec && sh_audio->codec->name)
492 return talloc_strdup(NULL, sh_audio->codec->name);
493 return talloc_strdup(NULL, "");
494 case META_AUDIO_BITRATE:
495 return talloc_asprintf(NULL, "%d kbps",
496 (int) (sh_audio->i_bps * 8/1000));
497 case META_AUDIO_SAMPLES:
498 return talloc_asprintf(NULL, "%d Hz, %d ch.", sh_audio->samplerate,
499 sh_audio->channels);
501 /* check for valid demuxer */
502 case META_INFO_TITLE:
503 return get_demuxer_info(mpctx, "Title");
505 case META_INFO_ARTIST:
506 return get_demuxer_info(mpctx, "Artist");
508 case META_INFO_ALBUM:
509 return get_demuxer_info(mpctx, "Album");
511 case META_INFO_YEAR:
512 return get_demuxer_info(mpctx, "Year");
514 case META_INFO_COMMENT:
515 return get_demuxer_info(mpctx, "Comment");
517 case META_INFO_TRACK:
518 return get_demuxer_info(mpctx, "Track");
520 case META_INFO_GENRE:
521 return get_demuxer_info(mpctx, "Genre");
523 default:
524 break;
527 return talloc_strdup(NULL, "");
530 static void print_file_properties(struct MPContext *mpctx, const char *filename)
532 double start_pts = MP_NOPTS_VALUE;
533 double video_start_pts = MP_NOPTS_VALUE;
534 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_FILENAME=%s\n",
535 filename_recode(filename));
536 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_DEMUXER=%s\n", mpctx->demuxer->desc->name);
537 if (mpctx->sh_video) {
538 /* Assume FOURCC if all bytes >= 0x20 (' ') */
539 if (mpctx->sh_video->format >= 0x20202020)
540 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=%.4s\n", (char *)&mpctx->sh_video->format);
541 else
542 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=0x%08X\n", mpctx->sh_video->format);
543 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_BITRATE=%d\n", mpctx->sh_video->i_bps*8);
544 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_WIDTH=%d\n", mpctx->sh_video->disp_w);
545 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_HEIGHT=%d\n", mpctx->sh_video->disp_h);
546 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FPS=%5.3f\n", mpctx->sh_video->fps);
547 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_ASPECT=%1.4f\n", mpctx->sh_video->aspect);
548 video_start_pts = ds_get_next_pts(mpctx->d_video);
550 if (mpctx->sh_audio) {
551 /* Assume FOURCC if all bytes >= 0x20 (' ') */
552 if (mpctx->sh_audio->format >= 0x20202020)
553 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_FORMAT=%.4s\n", (char *)&mpctx->sh_audio->format);
554 else
555 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_FORMAT=%d\n", mpctx->sh_audio->format);
556 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_BITRATE=%d\n", mpctx->sh_audio->i_bps*8);
557 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_RATE=%d\n", mpctx->sh_audio->samplerate);
558 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_NCH=%d\n", mpctx->sh_audio->channels);
559 start_pts = ds_get_next_pts(mpctx->d_audio);
561 if (video_start_pts != MP_NOPTS_VALUE) {
562 if (start_pts == MP_NOPTS_VALUE || !mpctx->sh_audio ||
563 (mpctx->sh_video && video_start_pts < start_pts))
564 start_pts = video_start_pts;
566 if (start_pts != MP_NOPTS_VALUE)
567 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_START_TIME=%.2f\n", start_pts);
568 else
569 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_START_TIME=unknown\n");
570 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_LENGTH=%.2f\n", get_time_length(mpctx));
571 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_SEEKABLE=%d\n",
572 mpctx->stream->seek && (!mpctx->demuxer || mpctx->demuxer->seekable));
573 if (mpctx->demuxer) {
574 if (mpctx->demuxer->num_chapters == 0)
575 stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_NUM_CHAPTERS, &mpctx->demuxer->num_chapters);
576 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_CHAPTERS=%d\n", mpctx->demuxer->num_chapters);
580 /// step size of mixer changes
581 int volstep = 3;
583 #ifdef CONFIG_DVDNAV
584 static void mp_dvdnav_context_free(MPContext *ctx){
585 if (ctx->nav_smpi) free_mp_image(ctx->nav_smpi);
586 ctx->nav_smpi = NULL;
587 free(ctx->nav_buffer);
588 ctx->nav_buffer = NULL;
589 ctx->nav_start = NULL;
590 ctx->nav_in_size = 0;
592 #endif
594 static void uninit_subs(struct demuxer *demuxer)
596 for (int i = 0; i < MAX_S_STREAMS; i++) {
597 struct sh_sub *sh = demuxer->s_streams[i];
598 if (sh && sh->initialized)
599 sub_uninit(sh);
603 void uninit_player(struct MPContext *mpctx, unsigned int mask){
604 mask &= mpctx->initialized_flags;
606 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n*** uninit(0x%X)\n",mask);
608 if(mask&INITIALIZED_ACODEC){
609 mpctx->initialized_flags&=~INITIALIZED_ACODEC;
610 current_module="uninit_acodec";
611 if(mpctx->sh_audio) uninit_audio(mpctx->sh_audio);
612 mpctx->sh_audio=NULL;
613 mpctx->mixer.afilter = NULL;
616 if (mask & INITIALIZED_SUB) {
617 mpctx->initialized_flags &= ~INITIALIZED_SUB;
618 if (mpctx->d_sub->sh)
619 sub_switchoff(mpctx->d_sub->sh, mpctx->osd);
622 if(mask&INITIALIZED_VCODEC){
623 mpctx->initialized_flags&=~INITIALIZED_VCODEC;
624 current_module="uninit_vcodec";
625 if(mpctx->sh_video) uninit_video(mpctx->sh_video);
626 mpctx->sh_video=NULL;
627 #ifdef CONFIG_MENU
628 vf_menu=NULL;
629 #endif
632 if(mask&INITIALIZED_DEMUXER){
633 mpctx->initialized_flags&=~INITIALIZED_DEMUXER;
634 current_module="free_demuxer";
635 if (mpctx->num_sources) {
636 mpctx->demuxer = mpctx->sources[0].demuxer;
637 for (int i = 1; i < mpctx->num_sources; i++) {
638 uninit_subs(mpctx->sources[i].demuxer);
639 free_stream(mpctx->sources[i].stream);
640 free_demuxer(mpctx->sources[i].demuxer);
643 talloc_free(mpctx->sources);
644 mpctx->sources = NULL;
645 mpctx->num_sources = 0;
646 talloc_free(mpctx->timeline);
647 mpctx->timeline = NULL;
648 mpctx->num_timeline_parts = 0;
649 talloc_free(mpctx->chapters);
650 mpctx->chapters = NULL;
651 mpctx->num_chapters = 0;
652 mpctx->video_offset = 0;
653 if(mpctx->demuxer){
654 mpctx->stream=mpctx->demuxer->stream;
655 uninit_subs(mpctx->demuxer);
656 free_demuxer(mpctx->demuxer);
658 mpctx->demuxer=NULL;
661 // kill the cache process:
662 if(mask&INITIALIZED_STREAM){
663 mpctx->initialized_flags&=~INITIALIZED_STREAM;
664 current_module="uninit_stream";
665 if(mpctx->stream) free_stream(mpctx->stream);
666 mpctx->stream=NULL;
669 if(mask&INITIALIZED_VO){
670 mpctx->initialized_flags&=~INITIALIZED_VO;
671 current_module="uninit_vo";
672 vo_destroy(mpctx->video_out);
673 mpctx->video_out=NULL;
674 #ifdef CONFIG_DVDNAV
675 mp_dvdnav_context_free(mpctx);
676 #endif
679 // Must be after libvo uninit, as few vo drivers (svgalib) have tty code.
680 if(mask&INITIALIZED_GETCH2){
681 mpctx->initialized_flags&=~INITIALIZED_GETCH2;
682 current_module="uninit_getch2";
683 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[uninit getch2]]]\n");
684 // restore terminal:
685 getch2_disable();
688 if(mask&INITIALIZED_VOBSUB){
689 mpctx->initialized_flags&=~INITIALIZED_VOBSUB;
690 current_module="uninit_vobsub";
691 if(vo_vobsub) vobsub_close(vo_vobsub);
692 vo_vobsub=NULL;
695 if (mask&INITIALIZED_SPUDEC){
696 mpctx->initialized_flags&=~INITIALIZED_SPUDEC;
697 current_module="uninit_spudec";
698 spudec_free(vo_spudec);
699 vo_spudec=NULL;
702 if(mask&INITIALIZED_AO){
703 mpctx->initialized_flags&=~INITIALIZED_AO;
704 current_module="uninit_ao";
705 if (mpctx->edl_muted) mixer_mute(&mpctx->mixer);
706 if (mpctx->ao)
707 ao_uninit(mpctx->ao, mpctx->stop_play != AT_END_OF_FILE);
708 mpctx->ao = NULL;
711 current_module=NULL;
714 void exit_player_with_rc(struct MPContext *mpctx, enum exit_reason how, int rc)
716 if (mpctx->user_muted && !mpctx->edl_muted) mixer_mute(&mpctx->mixer);
717 uninit_player(mpctx, INITIALIZED_ALL);
718 #if defined(__MINGW32__) || defined(__CYGWIN__)
719 timeEndPeriod(1);
720 #endif
721 #ifdef CONFIG_X11
722 vo_uninit(mpctx->x11_state); // Close the X11 connection (if any is open).
723 #endif
725 current_module="uninit_input";
726 mp_input_uninit(mpctx->input);
727 #ifdef CONFIG_MENU
728 if (use_menu)
729 menu_uninit();
730 #endif
732 #ifdef CONFIG_FREETYPE
733 current_module="uninit_font";
734 if (mpctx->osd && mpctx->osd->sub_font != vo_font)
735 free_font_desc(mpctx->osd->sub_font);
736 free_font_desc(vo_font);
737 vo_font = NULL;
738 done_freetype();
739 #endif
740 osd_free(mpctx->osd);
742 #ifdef CONFIG_ASS
743 ass_library_done(ass_library);
744 ass_library = NULL;
745 #endif
747 current_module="exit_player";
749 // free mplayer config
750 if(mpctx->mconfig)
751 m_config_free(mpctx->mconfig);
752 mpctx->mconfig = NULL;
754 if(mpctx->playtree_iter)
755 play_tree_iter_free(mpctx->playtree_iter);
756 mpctx->playtree_iter = NULL;
757 if(mpctx->playtree)
758 play_tree_free(mpctx->playtree, 1);
759 mpctx->playtree = NULL;
761 talloc_free(mpctx->key_fifo);
763 free(edl_records); // free mem allocated for EDL
764 edl_records = NULL;
765 switch(how) {
766 case EXIT_QUIT:
767 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Quit");
768 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=QUIT\n");
769 break;
770 case EXIT_EOF:
771 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","End of file");
772 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=EOF\n");
773 break;
774 case EXIT_ERROR:
775 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Fatal error");
776 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=ERROR\n");
777 break;
778 default:
779 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=NONE\n");
781 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"max framesize was %d bytes\n",max_framesize);
783 exit(rc);
786 static void exit_player(struct MPContext *mpctx, enum exit_reason how)
788 exit_player_with_rc(mpctx, how, 1);
791 #ifndef __MINGW32__
792 static void child_sighandler(int x){
793 pid_t pid;
794 while((pid=waitpid(-1,NULL,WNOHANG)) > 0);
796 #endif
798 #ifdef CONFIG_CRASH_DEBUG
799 static char *prog_path;
800 static int crash_debug = 0;
801 #endif
803 static void exit_sighandler(int x){
804 static int sig_count=0;
805 #ifdef CONFIG_CRASH_DEBUG
806 if (!crash_debug || x != SIGTRAP)
807 #endif
808 ++sig_count;
809 if(sig_count==5)
811 /* We're crashing bad and can't uninit cleanly :(
812 * by popular request, we make one last (dirty)
813 * effort to restore the user's
814 * terminal. */
815 getch2_disable();
816 exit(1);
818 if(sig_count==6) exit(1);
819 if(sig_count>6){
820 // can't stop :(
821 #ifndef __MINGW32__
822 kill(getpid(),SIGKILL);
823 #endif
825 mp_msg(MSGT_CPLAYER, MSGL_FATAL, "\n");
826 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,
827 "\nMPlayer interrupted by signal %d in module: %s\n", x,
828 current_module ? current_module : "unknown");
829 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SIGNAL=%d\n", x);
830 if(sig_count<=1)
831 switch(x){
832 case SIGINT:
833 case SIGPIPE:
834 case SIGQUIT:
835 case SIGTERM:
836 case SIGKILL:
837 async_quit_request = 1;
838 return; // killed from keyboard (^C) or killed [-9]
839 case SIGILL:
840 #if CONFIG_RUNTIME_CPUDETECT
841 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL_RTCpuSel);
842 #else
843 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL);
844 #endif
845 case SIGFPE:
846 case SIGSEGV:
847 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGSEGV_SIGFPE);
848 default:
849 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGCRASH);
850 #ifdef CONFIG_CRASH_DEBUG
851 if (crash_debug) {
852 int gdb_pid;
853 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forking...\n");
854 gdb_pid = fork();
855 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forked...\n");
856 if (gdb_pid == 0) { // We are the child
857 char spid[20];
858 snprintf(spid, sizeof(spid), "%i", getppid());
859 getch2_disable(); // allow terminal to work properly with gdb
860 if (execlp("gdb", "gdb", prog_path, spid, "-ex", "bt", NULL) == -1)
861 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't start gdb\n");
862 } else if (gdb_pid < 0)
863 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't fork\n");
864 else {
865 waitpid(gdb_pid, NULL, 0);
867 if (x == SIGTRAP) return;
869 #endif
871 getch2_disable();
872 exit(1);
875 #include "cfg-mplayer.h"
877 static int cfg_include(m_option_t *conf, char *filename)
879 return m_config_parse_config_file(conf->priv, filename);
882 static void parse_cfgfiles(struct MPContext *mpctx, m_config_t* conf)
884 struct MPOpts *opts = &mpctx->opts;
885 char *conffile;
886 int conffile_fd;
887 if (!(opts->noconfig & 2) &&
888 m_config_parse_config_file(conf, MPLAYER_CONFDIR "/mplayer.conf") < 0)
889 exit_player(mpctx, EXIT_NONE);
890 if ((conffile = get_path("")) == NULL) {
891 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"Cannot find HOME directory.\n");
892 } else {
893 #ifdef __MINGW32__
894 mkdir(conffile);
895 #else
896 mkdir(conffile, 0777);
897 #endif
898 free(conffile);
899 if ((conffile = get_path("config")) == NULL) {
900 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"get_path(\"config\") problem\n");
901 } else {
902 if ((conffile_fd = open(conffile, O_CREAT | O_EXCL | O_WRONLY, 0666)) != -1) {
903 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Creating config file: %s\n", conffile);
904 write(conffile_fd, default_config, strlen(default_config));
905 close(conffile_fd);
907 if (!(opts->noconfig & 1) &&
908 m_config_parse_config_file(conf, conffile) < 0)
909 exit_player(mpctx, EXIT_NONE);
910 free(conffile);
915 #define PROFILE_CFG_PROTOCOL "protocol."
917 static void load_per_protocol_config (m_config_t* conf, const char *const file)
919 char *str;
920 char protocol[strlen (PROFILE_CFG_PROTOCOL) + strlen (file) + 1];
921 m_profile_t *p;
923 /* does filename actually uses a protocol ? */
924 str = strstr (file, "://");
925 if (!str)
926 return;
928 sprintf (protocol, "%s%s", PROFILE_CFG_PROTOCOL, file);
929 protocol[strlen (PROFILE_CFG_PROTOCOL)+strlen(file)-strlen(str)] = '\0';
930 p = m_config_get_profile (conf, protocol);
931 if (p)
933 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading protocol-related profile '%s'\n", protocol);
934 m_config_set_profile(conf,p);
938 #define PROFILE_CFG_EXTENSION "extension."
940 static void load_per_extension_config (m_config_t* conf, const char *const file)
942 char *str;
943 char extension[strlen (PROFILE_CFG_EXTENSION) + 8];
944 m_profile_t *p;
946 /* does filename actually have an extension ? */
947 str = strrchr (file, '.');
948 if (!str)
949 return;
951 sprintf (extension, PROFILE_CFG_EXTENSION);
952 strncat (extension, ++str, 7);
953 p = m_config_get_profile (conf, extension);
954 if (p)
956 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", extension);
957 m_config_set_profile(conf,p);
961 #define PROFILE_CFG_VO "vo."
962 #define PROFILE_CFG_AO "ao."
964 static void load_per_output_config (m_config_t* conf, char *cfg, char *out)
966 char profile[strlen (cfg) + strlen (out) + 1];
967 m_profile_t *p;
969 sprintf (profile, "%s%s", cfg, out);
970 p = m_config_get_profile (conf, profile);
971 if (p)
973 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", profile);
974 m_config_set_profile(conf,p);
979 * Tries to load a config file
980 * @return 0 if file was not found, 1 otherwise
982 static int try_load_config(m_config_t *conf, const char *file)
984 struct stat st;
985 if (stat(file, &st))
986 return 0;
987 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Loading config '%s'\n", file);
988 m_config_parse_config_file (conf, file);
989 return 1;
992 static void load_per_file_config (m_config_t* conf, const char *const file)
994 char *confpath;
995 char cfg[PATH_MAX];
996 const char *name;
998 if (strlen(file) > PATH_MAX - 14) {
999 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Filename is too long, can not load file or directory specific config files\n");
1000 return;
1002 sprintf (cfg, "%s.conf", file);
1004 name = mp_basename(cfg);
1005 if (use_filedir_conf) {
1006 char dircfg[PATH_MAX];
1007 strcpy(dircfg, cfg);
1008 strcpy(dircfg + (name - cfg), "mplayer.conf");
1009 try_load_config(conf, dircfg);
1011 if (try_load_config(conf, cfg))
1012 return;
1015 if ((confpath = get_path (name)) != NULL)
1017 try_load_config(conf, confpath);
1019 free (confpath);
1023 /* When libmpdemux performs a blocking operation (network connection or
1024 * cache filling) if the operation fails we use this function to check
1025 * if it was interrupted by the user.
1026 * The function returns a new value for eof. */
1027 static int libmpdemux_was_interrupted(struct MPContext *mpctx, int stop_play)
1029 mp_cmd_t* cmd;
1030 if((cmd = mp_input_get_cmd(mpctx->input, 0, 0)) != NULL) {
1031 switch(cmd->id) {
1032 case MP_CMD_QUIT:
1033 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
1034 case MP_CMD_PLAY_TREE_STEP: {
1035 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_ENTRY : PT_PREV_ENTRY;
1036 mpctx->play_tree_step = (cmd->args[0].v.i == 0) ? 1 : cmd->args[0].v.i;
1037 } break;
1038 case MP_CMD_PLAY_TREE_UP_STEP: {
1039 stop_play = (cmd->args[0].v.i > 0) ? PT_UP_NEXT : PT_UP_PREV;
1040 } break;
1041 case MP_CMD_PLAY_ALT_SRC_STEP: {
1042 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_SRC : PT_PREV_SRC;
1043 } break;
1045 mp_cmd_free(cmd);
1047 return stop_play;
1050 static int playtree_add_playlist(struct MPContext *mpctx, play_tree_t* entry)
1052 play_tree_add_bpf(entry,mpctx->filename);
1055 if(!entry) {
1056 entry = mpctx->playtree_iter->tree;
1057 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1058 return PT_NEXT_ENTRY;
1060 if(mpctx->playtree_iter->tree == entry ) { // Loop with a single file
1061 if(play_tree_iter_up_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1062 return PT_NEXT_ENTRY;
1065 play_tree_remove(entry,1,1);
1066 return PT_NEXT_SRC;
1068 play_tree_insert_entry(mpctx->playtree_iter->tree,entry);
1069 play_tree_set_params_from(entry,mpctx->playtree_iter->tree);
1070 entry = mpctx->playtree_iter->tree;
1071 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1072 return PT_NEXT_ENTRY;
1074 play_tree_remove(entry,1,1);
1076 return PT_NEXT_SRC;
1079 void add_subtitles(struct MPContext *mpctx, char *filename, float fps, int noerr)
1081 struct MPOpts *opts = &mpctx->opts;
1082 sub_data *subd = NULL;
1083 struct ass_track *asst = NULL;
1084 bool is_native_ass = false;
1086 if (filename == NULL || mpctx->set_of_sub_size >= MAX_SUBTITLE_FILES)
1087 return;
1089 #ifdef CONFIG_ASS
1090 if (opts->ass_enabled) {
1091 #ifdef CONFIG_ICONV
1092 asst = mp_ass_read_stream(ass_library, filename, sub_cp);
1093 #else
1094 asst = mp_ass_read_stream(ass_library, filename, 0);
1095 #endif
1096 is_native_ass = asst;
1097 if (!asst) {
1098 subd = sub_read_file(filename, fps, &mpctx->opts);
1099 if (subd) {
1100 asst = mp_ass_read_subdata(ass_library, subd, fps);
1101 sub_free(subd);
1102 subd = NULL;
1105 } else
1106 #endif
1107 subd = sub_read_file(filename, fps, &mpctx->opts);
1110 if (!asst && !subd) {
1111 mp_tmsg(MSGT_CPLAYER, noerr ? MSGL_WARN : MSGL_ERR,
1112 "Cannot load subtitles: %s\n", filename_recode(filename));
1113 return;
1116 mpctx->set_of_ass_tracks[mpctx->set_of_sub_size] = asst;
1117 mpctx->set_of_subtitles[mpctx->set_of_sub_size] = subd;
1118 mpctx->track_was_native_ass[mpctx->set_of_sub_size] = is_native_ass;
1119 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_ID=%d\n", mpctx->set_of_sub_size);
1120 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_FILENAME=%s\n",
1121 filename_recode(filename));
1122 ++mpctx->set_of_sub_size;
1123 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "SUB: Added subtitle file (%d): %s\n", mpctx->set_of_sub_size,
1124 filename_recode(filename));
1127 void init_vo_spudec(struct MPContext *mpctx)
1129 spudec_free(vo_spudec);
1130 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
1131 vo_spudec = NULL;
1133 // we currently can't work without video stream
1134 if (!mpctx->sh_video)
1135 return;
1137 if (spudec_ifo) {
1138 unsigned int palette[16], width, height;
1139 current_module="spudec_init_vobsub";
1140 if (vobsub_parse_ifo(NULL,spudec_ifo, palette, &width, &height, 1, -1, NULL) >= 0)
1141 vo_spudec=spudec_new_scaled(palette, width, height, NULL, 0);
1144 #ifdef CONFIG_DVDREAD
1145 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVD) {
1146 current_module="spudec_init_dvdread";
1147 vo_spudec=spudec_new_scaled(((dvd_priv_t *)(mpctx->stream->priv))->cur_pgc->palette,
1148 mpctx->sh_video->disp_w, mpctx->sh_video->disp_h,
1149 NULL, 0);
1151 #endif
1153 #ifdef CONFIG_DVDNAV
1154 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVDNAV) {
1155 unsigned int *palette = mp_dvdnav_get_spu_clut(mpctx->stream);
1156 current_module="spudec_init_dvdnav";
1157 vo_spudec=spudec_new_scaled(palette, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, NULL, 0);
1159 #endif
1161 if (vo_spudec==NULL) {
1162 sh_sub_t *sh = mpctx->d_sub->sh;
1163 current_module="spudec_init_normal";
1164 vo_spudec=spudec_new_scaled(NULL, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, sh->extradata, sh->extradata_len);
1165 spudec_set_font_factor(vo_spudec,font_factor);
1168 if (vo_spudec!=NULL) {
1169 mpctx->initialized_flags|=INITIALIZED_SPUDEC;
1170 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
1175 * In Mac OS X the SDL-lib is built upon Cocoa. The easiest way to
1176 * make it all work is to use the builtin SDL-bootstrap code, which
1177 * will be done automatically by replacing our main() if we include SDL.h.
1179 #if defined(__APPLE__) && defined(CONFIG_SDL)
1180 #ifdef CONFIG_SDL_SDL_H
1181 #include <SDL/SDL.h>
1182 #else
1183 #include <SDL.h>
1184 #endif
1185 #endif
1188 * \brief append a formatted string
1189 * \param buf buffer to print into
1190 * \param pos position of terminating 0 in buf
1191 * \param len maximum number of characters in buf, not including terminating 0
1192 * \param format printf format string
1194 static void saddf(char *buf, unsigned *pos, int len, const char *format, ...)
1196 va_list va;
1197 va_start(va, format);
1198 *pos += vsnprintf(&buf[*pos], len - *pos, format, va);
1199 va_end(va);
1200 if (*pos >= len ) {
1201 buf[len] = 0;
1202 *pos = len;
1207 * \brief append time in the hh:mm:ss.f format
1208 * \param buf buffer to print into
1209 * \param pos position of terminating 0 in buf
1210 * \param len maximum number of characters in buf, not including terminating 0
1211 * \param time time value to convert/append
1213 static void sadd_hhmmssf(char *buf, unsigned *pos, int len, float time) {
1214 int64_t tenths = 10 * time;
1215 int f1 = tenths % 10;
1216 int ss = (tenths / 10) % 60;
1217 int mm = (tenths / 600) % 60;
1218 int hh = tenths / 36000;
1219 if (time <= 0) {
1220 saddf(buf, pos, len, "unknown");
1221 return;
1223 if (hh > 0)
1224 saddf(buf, pos, len, "%2d:", hh);
1225 if (hh > 0 || mm > 0)
1226 saddf(buf, pos, len, "%02d:", mm);
1227 saddf(buf, pos, len, "%02d.%1d", ss, f1);
1230 static void print_status(struct MPContext *mpctx, double a_pos, bool at_frame)
1232 struct MPOpts *opts = &mpctx->opts;
1233 sh_video_t * const sh_video = mpctx->sh_video;
1235 if (mpctx->sh_audio && a_pos == MP_NOPTS_VALUE)
1236 a_pos = playing_audio_pts(mpctx);
1237 if (mpctx->sh_audio && sh_video && at_frame) {
1238 mpctx->last_av_difference = a_pos - mpctx->video_pts - audio_delay;
1239 if (mpctx->time_frame > 0)
1240 mpctx->last_av_difference += mpctx->time_frame * opts->playback_speed;
1241 if (mpctx->last_av_difference > 0.5 && drop_frame_cnt > 50
1242 && !mpctx->drop_message_shown) {
1243 mp_tmsg(MSGT_AVSYNC,MSGL_WARN,SystemTooSlow);
1244 mpctx->drop_message_shown = true;
1247 if (opts->quiet)
1248 return;
1251 int width;
1252 char *line;
1253 unsigned pos = 0;
1254 get_screen_size();
1255 if (screen_width > 0)
1256 width = screen_width;
1257 else
1258 width = 80;
1259 #if defined(__MINGW32__) || defined(__CYGWIN__) || defined(__OS2__)
1260 /* Windows command line is broken (MinGW's rxvt works, but we
1261 * should not depend on that). */
1262 width--;
1263 #endif
1264 line = malloc(width + 1); // one additional char for the terminating null
1266 // Audio time
1267 if (mpctx->sh_audio) {
1268 saddf(line, &pos, width, "A:%6.1f ", a_pos);
1269 if (!sh_video) {
1270 float len = get_time_length(mpctx);
1271 saddf(line, &pos, width, "(");
1272 sadd_hhmmssf(line, &pos, width, a_pos);
1273 saddf(line, &pos, width, ") of %.1f (", len);
1274 sadd_hhmmssf(line, &pos, width, len);
1275 saddf(line, &pos, width, ") ");
1279 // Video time
1280 if (sh_video)
1281 saddf(line, &pos, width, "V:%6.1f ", mpctx->video_pts);
1283 // A-V sync
1284 if (mpctx->sh_audio && sh_video)
1285 saddf(line, &pos, width, "A-V:%7.3f ct:%7.3f ",
1286 mpctx->last_av_difference, mpctx->total_avsync_change);
1288 // Video stats
1289 if (sh_video)
1290 saddf(line, &pos, width, "%3d/%3d ",
1291 (int)sh_video->num_frames,
1292 (int)sh_video->num_frames_decoded);
1294 // CPU usage
1295 if (sh_video) {
1296 if (sh_video->timer > 0.5)
1297 saddf(line, &pos, width, "%2d%% %2d%% %4.1f%% ",
1298 (int)(100.0*video_time_usage*opts->playback_speed/(double)sh_video->timer),
1299 (int)(100.0*vout_time_usage*opts->playback_speed/(double)sh_video->timer),
1300 (100.0*audio_time_usage*opts->playback_speed/(double)sh_video->timer));
1301 else
1302 saddf(line, &pos, width, "??%% ??%% ??,?%% ");
1303 } else if (mpctx->sh_audio) {
1304 if (mpctx->delay > 0.5)
1305 saddf(line, &pos, width, "%4.1f%% ",
1306 100.0*audio_time_usage/(double)mpctx->delay);
1307 else
1308 saddf(line, &pos, width, "??,?%% ");
1311 // VO stats
1312 if (sh_video)
1313 saddf(line, &pos, width, "%d %d ", drop_frame_cnt, output_quality);
1315 #ifdef CONFIG_STREAM_CACHE
1316 // cache stats
1317 if (stream_cache_size > 0)
1318 saddf(line, &pos, width, "%d%% ", cache_fill_status(mpctx->stream));
1319 #endif
1321 // other
1322 if (opts->playback_speed != 1)
1323 saddf(line, &pos, width, "%4.2fx ", opts->playback_speed);
1325 // end
1326 if (erase_to_end_of_line) {
1327 line[pos] = 0;
1328 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s%s\r", line, erase_to_end_of_line);
1329 } else {
1330 memset(&line[pos], ' ', width - pos);
1331 line[width] = 0;
1332 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s\r", line);
1334 free(line);
1338 * \brief build a chain of audio filters that converts the input format
1339 * to the ao's format, taking into account the current playback_speed.
1340 * sh_audio describes the requested input format of the chain.
1341 * ao describes the requested output format of the chain.
1343 static int build_afilter_chain(struct MPContext *mpctx)
1345 struct sh_audio *sh_audio = mpctx->sh_audio;
1346 struct ao *ao = mpctx->ao;
1347 struct MPOpts *opts = &mpctx->opts;
1348 int new_srate;
1349 int result;
1350 if (!sh_audio)
1352 mpctx->mixer.afilter = NULL;
1353 return 0;
1355 if(af_control_any_rev(sh_audio->afilter,
1356 AF_CONTROL_PLAYBACK_SPEED | AF_CONTROL_SET,
1357 &opts->playback_speed)) {
1358 new_srate = sh_audio->samplerate;
1359 } else {
1360 new_srate = sh_audio->samplerate * opts->playback_speed;
1361 if (new_srate != ao->samplerate) {
1362 // limits are taken from libaf/af_resample.c
1363 if (new_srate < 8000)
1364 new_srate = 8000;
1365 if (new_srate > 192000)
1366 new_srate = 192000;
1367 opts->playback_speed = (float)new_srate / (float)sh_audio->samplerate;
1370 result = init_audio_filters(sh_audio, new_srate,
1371 &ao->samplerate, &ao->channels, &ao->format);
1372 mpctx->mixer.afilter = sh_audio->afilter;
1373 return result;
1377 typedef struct mp_osd_msg mp_osd_msg_t;
1378 struct mp_osd_msg {
1379 /// Previous message on the stack.
1380 mp_osd_msg_t* prev;
1381 /// Message text.
1382 char msg[128];
1383 int id,level,started;
1384 /// Display duration in ms.
1385 unsigned time;
1388 /// OSD message stack.
1389 static mp_osd_msg_t* osd_msg_stack = NULL;
1392 * \brief Add a message on the OSD message stack
1394 * If a message with the same id is already present in the stack
1395 * it is pulled on top of the stack, otherwise a new message is created.
1398 static void set_osd_msg_va(int id, int level, int time, const char *fmt,
1399 va_list ap)
1401 mp_osd_msg_t *msg,*last=NULL;
1402 int r;
1404 // look if the id is already in the stack
1405 for(msg = osd_msg_stack ; msg && msg->id != id ;
1406 last = msg, msg = msg->prev);
1407 // not found: alloc it
1408 if(!msg) {
1409 msg = calloc(1,sizeof(mp_osd_msg_t));
1410 msg->prev = osd_msg_stack;
1411 osd_msg_stack = msg;
1412 } else if(last) { // found, but it's not on top of the stack
1413 last->prev = msg->prev;
1414 msg->prev = osd_msg_stack;
1415 osd_msg_stack = msg;
1417 // write the msg
1418 r = vsnprintf(msg->msg, 128, fmt, ap);
1419 if(r >= 128) msg->msg[127] = 0;
1420 // set id and time
1421 msg->id = id;
1422 msg->level = level;
1423 msg->time = time;
1427 void set_osd_msg(int id, int level, int time, const char *fmt, ...)
1429 va_list ap;
1430 va_start(ap, fmt);
1431 set_osd_msg_va(id, level, time, fmt, ap);
1432 va_end(ap);
1435 void set_osd_tmsg(int id, int level, int time, const char *fmt, ...)
1437 va_list ap;
1438 va_start(ap, fmt);
1439 set_osd_msg_va(id, level, time, mp_gtext(fmt), ap);
1440 va_end(ap);
1445 * \brief Remove a message from the OSD stack
1447 * This function can be used to get rid of a message right away.
1451 void rm_osd_msg(int id) {
1452 mp_osd_msg_t *msg,*last=NULL;
1454 // Search for the msg
1455 for(msg = osd_msg_stack ; msg && msg->id != id ;
1456 last = msg, msg = msg->prev);
1457 if(!msg) return;
1459 // Detach it from the stack and free it
1460 if(last)
1461 last->prev = msg->prev;
1462 else
1463 osd_msg_stack = msg->prev;
1464 free(msg);
1468 * \brief Remove all messages from the OSD stack
1472 static void clear_osd_msgs(void) {
1473 mp_osd_msg_t* msg = osd_msg_stack, *prev = NULL;
1474 while(msg) {
1475 prev = msg->prev;
1476 free(msg);
1477 msg = prev;
1479 osd_msg_stack = NULL;
1483 * \brief Get the current message from the OSD stack.
1485 * This function decrements the message timer and destroys the old ones.
1486 * The message that should be displayed is returned (if any).
1490 static mp_osd_msg_t* get_osd_msg(struct MPContext *mpctx)
1492 struct MPOpts *opts = &mpctx->opts;
1493 mp_osd_msg_t *msg,*prev,*last = NULL;
1494 static unsigned last_update = 0;
1495 unsigned now = GetTimerMS();
1496 unsigned diff;
1497 char hidden_dec_done = 0;
1499 if (mpctx->osd_visible) {
1500 // 36000000 means max timed visibility is 1 hour into the future, if
1501 // the difference is greater assume it's wrapped around from below 0
1502 if (mpctx->osd_visible - now > 36000000) {
1503 mpctx->osd_visible = 0;
1504 vo_osd_progbar_type = -1; // disable
1505 vo_osd_changed(OSDTYPE_PROGBAR);
1506 mpctx->osd_function = mpctx->paused ? OSD_PAUSE : OSD_PLAY;
1509 if (mpctx->osd_show_percentage_until - now > 36000000)
1510 mpctx->osd_show_percentage_until = 0;
1512 if(!last_update) last_update = now;
1513 diff = now >= last_update ? now - last_update : 0;
1515 last_update = now;
1517 // Look for the first message in the stack with high enough level.
1518 for(msg = osd_msg_stack ; msg ; last = msg, msg = prev) {
1519 prev = msg->prev;
1520 if (msg->level > opts->osd_level && hidden_dec_done)
1521 continue;
1522 // The message has a high enough level or it is the first hidden one
1523 // in both cases we decrement the timer or kill it.
1524 if(!msg->started || msg->time > diff) {
1525 if(msg->started) msg->time -= diff;
1526 else msg->started = 1;
1527 // display it
1528 if (msg->level <= opts->osd_level)
1529 return msg;
1530 hidden_dec_done = 1;
1531 continue;
1533 // kill the message
1534 free(msg);
1535 if(last) {
1536 last->prev = prev;
1537 msg = last;
1538 } else {
1539 osd_msg_stack = prev;
1540 msg = NULL;
1543 // Nothing found
1544 return NULL;
1548 * \brief Display the OSD bar.
1550 * Display the OSD bar or fall back on a simple message.
1554 void set_osd_bar(struct MPContext *mpctx, int type,const char* name,double min,double max,double val) {
1555 struct MPOpts *opts = &mpctx->opts;
1556 if (opts->osd_level < 1)
1557 return;
1559 if(mpctx->sh_video) {
1560 mpctx->osd_visible = (GetTimerMS() + 1000) | 1;
1561 vo_osd_progbar_type = type;
1562 vo_osd_progbar_value = 256*(val-min)/(max-min);
1563 vo_osd_changed(OSDTYPE_PROGBAR);
1564 return;
1567 set_osd_msg(OSD_MSG_BAR, 1, opts->osd_duration, "%s: %d %%",
1568 name, ROUND(100*(val-min)/(max-min)));
1572 * \brief Display text subtitles on the OSD
1574 void set_osd_subtitle(struct MPContext *mpctx, subtitle *subs)
1576 int i;
1577 vo_sub = subs;
1578 vo_osd_changed(OSDTYPE_SUBTITLE);
1579 if (!mpctx->sh_video) {
1580 // reverse order, since newest set_osd_msg is displayed first
1581 for (i = SUB_MAX_TEXT - 1; i >= 0; i--) {
1582 if (!subs || i >= subs->lines || !subs->text[i])
1583 rm_osd_msg(OSD_MSG_SUB_BASE + i);
1584 else {
1585 // HACK: currently display time for each sub line except the last is set to 2 seconds.
1586 int display_time = i == subs->lines - 1 ? 180000 : 2000;
1587 set_osd_msg(OSD_MSG_SUB_BASE + i, 1, display_time, "%s", subs->text[i]);
1594 * \brief Update the OSD message line.
1596 * This function displays the current message on the vo OSD or on the term.
1597 * If the stack is empty and the OSD level is high enough the timer
1598 * is displayed (only on the vo OSD).
1602 static void update_osd_msg(struct MPContext *mpctx)
1604 struct MPOpts *opts = &mpctx->opts;
1605 mp_osd_msg_t *msg;
1606 struct osd_state *osd = mpctx->osd;
1607 char osd_text_timer[128];
1609 if (mpctx->add_osd_seek_info) {
1610 double percentage = get_percent_pos(mpctx);
1611 set_osd_bar(mpctx, 0, "Position", 0, 100, percentage);
1612 if (mpctx->sh_video)
1613 mpctx->osd_show_percentage_until = (GetTimerMS() + 1000) | 1;
1614 mpctx->add_osd_seek_info = false;
1617 // Look if we have a msg
1618 if((msg = get_osd_msg(mpctx))) {
1619 if (strcmp(osd->osd_text, msg->msg)) {
1620 strncpy(osd->osd_text, msg->msg, 127);
1621 if(mpctx->sh_video) vo_osd_changed(OSDTYPE_OSD); else
1622 if(opts->term_osd)
1623 mp_msg(MSGT_CPLAYER,MSGL_STATUS, "%s%s\n", opts->term_osd_esc,
1624 msg->msg);
1626 return;
1629 if(mpctx->sh_video) {
1630 // fallback on the timer
1631 if (opts->osd_level >= 2) {
1632 int len = get_time_length(mpctx);
1633 int percentage = -1;
1634 char percentage_text[10];
1635 int pts = get_current_time(mpctx);
1637 if (mpctx->osd_show_percentage_until)
1638 percentage = get_percent_pos(mpctx);
1640 if (percentage >= 0)
1641 snprintf(percentage_text, 9, " (%d%%)", percentage);
1642 else
1643 percentage_text[0] = 0;
1645 if (opts->osd_level == 3)
1646 snprintf(osd_text_timer, 63,
1647 "%c %02d:%02d:%02d / %02d:%02d:%02d%s",
1648 mpctx->osd_function,pts/3600,(pts/60)%60,pts%60,
1649 len/3600,(len/60)%60,len%60,percentage_text);
1650 else
1651 snprintf(osd_text_timer, 63, "%c %02d:%02d:%02d%s",
1652 mpctx->osd_function,pts/3600,(pts/60)%60,
1653 pts%60,percentage_text);
1654 } else
1655 osd_text_timer[0]=0;
1657 if (strcmp(osd->osd_text, osd_text_timer)) {
1658 strncpy(osd->osd_text, osd_text_timer, 63);
1659 vo_osd_changed(OSDTYPE_OSD);
1661 return;
1664 // Clear the term osd line
1665 if (opts->term_osd && osd->osd_text[0]) {
1666 osd->osd_text[0] = 0;
1667 printf("%s\n", opts->term_osd_esc);
1671 ///@}
1672 // OSDMsgStack
1675 void reinit_audio_chain(struct MPContext *mpctx)
1677 struct MPOpts *opts = &mpctx->opts;
1678 struct ao *ao;
1679 if (!mpctx->sh_audio)
1680 return;
1681 if (!(mpctx->initialized_flags & INITIALIZED_ACODEC)) {
1682 current_module="init_audio_codec";
1683 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1684 if(!init_best_audio_codec(mpctx->sh_audio,audio_codec_list,audio_fm_list)){
1685 goto init_error;
1687 mpctx->initialized_flags|=INITIALIZED_ACODEC;
1688 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1692 current_module="af_preinit";
1693 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1694 mpctx->initialized_flags |= INITIALIZED_AO;
1695 mpctx->ao = ao_create();
1696 mpctx->ao->samplerate = force_srate;
1697 mpctx->ao->format = opts->audio_output_format;
1699 ao = mpctx->ao;
1701 // first init to detect best values
1702 if(!init_audio_filters(mpctx->sh_audio, // preliminary init
1703 // input:
1704 mpctx->sh_audio->samplerate,
1705 // output:
1706 &ao->samplerate, &ao->channels, &ao->format)) {
1707 mp_tmsg(MSGT_CPLAYER,MSGL_ERR, "Error at audio filter chain "
1708 "pre-init!\n");
1709 exit_player(mpctx, EXIT_ERROR);
1711 if (!ao->initialized) {
1712 current_module="ao2_init";
1713 ao->buffersize = opts->ao_buffersize;
1714 ao_init(ao, opts->audio_driver_list);
1715 if (!ao->initialized) {
1716 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Could not open/initialize audio device -> no sound.\n");
1717 goto init_error;
1719 mp_msg(MSGT_CPLAYER,MSGL_INFO,"AO: [%s] %dHz %dch %s (%d bytes per sample)\n",
1720 ao->driver->info->short_name,
1721 ao->samplerate, ao->channels,
1722 af_fmt2str_short(ao->format),
1723 af_fmt2bits(ao->format)/8 );
1724 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Description: %s\nAO: Author: %s\n",
1725 ao->driver->info->name, ao->driver->info->author);
1726 if (strlen(ao->driver->info->comment) > 0)
1727 mp_msg(MSGT_CPLAYER, MSGL_V, "AO: Comment: %s\n",
1728 ao->driver->info->comment);
1731 // init audio filters:
1732 current_module="af_init";
1733 if (!build_afilter_chain(mpctx)) {
1734 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Couldn't find matching filter/ao format!\n");
1735 goto init_error;
1737 mpctx->mixer.ao = ao;
1738 mpctx->mixer.volstep = volstep;
1739 mpctx->syncing_audio = true;
1740 return;
1742 init_error:
1743 uninit_player(mpctx, INITIALIZED_ACODEC|INITIALIZED_AO); // close codec and possibly AO
1744 mpctx->sh_audio=mpctx->d_audio->sh=NULL; // -> nosound
1745 mpctx->d_audio->id = -2;
1749 ///@}
1750 // Command2Property
1753 // Return pts value corresponding to the end point of audio written to the
1754 // ao so far.
1755 static double written_audio_pts(struct MPContext *mpctx)
1757 sh_audio_t *sh_audio = mpctx->sh_audio;
1758 demux_stream_t *d_audio = mpctx->d_audio;
1759 double buffered_output;
1760 // first calculate the end pts of audio that has been output by decoder
1761 double a_pts = sh_audio->pts;
1762 if (a_pts != MP_NOPTS_VALUE)
1763 // Good, decoder supports new way of calculating audio pts.
1764 // sh_audio->pts is the timestamp of the latest input packet with
1765 // known pts that the decoder has decoded. sh_audio->pts_bytes is
1766 // the amount of bytes the decoder has written after that timestamp.
1767 a_pts += sh_audio->pts_bytes / (double) sh_audio->o_bps;
1768 else {
1769 // Decoder doesn't support new way of calculating pts (or we're
1770 // being called before it has decoded anything with known timestamp).
1771 // Use the old method of audio pts calculation: take the timestamp
1772 // of last packet with known pts the decoder has read data from,
1773 // and add amount of bytes read after the beginning of that packet
1774 // divided by input bps. This will be inaccurate if the input/output
1775 // ratio is not constant for every audio packet or if it is constant
1776 // but not accurately known in sh_audio->i_bps.
1778 a_pts = d_audio->pts;
1779 // ds_tell_pts returns bytes read after last timestamp from
1780 // demuxing layer, decoder might use sh_audio->a_in_buffer for bytes
1781 // it has read but not decoded
1782 if (sh_audio->i_bps)
1783 a_pts += (ds_tell_pts(d_audio) - sh_audio->a_in_buffer_len) /
1784 (double)sh_audio->i_bps;
1786 // Now a_pts hopefully holds the pts for end of audio from decoder.
1787 // Substract data in buffers between decoder and audio out.
1789 // Decoded but not filtered
1790 a_pts -= sh_audio->a_buffer_len / (double)sh_audio->o_bps;
1792 // Data buffered in audio filters, measured in bytes of "missing" output
1793 buffered_output = af_calc_delay(sh_audio->afilter);
1795 // Data that was ready for ao but was buffered because ao didn't fully
1796 // accept everything to internal buffers yet
1797 buffered_output += sh_audio->a_out_buffer_len;
1799 // Filters divide audio length by playback_speed, so multiply by it
1800 // to get the length in original units without speedup or slowdown
1801 a_pts -= buffered_output * mpctx->opts.playback_speed / mpctx->ao->bps;
1803 return a_pts + mpctx->video_offset;
1806 // Return pts value corresponding to currently playing audio.
1807 double playing_audio_pts(struct MPContext *mpctx)
1809 return written_audio_pts(mpctx) - mpctx->opts.playback_speed *
1810 ao_get_delay(mpctx->ao);
1813 static bool is_av_sub(int type)
1815 return type == 'b' || type == 'p' || type == 'x';
1818 void update_subtitles(struct MPContext *mpctx, double refpts,
1819 double sub_offset, bool reset)
1821 struct MPOpts *opts = &mpctx->opts;
1822 struct sh_video *sh_video = mpctx->sh_video;
1823 struct demux_stream *d_sub = mpctx->d_sub;
1824 double curpts = refpts + sub_delay;
1825 unsigned char *packet=NULL;
1826 int len;
1827 struct sh_sub *sh_sub = d_sub->sh;
1828 int type = sh_sub ? sh_sub->type : 'v';
1829 static subtitle subs;
1830 if (reset) {
1831 if (sh_sub)
1832 sub_reset(sh_sub, mpctx->osd);
1833 sub_clear_text(&subs, MP_NOPTS_VALUE);
1834 if (vo_sub)
1835 set_osd_subtitle(mpctx, NULL);
1836 if (vo_spudec) {
1837 spudec_reset(vo_spudec);
1838 vo_osd_changed(OSDTYPE_SPU);
1840 #ifdef CONFIG_FFMPEG
1841 if (is_av_sub(type))
1842 reset_avsub(sh_sub);
1843 #endif
1844 return;
1846 // find sub
1847 if (mpctx->subdata) {
1848 if (sub_fps==0) sub_fps = sh_video ? sh_video->fps : 25;
1849 current_module = "find_sub";
1850 find_sub(mpctx, mpctx->subdata, curpts *
1851 (mpctx->subdata->sub_uses_time ? 100. : sub_fps));
1852 if (vo_sub)
1853 mpctx->vo_sub_last = vo_sub;
1856 // DVD sub:
1857 if (vobsub_id >= 0 || type == 'v') {
1858 int timestamp;
1859 current_module = "spudec";
1860 /* Get a sub packet from the DVD or a vobsub */
1861 while(1) {
1862 // Vobsub
1863 len = 0;
1864 if (vo_vobsub) {
1865 if (curpts >= 0) {
1866 len = vobsub_get_packet(vo_vobsub, curpts,
1867 (void**)&packet, &timestamp);
1868 if (len > 0) {
1869 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);
1872 } else {
1873 // DVD sub
1874 len = ds_get_packet_sub(d_sub, (unsigned char**)&packet);
1875 if (len > 0) {
1876 // XXX This is wrong, sh_video->pts can be arbitrarily
1877 // much behind demuxing position. Unfortunately using
1878 // d_video->pts which would have been the simplest
1879 // improvement doesn't work because mpeg specific hacks
1880 // in video.c set d_video->pts to 0.
1881 float x = d_sub->pts - refpts;
1882 if (x > -20 && x < 20) // prevent missing subs on pts reset
1883 timestamp = 90000*d_sub->pts;
1884 else timestamp = 90000*curpts;
1885 mp_dbg(MSGT_CPLAYER, MSGL_V, "\rDVD sub: len=%d "
1886 "v_pts=%5.3f s_pts=%5.3f ts=%d \n", len,
1887 refpts, d_sub->pts, timestamp);
1890 if (len<=0 || !packet) break;
1891 // create it only here, since with some broken demuxers we might
1892 // type = v but no DVD sub and we currently do not change the
1893 // "original frame size" ever after init, leading to wrong-sized
1894 // PGS subtitles.
1895 if (!vo_spudec)
1896 vo_spudec = spudec_new(NULL);
1897 if (vo_vobsub || timestamp >= 0)
1898 spudec_assemble(vo_spudec, packet, len, timestamp);
1900 } else if (is_text_sub(type) || is_av_sub(type) || type == 'd') {
1901 if (type == 'd' && !d_sub->demuxer->teletext) {
1902 tt_stream_props tsp = {0};
1903 void *ptr = &tsp;
1904 if (teletext_control(NULL, TV_VBI_CONTROL_START, &ptr) == VBI_CONTROL_TRUE)
1905 d_sub->demuxer->teletext = ptr;
1907 if (d_sub->non_interleaved)
1908 ds_get_next_pts(d_sub);
1910 while (d_sub->first) {
1911 double subpts = ds_get_next_pts(d_sub) + sub_offset;
1912 if (subpts > curpts) {
1913 // Libass handled subs can be fed to it in advance
1914 if (!opts->ass_enabled || !is_text_sub(type))
1915 break;
1916 // Try to avoid demuxing whole file at once
1917 if (d_sub->non_interleaved && subpts > curpts + 1)
1918 break;
1920 double duration = d_sub->first->duration;
1921 len = ds_get_packet_sub(d_sub, &packet);
1922 if (is_av_sub(type)) {
1923 #ifdef CONFIG_FFMPEG
1924 int ret = decode_avsub(sh_sub, packet, len, subpts, duration);
1925 if (ret < 0)
1926 mp_msg(MSGT_SPUDEC, MSGL_WARN, "lavc failed decoding "
1927 "subtitle\n");
1928 #endif
1929 continue;
1931 if (type == 'm') {
1932 if (len < 2) continue;
1933 len = FFMIN(len - 2, AV_RB16(packet));
1934 packet += 2;
1936 if (type == 'd') {
1937 if (d_sub->demuxer->teletext) {
1938 uint8_t *p = packet;
1939 p++;
1940 len--;
1941 while (len >= 46) {
1942 int sublen = p[1];
1943 if (p[0] == 2 || p[0] == 3)
1944 teletext_control(d_sub->demuxer->teletext,
1945 TV_VBI_CONTROL_DECODE_DVB, p + 2);
1946 p += sublen + 2;
1947 len -= sublen + 2;
1950 continue;
1952 if (sh_sub && sh_sub->active) {
1953 sub_decode(sh_sub, mpctx->osd, packet, len, subpts, duration);
1954 continue;
1956 if (subpts != MP_NOPTS_VALUE) {
1957 if (duration < 0)
1958 sub_clear_text(&subs, MP_NOPTS_VALUE);
1959 if (type == 'a') { // ssa/ass subs without libass => convert to plaintext
1960 int i;
1961 unsigned char* p = packet;
1962 for (i=0; i < 8 && *p != '\0'; p++)
1963 if (*p == ',')
1964 i++;
1965 if (*p == '\0') /* Broken line? */
1966 continue;
1967 len -= p - packet;
1968 packet = p;
1970 double endpts = MP_NOPTS_VALUE;
1971 if (subpts != MP_NOPTS_VALUE && duration >= 0)
1972 endpts = subpts + duration;
1973 sub_add_text(&subs, packet, len, endpts);
1974 set_osd_subtitle(mpctx, &subs);
1976 if (d_sub->non_interleaved)
1977 ds_get_next_pts(d_sub);
1979 if (!opts->ass_enabled)
1980 if (sub_clear_text(&subs, curpts))
1981 set_osd_subtitle(mpctx, &subs);
1983 if (vo_spudec) {
1984 spudec_heartbeat(vo_spudec, 90000*curpts);
1985 if (spudec_changed(vo_spudec))
1986 vo_osd_changed(OSDTYPE_SPU);
1989 current_module=NULL;
1992 static void update_teletext(sh_video_t *sh_video, demuxer_t *demuxer, int reset)
1994 int page_changed;
1996 if (!demuxer->teletext)
1997 return;
1999 //Also forcing page update when such ioctl is not supported or call error occured
2000 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_IS_CHANGED,&page_changed)!=VBI_CONTROL_TRUE)
2001 page_changed=1;
2003 if(!page_changed)
2004 return;
2006 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_GET_VBIPAGE,&vo_osd_teletext_page)!=VBI_CONTROL_TRUE)
2007 vo_osd_teletext_page=NULL;
2008 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_GET_HALF_PAGE,&vo_osd_teletext_half)!=VBI_CONTROL_TRUE)
2009 vo_osd_teletext_half=0;
2010 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_GET_MODE,&vo_osd_teletext_mode)!=VBI_CONTROL_TRUE)
2011 vo_osd_teletext_mode=0;
2012 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_GET_FORMAT,&vo_osd_teletext_format)!=VBI_CONTROL_TRUE)
2013 vo_osd_teletext_format=0;
2014 vo_osd_changed(OSDTYPE_TELETEXT);
2016 teletext_control(demuxer->teletext,TV_VBI_CONTROL_MARK_UNCHANGED,NULL);
2019 static int check_framedrop(struct MPContext *mpctx, double frame_time) {
2020 struct MPOpts *opts = &mpctx->opts;
2021 // check for frame-drop:
2022 current_module = "check_framedrop";
2023 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
2024 static int dropped_frames;
2025 float delay = opts->playback_speed * ao_get_delay(mpctx->ao);
2026 float d = delay-mpctx->delay;
2027 ++total_frame_cnt;
2028 // we should avoid dropping too many frames in sequence unless we
2029 // are too late. and we allow 100ms A-V delay here:
2030 if (d < -dropped_frames*frame_time-0.100 && !mpctx->paused
2031 && !mpctx->restart_playback) {
2032 ++drop_frame_cnt;
2033 ++dropped_frames;
2034 return frame_dropping;
2035 } else
2036 dropped_frames = 0;
2038 return 0;
2042 #ifdef HAVE_RTC
2043 int rtc_fd = -1;
2044 #endif
2046 static float timing_sleep(struct MPContext *mpctx, float time_frame)
2048 #ifdef HAVE_RTC
2049 if (rtc_fd >= 0){
2050 // -------- RTC -----------
2051 current_module="sleep_rtc";
2052 while (time_frame > 0.000) {
2053 unsigned long rtc_ts;
2054 if (read(rtc_fd, &rtc_ts, sizeof(rtc_ts)) <= 0)
2055 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC read error: %s\n", strerror(errno));
2056 time_frame -= get_relative_time(mpctx);
2058 } else
2059 #endif
2061 // assume kernel HZ=100 for softsleep, works with larger HZ but with
2062 // unnecessarily high CPU usage
2063 struct MPOpts *opts = &mpctx->opts;
2064 float margin = opts->softsleep ? 0.011 : 0;
2065 current_module = "sleep_timer";
2066 while (time_frame > margin) {
2067 usec_sleep(1000000 * (time_frame - margin));
2068 time_frame -= get_relative_time(mpctx);
2070 if (opts->softsleep){
2071 current_module = "sleep_soft";
2072 if (time_frame < 0)
2073 mp_tmsg(MSGT_AVSYNC, MSGL_WARN, "Warning! Softsleep underflow!\n");
2074 while (time_frame > 0)
2075 time_frame -= get_relative_time(mpctx); // burn the CPU
2078 return time_frame;
2081 static int select_subtitle(MPContext *mpctx)
2083 struct MPOpts *opts = &mpctx->opts;
2084 // find the best sub to use
2085 int id;
2086 int found = 0;
2087 mpctx->global_sub_pos = -1; // no subs by default
2088 if (vobsub_id >= 0) {
2089 // if user asks for a vobsub id, use that first.
2090 id = vobsub_id;
2091 found = mp_property_do("sub_vob", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
2094 if (!found && opts->sub_id >= 0) {
2095 // if user asks for a dvd sub id, use that next.
2096 id = opts->sub_id;
2097 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
2100 if (!found) {
2101 // if there are text subs to use, use those. (autosubs come last here)
2102 id = 0;
2103 found = mp_property_do("sub_file", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
2106 if (!found && opts->sub_id == -1) {
2107 // finally select subs by language and container hints
2108 if (opts->sub_id == -1)
2109 opts->sub_id =
2110 demuxer_sub_track_by_lang_and_default(mpctx->d_sub->demuxer,
2111 opts->sub_lang);
2112 if (opts->sub_id >= 0) {
2113 id = opts->sub_id;
2114 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
2117 return found;
2120 #ifdef CONFIG_DVDNAV
2121 #ifndef FF_B_TYPE
2122 #define FF_B_TYPE 3
2123 #endif
2124 /// store decoded video image
2125 static mp_image_t * mp_dvdnav_copy_mpi(mp_image_t *to_mpi,
2126 mp_image_t *from_mpi) {
2127 mp_image_t *mpi;
2129 /// Do not store B-frames
2130 if (from_mpi->pict_type == FF_B_TYPE)
2131 return to_mpi;
2133 if (to_mpi &&
2134 to_mpi->w == from_mpi->w &&
2135 to_mpi->h == from_mpi->h &&
2136 to_mpi->imgfmt == from_mpi->imgfmt)
2137 mpi = to_mpi;
2138 else {
2139 if (to_mpi)
2140 free_mp_image(to_mpi);
2141 if (from_mpi->w == 0 || from_mpi->h == 0)
2142 return NULL;
2143 mpi = alloc_mpi(from_mpi->w,from_mpi->h,from_mpi->imgfmt);
2146 copy_mpi(mpi,from_mpi);
2147 return mpi;
2150 static void mp_dvdnav_reset_stream (MPContext *ctx) {
2151 struct MPOpts *opts = &ctx->opts;
2152 if (ctx->sh_video) {
2153 /// clear video pts
2154 ctx->d_video->pts = 0.0f;
2155 ctx->sh_video->pts = 0.0f;
2156 ctx->sh_video->i_pts = 0.0f;
2157 ctx->sh_video->last_pts = 0.0f;
2158 ctx->sh_video->num_buffered_pts = 0;
2159 ctx->sh_video->num_frames = 0;
2160 ctx->sh_video->num_frames_decoded = 0;
2161 ctx->sh_video->timer = 0.0f;
2162 ctx->sh_video->stream_delay = 0.0f;
2163 ctx->sh_video->timer = 0;
2164 ctx->demuxer->stream_pts = MP_NOPTS_VALUE;
2167 if (ctx->sh_audio) {
2168 /// free audio packets and reset
2169 ds_free_packs(ctx->d_audio);
2170 audio_delay -= ctx->sh_audio->stream_delay;
2171 ctx->delay =- audio_delay;
2172 ao_reset(ctx->ao);
2173 resync_audio_stream(ctx->sh_audio);
2176 audio_delay = 0.0f;
2177 ctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(ctx->stream);
2178 if (opts->sub_lang && opts->sub_id == dvdsub_lang_id) {
2179 dvdsub_lang_id = mp_dvdnav_sid_from_lang(ctx->stream, opts->sub_lang);
2180 if (dvdsub_lang_id != opts->sub_id) {
2181 opts->sub_id = dvdsub_lang_id;
2182 select_subtitle(ctx);
2186 /// clear all EOF related flags
2187 ctx->d_video->eof = ctx->d_audio->eof = ctx->stream->eof = 0;
2190 /// Restore last decoded DVDNAV (still frame)
2191 static mp_image_t *mp_dvdnav_restore_smpi(struct MPContext *mpctx,
2192 int *in_size,
2193 unsigned char **start,
2194 mp_image_t *decoded_frame)
2196 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2197 return decoded_frame;
2199 /// a change occured in dvdnav stream
2200 if (mp_dvdnav_cell_has_changed(mpctx->stream,0)) {
2201 mp_dvdnav_read_wait(mpctx->stream, 1, 1);
2202 mp_dvdnav_context_free(mpctx);
2203 mp_dvdnav_reset_stream(mpctx);
2204 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
2205 mp_dvdnav_cell_has_changed(mpctx->stream,1);
2208 if (*in_size < 0) {
2209 float len;
2211 /// Display still frame, if any
2212 if (mpctx->nav_smpi && !mpctx->nav_buffer)
2213 decoded_frame = mpctx->nav_smpi;
2215 /// increment video frame : continue playing after still frame
2216 len = get_time_length(mpctx);
2217 if (mpctx->sh_video->pts >= len &&
2218 mpctx->sh_video->pts > 0.0 && len > 0.0) {
2219 mp_dvdnav_skip_still(mpctx->stream);
2220 mp_dvdnav_skip_wait(mpctx->stream);
2222 mpctx->sh_video->pts += 1 / mpctx->sh_video->fps;
2224 if (mpctx->nav_buffer) {
2225 *start = mpctx->nav_start;
2226 *in_size = mpctx->nav_in_size;
2227 if (mpctx->nav_start)
2228 memcpy(*start,mpctx->nav_buffer,mpctx->nav_in_size);
2232 return decoded_frame;
2235 /// Save last decoded DVDNAV (still frame)
2236 static void mp_dvdnav_save_smpi(struct MPContext *mpctx, int in_size,
2237 unsigned char *start,
2238 mp_image_t *decoded_frame)
2240 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2241 return;
2243 free(mpctx->nav_buffer);
2245 mpctx->nav_buffer = malloc(in_size);
2246 mpctx->nav_start = start;
2247 mpctx->nav_in_size = mpctx->nav_buffer ? in_size : -1;
2248 if (mpctx->nav_buffer)
2249 memcpy(mpctx->nav_buffer,start,in_size);
2251 if (decoded_frame && mpctx->nav_smpi != decoded_frame)
2252 mpctx->nav_smpi = mp_dvdnav_copy_mpi(mpctx->nav_smpi,decoded_frame);
2254 #endif /* CONFIG_DVDNAV */
2256 /* Modify video timing to match the audio timeline. There are two main
2257 * reasons this is needed. First, video and audio can start from different
2258 * positions at beginning of file or after a seek (MPlayer starts both
2259 * immediately even if they have different pts). Second, the file can have
2260 * audio timestamps that are inconsistent with the duration of the audio
2261 * packets, for example two consecutive timestamp values differing by
2262 * one second but only a packet with enough samples for half a second
2263 * of playback between them.
2265 static void adjust_sync(struct MPContext *mpctx, double frame_time)
2267 current_module = "av_sync";
2269 if (!mpctx->sh_audio || mpctx->syncing_audio)
2270 return;
2272 double a_pts = written_audio_pts(mpctx) - mpctx->delay;
2273 double v_pts = mpctx->sh_video->pts;
2274 double av_delay = a_pts - v_pts;
2275 // Try to sync vo_flip() so it will *finish* at given time
2276 av_delay += mpctx->last_vo_flip_duration;
2277 av_delay -= audio_delay; // This much pts difference is desired
2279 double change = av_delay * 0.1;
2280 double max_change = default_max_pts_correction >= 0 ?
2281 default_max_pts_correction : frame_time * 0.1;
2282 if (change < -max_change)
2283 change = -max_change;
2284 else if (change > max_change)
2285 change = max_change;
2286 mpctx->delay += change;
2287 mpctx->total_avsync_change += change;
2290 #define ASYNC_PLAY_DONE -3
2291 static int audio_start_sync(struct MPContext *mpctx, int playsize)
2293 struct ao *ao = mpctx->ao;
2294 struct MPOpts *opts = &mpctx->opts;
2295 sh_audio_t * const sh_audio = mpctx->sh_audio;
2296 int res;
2298 // Timing info may not be set without
2299 res = decode_audio(sh_audio, 1);
2300 if (res < 0)
2301 return res;
2303 int bytes;
2304 bool did_retry = false;
2305 while (1) {
2306 double written_pts = written_audio_pts(mpctx);
2307 double ptsdiff = written_pts - mpctx->video_pts - mpctx->delay
2308 - audio_delay;
2309 bytes = ptsdiff * ao->bps / mpctx->opts.playback_speed;
2310 bytes -= bytes % (ao->channels * af_fmt2bits(ao->format) / 8);
2312 // ogg demuxers give packets without timing
2313 if (written_pts <= 1 && sh_audio->pts == MP_NOPTS_VALUE) {
2314 if (!did_retry) {
2315 // Try to read more data to see packets that have pts
2316 int res = decode_audio(sh_audio, ao->bps);
2317 if (res < 0)
2318 return res;
2319 did_retry = true;
2320 continue;
2322 bytes = 0;
2325 if (fabs(ptsdiff) > 300) // pts reset or just broken?
2326 bytes = 0;
2328 if (bytes > 0)
2329 break;
2331 mpctx->syncing_audio = false;
2332 int a = FFMIN(-bytes, FFMAX(playsize, 20000));
2333 int res = decode_audio(sh_audio, a);
2334 bytes += sh_audio->a_out_buffer_len;
2335 if (bytes >= 0) {
2336 memmove(sh_audio->a_out_buffer,
2337 sh_audio->a_out_buffer +
2338 sh_audio->a_out_buffer_len - bytes,
2339 bytes);
2340 sh_audio->a_out_buffer_len = bytes;
2341 if (res < 0)
2342 return res;
2343 return decode_audio(sh_audio, playsize);
2345 sh_audio->a_out_buffer_len = 0;
2346 if (res < 0)
2347 return res;
2349 int fillbyte = 0;
2350 if ((ao->format & AF_FORMAT_SIGN_MASK) == AF_FORMAT_US)
2351 fillbyte = 0x80;
2352 if (bytes >= playsize) {
2353 /* This case could fall back to the one below with
2354 * bytes = playsize, but then silence would keep accumulating
2355 * in a_out_buffer if the AO accepts less data than it asks for
2356 * in playsize. */
2357 char *p = malloc(playsize);
2358 memset(p, fillbyte, playsize);
2359 playsize = ao_play(ao, p, playsize, 0);
2360 free(p);
2361 mpctx->delay += opts->playback_speed*playsize/(double)ao->bps;
2362 return ASYNC_PLAY_DONE;
2364 mpctx->syncing_audio = false;
2365 decode_audio_prepend_bytes(sh_audio, bytes, fillbyte);
2366 return decode_audio(sh_audio, playsize);
2369 static int fill_audio_out_buffers(struct MPContext *mpctx)
2371 struct MPOpts *opts = &mpctx->opts;
2372 struct ao *ao = mpctx->ao;
2373 unsigned int t;
2374 double tt;
2375 int playsize;
2376 int playflags=0;
2377 bool audio_eof = false;
2378 bool partial_fill = false;
2379 bool format_change = false;
2380 sh_audio_t * const sh_audio = mpctx->sh_audio;
2381 bool modifiable_audio_format = !(ao->format & AF_FORMAT_SPECIAL_MASK);
2382 int unitsize = ao->channels * af_fmt2bits(ao->format) / 8;
2384 current_module="play_audio";
2386 // all the current uses of ao->pts seem to be in aos that handle
2387 // sync completely wrong; there should be no need to use ao->pts
2388 // in get_space()
2389 ao->pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2390 playsize = ao_get_space(ao);
2392 // Fill buffer if needed:
2393 current_module="decode_audio";
2394 t = GetTimer();
2396 if (!opts->initial_audio_sync || !modifiable_audio_format)
2397 mpctx->syncing_audio = false;
2399 int res;
2400 if (mpctx->syncing_audio && mpctx->sh_video)
2401 res = audio_start_sync(mpctx, playsize);
2402 else
2403 res = decode_audio(sh_audio, playsize);
2404 if (res < 0) { // EOF, error or format change
2405 if (res == -2)
2406 format_change = true;
2407 else if (res == ASYNC_PLAY_DONE)
2408 return 0;
2409 else if (mpctx->d_audio->eof)
2410 audio_eof = true;
2412 t = GetTimer() - t;
2413 tt = t*0.000001f; audio_time_usage+=tt;
2414 if (mpctx->timeline && modifiable_audio_format) {
2415 double endpts = mpctx->timeline[mpctx->timeline_part + 1].start;
2416 double bytes = (endpts - written_audio_pts(mpctx) + audio_delay)
2417 * ao->bps / opts->playback_speed;
2418 if (playsize > bytes) {
2419 playsize = FFMAX(bytes, 0);
2420 playflags |= AOPLAY_FINAL_CHUNK;
2421 audio_eof = true;
2422 partial_fill = true;
2426 if (playsize > sh_audio->a_out_buffer_len) {
2427 partial_fill = true;
2428 playsize = sh_audio->a_out_buffer_len;
2429 if (audio_eof)
2430 playflags |= AOPLAY_FINAL_CHUNK;
2432 playsize -= playsize % unitsize;
2433 if (!playsize)
2434 return partial_fill && audio_eof ? -2 : -partial_fill;
2436 // play audio:
2437 current_module="play_audio";
2439 // Is this pts value actually useful for the aos that access it?
2440 // They're obviously badly broken in the way they handle av sync;
2441 // would not having access to this make them more broken?
2442 ao->pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2443 playsize = ao_play(ao, sh_audio->a_out_buffer, playsize, playflags);
2445 if (playsize > 0) {
2446 sh_audio->a_out_buffer_len -= playsize;
2447 memmove(sh_audio->a_out_buffer, &sh_audio->a_out_buffer[playsize],
2448 sh_audio->a_out_buffer_len);
2449 mpctx->delay += opts->playback_speed*playsize/(double)ao->bps;
2450 } else if (audio_eof && ao_get_delay(ao) < .04) {
2451 // Sanity check to avoid hanging in case current ao doesn't output
2452 // partial chunks and doesn't check for AOPLAY_FINAL_CHUNK
2453 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Audio output truncated at end.\n");
2454 sh_audio->a_out_buffer_len = 0;
2457 /* The format change isn't handled too gracefully. A more precise
2458 * implementation would require draining buffered old-format audio
2459 * while displaying video, then doing the output format switch.
2461 if (format_change) {
2462 uninit_player(mpctx, INITIALIZED_AO);
2463 reinit_audio_chain(mpctx);
2464 return -1;
2467 return -partial_fill;
2470 static int sleep_until_near_frame(struct MPContext *mpctx, float *time_frame,
2471 bool sync_to_audio, float *aq_sleep_time)
2473 struct MPOpts *opts = &mpctx->opts;
2474 double audio_limit = 2;
2475 current_module="calc_sleep_time";
2477 if (mpctx->restart_playback)
2478 return 0;
2480 *time_frame -= get_relative_time(mpctx); // reset timer
2482 if (sync_to_audio) {
2483 float delay = ao_get_delay(mpctx->ao);
2484 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "delay=%f\n", delay);
2486 if (opts->autosync) {
2488 * Adjust this raw delay value by calculating the expected
2489 * delay for this frame and generating a new value which is
2490 * weighted between the two. The higher autosync is, the
2491 * closer to the delay value gets to that which "-nosound"
2492 * would have used, and the longer it will take for A/V
2493 * sync to settle at the right value (but it eventually will.)
2494 * This settling time is very short for values below 100.
2496 float predicted = mpctx->delay / opts->playback_speed + *time_frame;
2497 float difference = delay - predicted;
2498 delay = predicted + difference / (float)opts->autosync;
2501 *time_frame = delay - mpctx->delay / opts->playback_speed;
2503 // delay = amount of audio buffered in soundcard/driver
2504 delay = FFMIN(delay, 0.5);
2505 delay = FFMAX(delay, 0.1);
2506 audio_limit = delay;
2507 } else {
2508 // If we're lagging more than 200 ms behind the right playback rate,
2509 // don't try to "catch up".
2510 // If benchmark is set always output frames as fast as possible
2511 // without sleeping.
2512 if (*time_frame < -0.2 || opts->benchmark)
2513 *time_frame = 0;
2516 double t = *time_frame - mpctx->video_out->flip_queue_offset;
2518 if (t <= 0.05)
2519 return 0;
2521 t -= 0.05;
2522 if (t > audio_limit * 0.6)
2523 t = audio_limit * 0.5;
2524 *aq_sleep_time += t;
2525 mp_input_get_cmd(mpctx->input, t * 1000 + 1, 1);
2526 return 1;
2529 int reinit_video_chain(struct MPContext *mpctx)
2531 struct MPOpts *opts = &mpctx->opts;
2532 sh_video_t * const sh_video = mpctx->sh_video;
2533 if (!sh_video)
2534 return 0;
2535 double ar=-1.0;
2536 //================== Init VIDEO (codec & libvo) ==========================
2537 if (!opts->fixed_vo || !(mpctx->initialized_flags & INITIALIZED_VO)) {
2538 current_module="preinit_libvo";
2540 //shouldn't we set dvideo->id=-2 when we fail?
2541 //if((mpctx->video_out->preinit(vo_subdevice))!=0){
2542 if(!(mpctx->video_out=init_best_video_out(opts, mpctx->x11_state, mpctx->key_fifo, mpctx->input))){
2543 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Error opening/initializing the selected video_out (-vo) device.\n");
2544 goto err_out;
2546 mpctx->initialized_flags|=INITIALIZED_VO;
2549 if(stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_ASPECT_RATIO, &ar) != STREAM_UNSUPPORTED)
2550 mpctx->sh_video->stream_aspect = ar;
2551 current_module="init_video_filters";
2553 char* vf_arg[] = { "_oldargs_", (char*)mpctx->video_out , NULL };
2554 sh_video->vfilter = vf_open_filter(opts, NULL,"vo",vf_arg);
2556 #ifdef CONFIG_MENU
2557 if(use_menu) {
2558 char* vf_arg[] = { "_oldargs_", menu_root, NULL };
2559 vf_menu = vf_open_plugin(opts,libmenu_vfs,sh_video->vfilter,"menu",vf_arg);
2560 if(!vf_menu) {
2561 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Can't open libmenu video filter with root menu %s.\n",menu_root);
2562 use_menu = 0;
2565 if(vf_menu)
2566 sh_video->vfilter = vf_menu;
2567 #endif
2569 #ifdef CONFIG_ASS
2570 if(opts->ass_enabled) {
2571 int i;
2572 int insert = 1;
2573 if (opts->vf_settings)
2574 for (i = 0; opts->vf_settings[i].name; ++i)
2575 if (strcmp(opts->vf_settings[i].name, "ass") == 0) {
2576 insert = 0;
2577 break;
2579 if (insert) {
2580 extern vf_info_t vf_info_ass;
2581 const vf_info_t* libass_vfs[] = {&vf_info_ass, NULL};
2582 char* vf_arg[] = {"auto", "1", NULL};
2583 int retcode = 0;
2584 struct vf_instance *vf_ass = vf_open_plugin_noerr(opts, libass_vfs,
2585 sh_video->vfilter,
2586 "ass", vf_arg,
2587 &retcode);
2588 if (vf_ass)
2589 sh_video->vfilter = vf_ass;
2590 else if (retcode == -1) // vf_ass open() returns -1 if there's VO EOSD
2591 mp_msg(MSGT_CPLAYER, MSGL_V, "[ass] vf_ass not needed\n");
2592 else
2593 mp_msg(MSGT_CPLAYER,MSGL_ERR, "ASS: cannot add video filter\n");
2596 #endif
2598 sh_video->vfilter = append_filters(sh_video->vfilter, opts->vf_settings);
2600 #ifdef CONFIG_ASS
2601 if (opts->ass_enabled)
2602 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_INIT_EOSD, ass_library);
2603 #endif
2605 current_module="init_video_codec";
2607 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2608 init_best_video_codec(sh_video,video_codec_list,video_fm_list);
2609 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2611 if(!sh_video->initialized){
2612 if(!opts->fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
2613 goto err_out;
2616 mpctx->initialized_flags|=INITIALIZED_VCODEC;
2618 if (sh_video->codec)
2619 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODEC=%s\n", sh_video->codec->name);
2621 sh_video->last_pts = MP_NOPTS_VALUE;
2622 sh_video->num_buffered_pts = 0;
2623 sh_video->next_frame_time = 0;
2625 if (opts->auto_quality > 0) {
2626 // Auto quality option enabled
2627 output_quality=get_video_quality_max(sh_video);
2628 if (opts->auto_quality > output_quality)
2629 opts->auto_quality = output_quality;
2630 else
2631 output_quality = opts->auto_quality;
2632 mp_msg(MSGT_CPLAYER,MSGL_V,"AutoQ: setting quality to %d.\n",output_quality);
2633 set_video_quality(sh_video,output_quality);
2636 // ========== Init display (sh_video->disp_w*sh_video->disp_h/out_fmt) ============
2638 current_module="init_vo";
2640 return 1;
2642 err_out:
2643 mpctx->sh_video = mpctx->d_video->sh = NULL;
2644 return 0;
2647 static double update_video_nocorrect_pts(struct MPContext *mpctx)
2649 struct sh_video *sh_video = mpctx->sh_video;
2650 double frame_time = 0;
2651 struct vo *video_out = mpctx->video_out;
2652 while (1) {
2653 current_module = "filter_video";
2654 // In nocorrect-pts mode there is no way to properly time these frames
2655 if (vo_get_buffered_frame(video_out, 0) >= 0)
2656 break;
2657 if (vf_output_queued_frame(sh_video->vfilter))
2658 break;
2659 unsigned char *packet = NULL;
2660 frame_time = sh_video->next_frame_time;
2661 if (mpctx->restart_playback)
2662 frame_time = 0;
2663 int in_size = video_read_frame(sh_video, &sh_video->next_frame_time,
2664 &packet, force_fps);
2665 if (in_size < 0) {
2666 #ifdef CONFIG_DVDNAV
2667 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
2668 if (mp_dvdnav_is_eof(mpctx->stream))
2669 return -1;
2670 if (mpctx->d_video)
2671 mpctx->d_video->eof = 0;
2672 if (mpctx->d_audio)
2673 mpctx->d_audio->eof = 0;
2674 mpctx->stream->eof = 0;
2675 } else
2676 #endif
2677 return -1;
2679 if (in_size > max_framesize)
2680 max_framesize = in_size;
2681 sh_video->timer += frame_time;
2682 if (mpctx->sh_audio)
2683 mpctx->delay -= frame_time;
2684 // video_read_frame can change fps (e.g. for ASF video)
2685 vo_fps = sh_video->fps;
2686 int framedrop_type = check_framedrop(mpctx, frame_time);
2687 current_module = "decode video";
2689 void *decoded_frame;
2690 #ifdef CONFIG_DVDNAV
2691 decoded_frame = mp_dvdnav_restore_smpi(mpctx, &in_size, &packet, NULL);
2692 if (in_size >= 0 && !decoded_frame)
2693 #endif
2694 decoded_frame = decode_video(sh_video, packet, in_size, framedrop_type,
2695 sh_video->pts);
2696 #ifdef CONFIG_DVDNAV
2697 // Save last still frame for future display
2698 mp_dvdnav_save_smpi(mpctx, in_size, packet, decoded_frame);
2699 #endif
2700 if (decoded_frame) {
2701 current_module = "filter video";
2702 filter_video(sh_video, decoded_frame, sh_video->pts);
2704 break;
2706 return frame_time;
2709 static void determine_frame_pts(struct MPContext *mpctx)
2711 struct sh_video *sh_video = mpctx->sh_video;
2712 struct MPOpts *opts = &mpctx->opts;
2714 if (opts->user_pts_assoc_mode) {
2715 sh_video->pts_assoc_mode = opts->user_pts_assoc_mode;
2716 } else if (sh_video->pts_assoc_mode == 0) {
2717 if (mpctx->d_video->demuxer->timestamp_type == TIMESTAMP_TYPE_PTS
2718 && sh_video->codec_reordered_pts != MP_NOPTS_VALUE)
2719 sh_video->pts_assoc_mode = 1;
2720 else
2721 sh_video->pts_assoc_mode = 2;
2722 } else {
2723 int probcount1 = sh_video->num_reordered_pts_problems;
2724 int probcount2 = sh_video->num_sorted_pts_problems;
2725 if (sh_video->pts_assoc_mode == 2) {
2726 int tmp = probcount1;
2727 probcount1 = probcount2;
2728 probcount2 = tmp;
2730 if (probcount1 >= probcount2 * 1.5 + 2) {
2731 sh_video->pts_assoc_mode = 3 - sh_video->pts_assoc_mode;
2732 mp_msg(MSGT_CPLAYER, MSGL_V, "Switching to pts association mode "
2733 "%d.\n", sh_video->pts_assoc_mode);
2736 sh_video->pts = sh_video->pts_assoc_mode == 1 ?
2737 sh_video->codec_reordered_pts : sh_video->sorted_pts;
2740 static double update_video(struct MPContext *mpctx)
2742 struct sh_video *sh_video = mpctx->sh_video;
2743 struct vo *video_out = mpctx->video_out;
2744 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_SET_OSD_OBJ,
2745 mpctx->osd); // hack for vf_expand
2746 if (!mpctx->opts.correct_pts)
2747 return update_video_nocorrect_pts(mpctx);
2749 double pts;
2751 while (1) {
2752 current_module = "filter_video";
2753 if (!mpctx->hrseek_active
2754 && vo_get_buffered_frame(video_out, false) >= 0)
2755 break;
2756 // XXX Time used in this call is not counted in any performance
2757 // timer now
2758 if (vf_output_queued_frame(sh_video->vfilter))
2759 break;
2760 unsigned char *packet = NULL;
2761 int in_size = ds_get_packet_pts(mpctx->d_video, &packet, &pts);
2762 if (pts != MP_NOPTS_VALUE)
2763 pts += mpctx->video_offset;
2764 bool hit_eof = false;
2765 if (in_size < 0) {
2766 // try to extract last frames in case of decoder lag
2767 in_size = 0;
2768 pts = MP_NOPTS_VALUE;
2769 hit_eof = true;
2771 if (in_size > max_framesize)
2772 max_framesize = in_size;
2773 current_module = "decode video";
2774 if (pts >= mpctx->hrseek_pts - .005)
2775 mpctx->hrseek_framedrop = false;
2776 int framedrop_type = mpctx->hrseek_framedrop ? 1 :
2777 check_framedrop(mpctx, sh_video->frametime);
2778 void *decoded_frame = decode_video(sh_video, packet, in_size,
2779 framedrop_type, pts);
2780 if (decoded_frame) {
2781 determine_frame_pts(mpctx);
2782 current_module = "filter video";
2783 filter_video(sh_video, decoded_frame, sh_video->pts);
2784 } else if (hit_eof) {
2785 if (vo_get_buffered_frame(video_out, true) < 0)
2786 return -1;
2788 break;
2791 if (!video_out->frame_loaded)
2792 return 0;
2794 pts = video_out->next_pts;
2795 if (pts == MP_NOPTS_VALUE) {
2796 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Video pts after filters MISSING\n");
2797 // Try to use decoder pts from before filters
2798 pts = sh_video->pts;
2799 if (pts == MP_NOPTS_VALUE)
2800 pts = sh_video->last_pts;
2802 if (mpctx->hrseek_active && pts < mpctx->hrseek_pts - .005) {
2803 vo_skip_frame(video_out);
2804 return 0;
2806 mpctx->hrseek_active = false;
2807 sh_video->pts = pts;
2808 if (sh_video->last_pts == MP_NOPTS_VALUE)
2809 sh_video->last_pts = sh_video->pts;
2810 else if (sh_video->last_pts > sh_video->pts) {
2811 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Decreasing video pts: %f < %f\n",
2812 sh_video->pts, sh_video->last_pts);
2813 /* If the difference in pts is small treat it as jitter around the
2814 * right value (possibly caused by incorrect timestamp ordering) and
2815 * just show this frame immediately after the last one.
2816 * Treat bigger differences as timestamp resets and start counting
2817 * timing of later frames from the position of this one. */
2818 if (sh_video->last_pts - sh_video->pts > 0.5)
2819 sh_video->last_pts = sh_video->pts;
2820 else
2821 sh_video->pts = sh_video->last_pts;
2823 double frame_time = sh_video->pts - sh_video->last_pts;
2824 sh_video->last_pts = sh_video->pts;
2825 sh_video->timer += frame_time;
2826 if (mpctx->sh_audio)
2827 mpctx->delay -= frame_time;
2828 return frame_time;
2831 void pause_player(struct MPContext *mpctx)
2833 if (mpctx->paused)
2834 return;
2835 mpctx->paused = 1;
2836 mpctx->step_frames = 0;
2837 mpctx->time_frame -= get_relative_time(mpctx);
2839 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2840 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2842 if (mpctx->ao && mpctx->sh_audio)
2843 ao_pause(mpctx->ao); // pause audio, keep data if possible
2846 void unpause_player(struct MPContext *mpctx)
2848 if (!mpctx->paused)
2849 return;
2850 mpctx->paused = 0;
2852 if (mpctx->ao && mpctx->sh_audio)
2853 ao_resume(mpctx->ao);
2854 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok
2855 && !mpctx->step_frames)
2856 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL); // resume video
2857 (void)get_relative_time(mpctx); // ignore time that passed during pause
2860 void add_step_frame(struct MPContext *mpctx)
2862 mpctx->step_frames++;
2863 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2864 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2865 unpause_player(mpctx);
2868 static void pause_loop(struct MPContext *mpctx)
2870 struct MPOpts *opts = &mpctx->opts;
2871 mp_cmd_t* cmd;
2872 #ifdef CONFIG_STREAM_CACHE
2873 int old_cache_fill = stream_cache_size > 0 ?
2874 cache_fill_status(mpctx->stream) : 0;
2875 #endif
2876 if (!opts->quiet) {
2877 if (opts->term_osd && !mpctx->sh_video) {
2878 set_osd_tmsg(OSD_MSG_PAUSE, 1, 0, " ===== PAUSE =====");
2879 update_osd_msg(mpctx);
2880 } else
2881 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "\n%s\r",
2882 mp_gtext(" ===== PAUSE ====="));
2883 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_PAUSED\n");
2886 while ( (cmd = mp_input_get_cmd(mpctx->input, 20, 1)) == NULL
2887 || cmd->id == MP_CMD_SET_MOUSE_POS || cmd->pausing == 4) {
2888 if (cmd) {
2889 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
2890 run_command(mpctx, cmd);
2891 mp_cmd_free(cmd);
2892 continue;
2894 if (mpctx->sh_video && mpctx->video_out)
2895 vo_check_events(mpctx->video_out);
2896 #ifdef CONFIG_MENU
2897 if (vf_menu)
2898 vf_menu_pause_update(vf_menu);
2899 #endif
2900 usec_sleep(20000);
2901 update_osd_msg(mpctx);
2902 int hack = vo_osd_changed(0);
2903 vo_osd_changed(hack);
2904 if (hack)
2905 break;
2906 #ifdef CONFIG_STREAM_CACHE
2907 if (!opts->quiet && stream_cache_size > 0) {
2908 int new_cache_fill = cache_fill_status(mpctx->stream);
2909 if (new_cache_fill != old_cache_fill) {
2910 if (opts->term_osd && !mpctx->sh_video) {
2911 set_osd_tmsg(OSD_MSG_PAUSE, 1, 0, "%s %d%%",
2912 mp_gtext(" ===== PAUSE ====="),
2913 new_cache_fill);
2914 update_osd_msg(mpctx);
2915 } else
2916 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "%s %d%%\r",
2917 mp_gtext(" ===== PAUSE ====="),
2918 new_cache_fill);
2919 old_cache_fill = new_cache_fill;
2922 #endif
2927 // Find the right mute status and record position for new file position
2928 static void edl_seek_reset(MPContext *mpctx)
2930 mpctx->edl_muted = 0;
2931 next_edl_record = edl_records;
2933 while (next_edl_record) {
2934 if (next_edl_record->start_sec >= get_current_time(mpctx))
2935 break;
2937 if (next_edl_record->action == EDL_MUTE)
2938 mpctx->edl_muted = !mpctx->edl_muted;
2939 next_edl_record = next_edl_record->next;
2941 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2942 mixer_mute(&mpctx->mixer);
2946 // Execute EDL command for the current position if one exists
2947 static void edl_update(MPContext *mpctx)
2949 if (!next_edl_record)
2950 return;
2952 if (!mpctx->sh_video) {
2953 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot use EDL without video, disabling.\n");
2954 free_edl(edl_records);
2955 next_edl_record = NULL;
2956 edl_records = NULL;
2957 return;
2960 if (get_current_time(mpctx) >= next_edl_record->start_sec) {
2961 if (next_edl_record->action == EDL_SKIP) {
2962 mpctx->osd_function = OSD_FFW;
2963 queue_seek(mpctx, MPSEEK_RELATIVE, next_edl_record->length_sec, 0);
2964 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_SKIP: start [%f], stop "
2965 "[%f], length [%f]\n", next_edl_record->start_sec,
2966 next_edl_record->stop_sec, next_edl_record->length_sec);
2968 else if (next_edl_record->action == EDL_MUTE) {
2969 mpctx->edl_muted = !mpctx->edl_muted;
2970 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2971 mixer_mute(&mpctx->mixer);
2972 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_MUTE: [%f]\n",
2973 next_edl_record->start_sec );
2975 next_edl_record = next_edl_record->next;
2979 static void reinit_decoders(struct MPContext *mpctx)
2981 reinit_video_chain(mpctx);
2982 reinit_audio_chain(mpctx);
2983 mp_property_do("sub", M_PROPERTY_SET, &(int){mpctx->global_sub_pos}, mpctx);
2986 static void seek_reset(struct MPContext *mpctx, bool reset_ao)
2988 if (mpctx->sh_video) {
2989 current_module = "seek_video_reset";
2990 resync_video_stream(mpctx->sh_video);
2991 mpctx->sh_video->timer = 0;
2992 vo_seek_reset(mpctx->video_out);
2993 mpctx->sh_video->timer = 0;
2994 mpctx->sh_video->num_buffered_pts = 0;
2995 mpctx->sh_video->last_pts = MP_NOPTS_VALUE;
2996 mpctx->delay = 0;
2997 mpctx->time_frame = 0;
2998 mpctx->restart_playback = true;
2999 // Not all demuxers set d_video->pts during seek, so this value
3000 // (which is used by at least vobsub and edl code below) may
3001 // be completely wrong (probably 0).
3002 mpctx->sh_video->pts = mpctx->d_video->pts + mpctx->video_offset;
3003 mpctx->video_pts = mpctx->sh_video->pts;
3004 update_subtitles(mpctx, mpctx->sh_video->pts, mpctx->video_offset,
3005 true);
3006 update_teletext(mpctx->sh_video, mpctx->demuxer, 1);
3009 if (mpctx->sh_audio) {
3010 current_module = "seek_audio_reset";
3011 resync_audio_stream(mpctx->sh_audio);
3012 if (reset_ao)
3013 // stop audio, throwing away buffered data
3014 ao_reset(mpctx->ao);
3015 mpctx->sh_audio->a_buffer_len = 0;
3016 mpctx->sh_audio->a_out_buffer_len = 0;
3017 if (!mpctx->sh_video)
3018 update_subtitles(mpctx, mpctx->sh_audio->pts,
3019 mpctx->video_offset, true);
3022 if (vo_vobsub && mpctx->sh_video) {
3023 current_module = "seek_vobsub_reset";
3024 vobsub_seek(vo_vobsub, mpctx->sh_video->pts);
3027 edl_seek_reset(mpctx);
3029 mpctx->hrseek_active = false;
3030 mpctx->hrseek_framedrop = false;
3031 mpctx->total_avsync_change = 0;
3032 audio_time_usage = 0; video_time_usage = 0; vout_time_usage = 0;
3033 drop_frame_cnt = 0;
3035 current_module = NULL;
3038 static bool timeline_set_part(struct MPContext *mpctx, int i)
3040 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
3041 struct timeline_part *n = mpctx->timeline + i;
3042 mpctx->timeline_part = i;
3043 mpctx->video_offset = n->start - n->source_start;
3044 if (n->source == p->source)
3045 return false;
3046 enum stop_play_reason orig_stop_play = mpctx->stop_play;
3047 if (!mpctx->sh_video && mpctx->stop_play == KEEP_PLAYING)
3048 mpctx->stop_play = AT_END_OF_FILE; // let audio uninit drain data
3049 uninit_player(mpctx, INITIALIZED_VCODEC | (mpctx->opts.fixed_vo ? 0 : INITIALIZED_VO) | (mpctx->opts.gapless_audio ? 0 : INITIALIZED_AO) | INITIALIZED_ACODEC | INITIALIZED_SUB);
3050 mpctx->stop_play = orig_stop_play;
3051 mpctx->demuxer = n->source->demuxer;
3052 mpctx->d_video = mpctx->demuxer->video;
3053 mpctx->d_audio = mpctx->demuxer->audio;
3054 mpctx->d_sub = mpctx->demuxer->sub;
3055 mpctx->sh_video = mpctx->d_video->sh;
3056 mpctx->sh_audio = mpctx->d_audio->sh;
3057 return true;
3060 // Given pts, switch playback to the corresponding part.
3061 // Return offset within that part.
3062 static double timeline_set_from_time(struct MPContext *mpctx, double pts,
3063 bool *need_reset)
3065 if (pts < 0)
3066 pts = 0;
3067 for (int i = 0; i < mpctx->num_timeline_parts; i++) {
3068 struct timeline_part *p = mpctx->timeline + i;
3069 if (pts < (p+1)->start) {
3070 *need_reset = timeline_set_part(mpctx, i);
3071 return pts - p->start + p->source_start;
3074 return -1;
3078 // return -1 if seek failed (non-seekable stream?), 0 otherwise
3079 static int seek(MPContext *mpctx, struct seek_params seek,
3080 bool timeline_fallthrough)
3082 struct MPOpts *opts = &mpctx->opts;
3084 current_module = "seek";
3085 if (mpctx->stop_play == AT_END_OF_FILE)
3086 mpctx->stop_play = KEEP_PLAYING;
3087 bool hr_seek = mpctx->demuxer->accurate_seek && opts->correct_pts;
3088 hr_seek &= seek.exact >= 0 && seek.type != MPSEEK_FACTOR;
3089 hr_seek &= opts->hr_seek == 0 && seek.type == MPSEEK_ABSOLUTE
3090 || opts->hr_seek > 0 || seek.exact > 0;
3091 if (seek.type == MPSEEK_FACTOR
3092 || seek.type == MPSEEK_ABSOLUTE
3093 && seek.amount < mpctx->last_chapter_pts
3094 || seek.amount < 0)
3095 mpctx->last_chapter_seek = -1;
3096 if (mpctx->timeline && seek.type == MPSEEK_FACTOR) {
3097 seek.amount *= mpctx->timeline[mpctx->num_timeline_parts].start;
3098 seek.type = MPSEEK_ABSOLUTE;
3100 if ((mpctx->demuxer->accurate_seek || mpctx->timeline)
3101 && seek.type == MPSEEK_RELATIVE) {
3102 seek.type = MPSEEK_ABSOLUTE;
3103 seek.direction = seek.amount > 0 ? 1 : -1;
3104 seek.amount += get_current_time(mpctx);
3107 /* At least the liba52 decoder wants to read from the input stream
3108 * during initialization, so reinit must be done after the demux_seek()
3109 * call that clears possible stream EOF. */
3110 bool need_reset = false;
3111 double demuxer_amount = seek.amount;
3112 if (mpctx->timeline) {
3113 demuxer_amount = timeline_set_from_time(mpctx, seek.amount,
3114 &need_reset);
3115 if (demuxer_amount == -1) {
3116 mpctx->stop_play = AT_END_OF_FILE;
3117 // Clear audio from current position
3118 if (mpctx->sh_audio) {
3119 ao_reset(mpctx->ao);
3120 mpctx->sh_audio->a_buffer_len = 0;
3121 mpctx->sh_audio->a_out_buffer_len = 0;
3123 return -1;
3126 int demuxer_style = 0;
3127 switch (seek.type) {
3128 case MPSEEK_FACTOR:
3129 demuxer_style |= SEEK_FACTOR; // fallthrough
3130 case MPSEEK_ABSOLUTE:
3131 demuxer_style |= SEEK_ABSOLUTE;
3133 if (hr_seek || seek.direction < 0)
3134 demuxer_style |= SEEK_BACKWARD;
3135 else if (seek.direction > 0)
3136 demuxer_style |= SEEK_FORWARD;
3138 int seekresult = demux_seek(mpctx->demuxer, demuxer_amount, audio_delay,
3139 demuxer_style);
3140 if (need_reset)
3141 reinit_decoders(mpctx);
3142 if (seekresult == 0)
3143 return -1;
3145 seek_reset(mpctx, !timeline_fallthrough);
3147 /* Use the target time as "current position" for further relative
3148 * seeks etc until a new video frame has been decoded */
3149 if (seek.type == MPSEEK_ABSOLUTE)
3150 mpctx->video_pts = seek.amount;
3152 if (hr_seek) {
3153 mpctx->hrseek_active = true;
3154 mpctx->hrseek_framedrop = true;
3155 mpctx->hrseek_pts = seek.amount;
3158 mpctx->start_timestamp = GetTimerMS();
3160 return 0;
3163 void queue_seek(struct MPContext *mpctx, enum seek_type type, double amount,
3164 int exact)
3166 struct seek_params *seek = &mpctx->seek;
3167 switch (type) {
3168 case MPSEEK_RELATIVE:
3169 if (seek->type == MPSEEK_FACTOR)
3170 return; // Well... not common enough to bother doing better
3171 seek->amount += amount;
3172 seek->exact = FFMAX(seek->exact, exact);
3173 if (seek->type == MPSEEK_NONE)
3174 seek->exact = exact;
3175 if (seek->type == MPSEEK_ABSOLUTE)
3176 return;
3177 if (seek->amount == 0) {
3178 *seek = (struct seek_params){0};
3179 return;
3181 seek->type = MPSEEK_RELATIVE;
3182 return;
3183 case MPSEEK_ABSOLUTE:
3184 case MPSEEK_FACTOR:
3185 *seek = (struct seek_params) {
3186 .type = type,
3187 .amount = amount,
3188 .exact = exact,
3190 return;
3191 case MPSEEK_NONE:
3192 *seek = (struct seek_params){0};
3193 return;
3195 abort();
3199 double get_time_length(struct MPContext *mpctx)
3201 if (mpctx->timeline)
3202 return mpctx->timeline[mpctx->num_timeline_parts].start;
3204 struct demuxer *demuxer = mpctx->demuxer;
3205 double get_time_ans;
3206 // <= 0 means DEMUXER_CTRL_NOTIMPL or DEMUXER_CTRL_DONTKNOW
3207 if (demux_control(demuxer, DEMUXER_CTRL_GET_TIME_LENGTH,
3208 (void *) &get_time_ans) > 0)
3209 return get_time_ans;
3211 struct sh_video *sh_video = mpctx->d_video->sh;
3212 struct sh_audio *sh_audio = mpctx->d_audio->sh;
3213 if (sh_video && sh_video->i_bps && sh_audio && sh_audio->i_bps)
3214 return (double) (demuxer->movi_end - demuxer->movi_start) /
3215 (sh_video->i_bps + sh_audio->i_bps);
3216 if (sh_video && sh_video->i_bps)
3217 return (double) (demuxer->movi_end - demuxer->movi_start) /
3218 sh_video->i_bps;
3219 if (sh_audio && sh_audio->i_bps)
3220 return (double) (demuxer->movi_end - demuxer->movi_start) /
3221 sh_audio->i_bps;
3222 return 0;
3225 /* If there are timestamps from stream level then use those (for example
3226 * DVDs can have consistent times there while the MPEG-level timestamps
3227 * reset). */
3228 double get_current_time(struct MPContext *mpctx)
3230 struct demuxer *demuxer = mpctx->demuxer;
3231 if (demuxer->stream_pts != MP_NOPTS_VALUE)
3232 return demuxer->stream_pts;
3233 struct sh_video *sh_video = demuxer->video->sh;
3234 if (sh_video)
3235 return mpctx->video_pts;
3236 return playing_audio_pts(mpctx);
3239 int get_percent_pos(struct MPContext *mpctx)
3241 struct demuxer *demuxer = mpctx->demuxer;
3242 int ans = 0;
3243 if (mpctx->timeline)
3244 ans = get_current_time(mpctx) * 100 /
3245 mpctx->timeline[mpctx->num_timeline_parts].start;
3246 else if (demux_control(demuxer, DEMUXER_CTRL_GET_PERCENT_POS, &ans) > 0)
3248 else {
3249 int len = (demuxer->movi_end - demuxer->movi_start) / 100;
3250 off_t pos = demuxer->filepos > 0 ?
3251 demuxer->filepos : stream_tell(demuxer->stream);
3252 if (len > 0)
3253 ans = (pos - demuxer->movi_start) / len;
3254 else
3255 ans = 0;
3257 if (ans < 0)
3258 ans = 0;
3259 if (ans > 100)
3260 ans = 100;
3261 return ans;
3264 // -2 is no chapters, -1 is before first chapter
3265 int get_current_chapter(struct MPContext *mpctx)
3267 double current_pts = get_current_time(mpctx);
3268 if (!mpctx->chapters)
3269 return FFMAX(mpctx->last_chapter_seek,
3270 demuxer_get_current_chapter(mpctx->demuxer, current_pts));
3272 int i;
3273 for (i = 1; i < mpctx->num_chapters; i++)
3274 if (current_pts < mpctx->chapters[i].start)
3275 break;
3276 return FFMAX(mpctx->last_chapter_seek, i - 1);
3279 // currently returns a string allocated with malloc, not talloc
3280 char *chapter_display_name(struct MPContext *mpctx, int chapter)
3282 if (!mpctx->chapters || !mpctx->sh_video)
3283 return demuxer_chapter_display_name(mpctx->demuxer, chapter);
3284 return strdup(mpctx->chapters[chapter].name);
3287 int seek_chapter(struct MPContext *mpctx, int chapter, double *seek_pts,
3288 char **chapter_name)
3290 mpctx->last_chapter_seek = -1;
3291 if (!mpctx->chapters || !mpctx->sh_video) {
3292 int res = demuxer_seek_chapter(mpctx->demuxer, chapter, seek_pts,
3293 chapter_name);
3294 if (res >= 0) {
3295 if (*seek_pts == -1)
3296 seek_reset(mpctx, true);
3297 else {
3298 mpctx->last_chapter_seek = res;
3299 mpctx->last_chapter_pts = *seek_pts;
3302 return res;
3305 if (chapter >= mpctx->num_chapters)
3306 return -1;
3307 if (chapter < 0)
3308 chapter = 0;
3309 *seek_pts = mpctx->chapters[chapter].start;
3310 mpctx->last_chapter_seek = chapter;
3311 mpctx->last_chapter_pts = *seek_pts;
3312 if (chapter_name)
3313 *chapter_name = talloc_strdup(NULL, mpctx->chapters[chapter].name);
3314 return chapter;
3318 static void run_playloop(struct MPContext *mpctx)
3320 struct MPOpts *opts = &mpctx->opts;
3321 float aq_sleep_time = 0;
3322 bool full_audio_buffers = false;
3324 if (opts->chapterrange[1] > 0) {
3325 int cur_chapter = get_current_chapter(mpctx);
3326 if (cur_chapter!=-1 && cur_chapter + 1 > opts->chapterrange[1])
3327 mpctx->stop_play = PT_NEXT_ENTRY;
3330 if (!mpctx->sh_audio && mpctx->d_audio->sh) {
3331 mpctx->sh_audio = mpctx->d_audio->sh;
3332 mpctx->sh_audio->ds = mpctx->d_audio;
3333 reinit_audio_chain(mpctx);
3336 /*========================== PLAY AUDIO ============================*/
3338 if (mpctx->sh_audio && !mpctx->paused
3339 && (!mpctx->restart_playback || !mpctx->sh_video)) {
3340 int status = fill_audio_out_buffers(mpctx);
3341 full_audio_buffers = status >= 0;
3342 if (status == -2)
3343 // at eof, all audio at least written to ao
3344 if (!mpctx->sh_video)
3345 mpctx->stop_play = AT_END_OF_FILE;
3349 if (!mpctx->sh_video) {
3350 mpctx->restart_playback = false;
3351 if (mpctx->step_frames) {
3352 mpctx->step_frames = 0;
3353 pause_player(mpctx);
3355 // handle audio-only case:
3356 double a_pos = 0;
3357 // sh_audio can be NULL due to video stream switching
3358 // TODO: handle this better
3359 if (mpctx->sh_audio)
3360 a_pos = playing_audio_pts(mpctx);
3362 print_status(mpctx, a_pos, false);
3364 update_subtitles(mpctx, a_pos, mpctx->video_offset, false);
3365 update_osd_msg(mpctx);
3366 if (end_at.type == END_AT_TIME && end_at.pos < a_pos) {
3367 mpctx->stop_play = AT_END_OF_FILE;
3368 } else if (mpctx->timeline && mpctx->stop_play == AT_END_OF_FILE
3369 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts
3370 && mpctx->sh_audio) {
3371 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
3372 double delay = ao_get_delay(mpctx->ao);
3373 if (!opts->gapless_audio && p->source != (p+1)->source
3374 && delay > 0.05) {
3375 mpctx->stop_play = KEEP_PLAYING;
3376 mp_input_get_cmd(mpctx->input, (delay-.05) * 1000, true);
3377 } else {
3378 seek(mpctx, (struct seek_params){ .type = MPSEEK_ABSOLUTE,
3379 .amount = (p+1)->start },
3380 true);
3382 } else if (!mpctx->stop_play) {
3383 int sleep_time = full_audio_buffers || !mpctx->sh_audio ? 100 : 20;
3384 mp_input_get_cmd(mpctx->input, sleep_time, true);
3386 } else {
3388 /*========================== PLAY VIDEO ============================*/
3390 vo_pts = mpctx->sh_video->timer * 90000.0;
3391 vo_fps = mpctx->sh_video->fps;
3393 bool blit_frame = mpctx->video_out->frame_loaded;
3394 if (!blit_frame || mpctx->hrseek_active) {
3395 double frame_time = update_video(mpctx);
3396 blit_frame = mpctx->video_out->frame_loaded;
3397 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "*** ftime=%5.3f ***\n", frame_time);
3398 if (mpctx->sh_video->vf_initialized < 0) {
3399 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
3400 "\nFATAL: Could not initialize video filters (-vf) "
3401 "or video output (-vo).\n");
3402 mpctx->stop_play = PT_NEXT_ENTRY;
3403 return;
3405 if (frame_time < 0)
3406 mpctx->stop_play = AT_END_OF_FILE;
3407 else if (!mpctx->restart_playback) {
3408 mpctx->time_frame += frame_time / opts->playback_speed;
3409 adjust_sync(mpctx, frame_time);
3412 if (mpctx->timeline) {
3413 struct timeline_part *next =
3414 mpctx->timeline + mpctx->timeline_part + 1;
3415 if (mpctx->sh_video->pts >= next->start
3416 || mpctx->stop_play == AT_END_OF_FILE
3417 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts) {
3418 seek(mpctx, (struct seek_params){ .type = MPSEEK_ABSOLUTE,
3419 .amount = next->start },
3420 true);
3421 return;
3425 // ==========================================================================
3427 current_module = "vo_check_events";
3428 vo_check_events(mpctx->video_out);
3430 #ifdef CONFIG_X11
3431 if (stop_xscreensaver) {
3432 current_module = "stop_xscreensaver";
3433 xscreensaver_heartbeat(mpctx->x11_state);
3435 #endif
3436 if (heartbeat_cmd) {
3437 static unsigned last_heartbeat;
3438 unsigned now = GetTimerMS();
3439 if (now - last_heartbeat > 30000) {
3440 last_heartbeat = now;
3441 system(heartbeat_cmd);
3445 bool frame_time_remaining = sleep_until_near_frame(mpctx,
3446 &mpctx->time_frame,
3447 full_audio_buffers,
3448 &aq_sleep_time);
3450 //====================== FLIP PAGE (VIDEO BLT): =========================
3452 current_module = "flip_page";
3453 if (!frame_time_remaining && blit_frame) {
3454 struct sh_video *sh_video = mpctx->sh_video;
3455 mpctx->video_pts = sh_video->pts;
3456 update_subtitles(mpctx, sh_video->pts, mpctx->video_offset, false);
3457 update_teletext(sh_video, mpctx->demuxer, 0);
3458 update_osd_msg(mpctx);
3459 struct vf_instance *vf = sh_video->vfilter;
3460 vf->control(vf, VFCTRL_DRAW_EOSD, mpctx->osd);
3461 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
3462 vo_osd_changed(0);
3464 mpctx->time_frame -= mpctx->video_out->flip_queue_offset;
3465 aq_sleep_time += mpctx->time_frame;
3466 // flag 256 means: libvo driver does its timing (dvb card)
3467 if (mpctx->time_frame > 0.001
3468 && !(mpctx->sh_video->output_flags & VFCAP_TIMER))
3469 mpctx->time_frame = timing_sleep(mpctx, mpctx->time_frame);
3470 mpctx->time_frame += mpctx->video_out->flip_queue_offset;
3472 unsigned int t2 = GetTimer();
3473 /* Playing with playback speed it's possible to get pathological
3474 * cases with mpctx->time_frame negative enough to cause an
3475 * overflow in pts_us calculation, thus the FFMAX. */
3476 double time_frame = FFMAX(mpctx->time_frame, -1);
3477 unsigned int pts_us = mpctx->last_time + time_frame * 1e6;
3478 int duration = -1;
3479 double pts2 = mpctx->video_out->next_pts2;
3480 if (pts2 != MP_NOPTS_VALUE && opts->correct_pts
3481 && !mpctx->restart_playback) {
3482 // expected A/V sync correction is ignored
3483 double diff = (pts2 - mpctx->video_pts);
3484 diff /= opts->playback_speed;
3485 if (mpctx->time_frame < 0)
3486 diff += mpctx->time_frame;
3487 if (diff < 0)
3488 diff = 0;
3489 if (diff > 10)
3490 diff = 10;
3491 duration = diff * 1e6;
3493 vo_flip_page(mpctx->video_out, pts_us | 1, duration);
3495 mpctx->last_vo_flip_duration = (GetTimer() - t2) * 0.000001;
3496 vout_time_usage += mpctx->last_vo_flip_duration;
3497 if (mpctx->video_out->driver->flip_page_timed) {
3498 // No need to adjust sync based on flip speed
3499 mpctx->last_vo_flip_duration = 0;
3500 // For print_status - VO call finishing early is OK for sync
3501 mpctx->time_frame -= get_relative_time(mpctx);
3503 if (mpctx->restart_playback) {
3504 mpctx->syncing_audio = true;
3505 if (mpctx->sh_audio && !mpctx->paused)
3506 fill_audio_out_buffers(mpctx);
3507 mpctx->restart_playback = false;
3508 mpctx->time_frame = 0;
3509 get_relative_time(mpctx);
3511 print_status(mpctx, MP_NOPTS_VALUE, true);
3512 } else
3513 print_status(mpctx, MP_NOPTS_VALUE, false);
3515 //============================ Auto QUALITY ============================
3517 /*Output quality adjustments:*/
3518 if (opts->auto_quality > 0) {
3519 current_module = "autoq";
3520 if (output_quality < opts->auto_quality && aq_sleep_time > 0)
3521 ++output_quality;
3522 else
3523 if (output_quality>1 && aq_sleep_time<0)
3524 --output_quality;
3525 else if (output_quality>0 && aq_sleep_time<-0.050f) // 50ms
3526 output_quality = 0;
3527 set_video_quality(mpctx->sh_video, output_quality);
3530 if (!frame_time_remaining && blit_frame) {
3531 if (play_n_frames >= 0) {
3532 --play_n_frames;
3533 if (play_n_frames <= 0)
3534 mpctx->stop_play = PT_NEXT_ENTRY;
3536 if (mpctx->step_frames > 0) {
3537 mpctx->step_frames--;
3538 if (mpctx->step_frames == 0)
3539 pause_player(mpctx);
3543 // FIXME: add size based support for -endpos
3544 if (end_at.type == END_AT_TIME &&
3545 !frame_time_remaining && end_at.pos <= mpctx->sh_video->pts)
3546 mpctx->stop_play = PT_NEXT_ENTRY;
3548 } // end if(mpctx->sh_video)
3550 #ifdef CONFIG_DVDNAV
3551 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
3552 nav_highlight_t hl;
3553 mp_dvdnav_get_highlight(mpctx->stream, &hl);
3554 if (!vo_spudec || !spudec_apply_palette_crop(vo_spudec, hl.palette, hl.sx, hl.sy, hl.ex, hl.ey)) {
3555 osd_set_nav_box(hl.sx, hl.sy, hl.ex, hl.ey);
3556 vo_osd_changed(OSDTYPE_DVDNAV);
3557 } else {
3558 osd_set_nav_box(0, 0, 0, 0);
3559 vo_osd_changed(OSDTYPE_DVDNAV);
3560 vo_osd_changed(OSDTYPE_SPU);
3563 if (mp_dvdnav_stream_has_changed(mpctx->stream)) {
3564 double ar = -1.0;
3565 if (mpctx->sh_video &&
3566 stream_control(mpctx->demuxer->stream,
3567 STREAM_CTRL_GET_ASPECT_RATIO, &ar)
3568 != STREAM_UNSUPPORTED)
3569 mpctx->sh_video->stream_aspect = ar;
3572 #endif
3574 //================= Keyboard events, SEEKing ====================
3576 current_module = "key_events";
3578 while (1) {
3579 mp_cmd_t *cmd;
3580 while ((cmd = mp_input_get_cmd(mpctx->input, 0, 1)) != NULL) {
3581 /* Allow running consecutive seek commands to combine them,
3582 * but execute the seek before running other commands.
3583 * If the user seeks continuously (keeps arrow key down)
3584 * try to finish showing a frame from one location before doing
3585 * another seek (which could lead to unchanging display). */
3586 if (mpctx->seek.type && cmd->id != MP_CMD_SEEK
3587 || mpctx->restart_playback && cmd->id == MP_CMD_SEEK
3588 && GetTimerMS() - mpctx->start_timestamp < 300)
3589 break;
3590 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
3591 run_command(mpctx, cmd);
3592 mp_cmd_free(cmd);
3593 if (mpctx->stop_play)
3594 break;
3596 if (!mpctx->paused || mpctx->stop_play || mpctx->seek.type
3597 || mpctx->restart_playback)
3598 break;
3599 if (mpctx->sh_video) {
3600 update_osd_msg(mpctx);
3601 int hack = vo_osd_changed(0);
3602 vo_osd_changed(hack);
3603 if (hack) {
3604 if (redraw_osd(mpctx->sh_video, mpctx->osd) < 0) {
3605 add_step_frame(mpctx);
3606 break;
3607 } else
3608 vo_osd_changed(0);
3611 pause_loop(mpctx);
3614 // handle -sstep
3615 if (step_sec > 0 && !mpctx->paused) {
3616 mpctx->osd_function = OSD_FFW;
3617 queue_seek(mpctx, MPSEEK_RELATIVE, step_sec, 0);
3620 edl_update(mpctx);
3622 /* Looping. */
3623 if (mpctx->stop_play==AT_END_OF_FILE && opts->loop_times>=0) {
3624 mp_msg(MSGT_CPLAYER, MSGL_V, "loop_times = %d\n", opts->loop_times);
3626 if (opts->loop_times>1)
3627 opts->loop_times--;
3628 else if (opts->loop_times==1)
3629 opts->loop_times = -1;
3630 play_n_frames = play_n_frames_mf;
3631 mpctx->stop_play = 0;
3632 queue_seek(mpctx, MPSEEK_ABSOLUTE, 0, 0);
3635 if (mpctx->seek.type) {
3636 seek(mpctx, mpctx->seek, false);
3637 mpctx->seek = (struct seek_params){0};
3642 static int read_keys(void *ctx, int fd)
3644 getch2(ctx);
3645 return mplayer_get_key(ctx, 0);
3648 static bool attachment_is_font(struct demux_attachment *att)
3650 if (!att->name || !att->type || !att->data || !att->data_size)
3651 return false;
3652 // match against MIME types
3653 if (strcmp(att->type, "application/x-truetype-font") == 0
3654 || strcmp(att->type, "application/x-font") == 0)
3655 return true;
3656 // fallback: match against file extension
3657 if (strlen(att->name) > 4) {
3658 char *ext = att->name + strlen(att->name) - 4;
3659 if (strcasecmp(ext, ".ttf") == 0 || strcasecmp(ext, ".ttc") == 0
3660 || strcasecmp(ext, ".otf") == 0)
3661 return true;
3663 return false;
3666 static int select_audio(demuxer_t *demuxer, int audio_id, char **audio_lang)
3668 if (audio_id == -1)
3669 audio_id = demuxer_audio_track_by_lang_and_default(demuxer, audio_lang);
3670 if (audio_id != -1) // -1 (automatic) is the default behaviour of demuxers
3671 demuxer_switch_audio(demuxer, audio_id);
3672 if (audio_id == -2) { // some demuxers don't yet know how to switch to no sound
3673 demuxer->audio->id = -2;
3674 demuxer->audio->sh = NULL;
3676 return demuxer->audio->id;
3679 static void print_version(const char* name)
3681 mp_msg(MSGT_CPLAYER, MSGL_INFO, MP_TITLE, name);
3683 /* Test for CPU capabilities (and corresponding OS support) for optimizing */
3684 GetCpuCaps(&gCpuCaps);
3685 #if ARCH_X86
3686 mp_msg(MSGT_CPLAYER, MSGL_V,
3687 "CPUflags: MMX: %d MMX2: %d 3DNow: %d 3DNowExt: %d SSE: %d SSE2: %d SSSE3: %d\n",
3688 gCpuCaps.hasMMX, gCpuCaps.hasMMX2,
3689 gCpuCaps.has3DNow, gCpuCaps.has3DNowExt,
3690 gCpuCaps.hasSSE, gCpuCaps.hasSSE2, gCpuCaps.hasSSSE3);
3691 #if CONFIG_RUNTIME_CPUDETECT
3692 mp_tmsg(MSGT_CPLAYER,MSGL_V, "Compiled with runtime CPU detection.\n");
3693 #else
3694 mp_tmsg(MSGT_CPLAYER,MSGL_V, "Compiled for x86 CPU with extensions:");
3695 if (HAVE_MMX)
3696 mp_msg(MSGT_CPLAYER,MSGL_V," MMX");
3697 if (HAVE_MMX2)
3698 mp_msg(MSGT_CPLAYER,MSGL_V," MMX2");
3699 if (HAVE_AMD3DNOW)
3700 mp_msg(MSGT_CPLAYER,MSGL_V," 3DNow");
3701 if (HAVE_AMD3DNOWEXT)
3702 mp_msg(MSGT_CPLAYER,MSGL_V," 3DNowExt");
3703 if (HAVE_SSE)
3704 mp_msg(MSGT_CPLAYER,MSGL_V," SSE");
3705 if (HAVE_SSE2)
3706 mp_msg(MSGT_CPLAYER,MSGL_V," SSE2");
3707 if (HAVE_SSSE3)
3708 mp_msg(MSGT_CPLAYER,MSGL_V," SSSE3");
3709 if (HAVE_CMOV)
3710 mp_msg(MSGT_CPLAYER,MSGL_V," CMOV");
3711 mp_msg(MSGT_CPLAYER,MSGL_V,"\n");
3712 #endif /* CONFIG_RUNTIME_CPUDETECT */
3713 #endif /* ARCH_X86 */
3716 #ifdef PTW32_STATIC_LIB
3717 static void detach_ptw32(void)
3719 pthread_win32_thread_detach_np();
3720 pthread_win32_process_detach_np();
3722 #endif
3724 /* This preprocessor directive is a hack to generate a mplayer-nomain.o object
3725 * file for some tools to link against. */
3726 #ifndef DISABLE_MAIN
3727 int main(int argc,char* argv[]){
3728 #ifdef PTW32_STATIC_LIB
3729 pthread_win32_process_attach_np();
3730 pthread_win32_thread_attach_np();
3731 atexit(detach_ptw32);
3732 #endif
3733 if (argc > 1 && !strcmp(argv[1], "-leak-report"))
3734 talloc_enable_leak_report();
3736 char * mem_ptr;
3738 // movie info:
3740 /* Flag indicating whether MPlayer should exit without playing anything. */
3741 int opt_exit = 0;
3742 int i;
3744 struct MPContext *mpctx = &(struct MPContext){
3745 .osd_function = OSD_PLAY,
3746 .begin_skip = MP_NOPTS_VALUE,
3747 .play_tree_step = 1,
3748 .global_sub_pos = -1,
3749 .set_of_sub_pos = -1,
3750 .file_format = DEMUXER_TYPE_UNKNOWN,
3751 .last_dvb_step = 1,
3754 InitTimer();
3755 srand(GetTimerMS());
3757 mp_msg_init();
3758 set_av_log_callback();
3760 #ifdef CONFIG_X11
3761 mpctx->x11_state = vo_x11_init_state();
3762 #endif
3763 struct MPOpts *opts = &mpctx->opts;
3764 set_default_mplayer_options(opts);
3765 // Create the config context and register the options
3766 mpctx->mconfig = m_config_new(opts, cfg_include);
3767 m_config_register_options(mpctx->mconfig,mplayer_opts);
3768 m_config_register_options(mpctx->mconfig, common_opts);
3769 mp_input_register_options(mpctx->mconfig);
3771 // Preparse the command line
3772 m_config_preparse_command_line(mpctx->mconfig,argc,argv);
3774 #if (defined(__MINGW32__) || defined(__CYGWIN__)) && defined(CONFIG_WIN32DLL)
3775 set_path_env();
3776 #endif
3778 #ifdef CONFIG_TV
3779 stream_tv_defaults.immediate = 1;
3780 #endif
3782 parse_cfgfiles(mpctx, mpctx->mconfig);
3784 mpctx->playtree = m_config_parse_mp_command_line(mpctx->mconfig, argc, argv);
3785 if(mpctx->playtree == NULL)
3786 opt_exit = 1;
3787 else {
3788 mpctx->playtree = play_tree_cleanup(mpctx->playtree);
3789 if(mpctx->playtree) {
3790 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,mpctx->mconfig);
3791 if(mpctx->playtree_iter) {
3792 if(play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
3793 play_tree_iter_free(mpctx->playtree_iter);
3794 mpctx->playtree_iter = NULL;
3796 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,1);
3800 mpctx->key_fifo = mp_fifo_create(opts);
3802 print_version("MPlayer2");
3804 #if defined(__MINGW32__) || defined(__CYGWIN__)
3806 HMODULE kernel32 = GetModuleHandle("Kernel32.dll");
3807 BOOL WINAPI (*setDEP)(DWORD) = NULL;
3808 BOOL WINAPI (*setDllDir)(LPCTSTR) = NULL;
3809 if (kernel32) {
3810 setDEP = GetProcAddress(kernel32, "SetProcessDEPPolicy");
3811 setDllDir = GetProcAddress(kernel32, "SetDllDirectoryA");
3813 if (setDEP) setDEP(3);
3814 if (setDllDir) setDllDir("");
3816 // stop Windows from showing all kinds of annoying error dialogs
3817 SetErrorMode(0x8003);
3818 // request 1ms timer resolution
3819 timeBeginPeriod(1);
3820 #endif
3822 #ifdef CONFIG_PRIORITY
3823 set_priority();
3824 #endif
3826 if (codec_path)
3827 set_codec_path(codec_path);
3829 if(opts->video_driver_list && strcmp(opts->video_driver_list[0],"help")==0){
3830 list_video_out();
3831 opt_exit = 1;
3834 if(opts->audio_driver_list && strcmp(opts->audio_driver_list[0],"help")==0){
3835 list_audio_out();
3836 opt_exit = 1;
3839 /* Check codecs.conf. */
3840 if(!codecs_file || !parse_codec_cfg(codecs_file)){
3841 if(!parse_codec_cfg(mem_ptr=get_path("codecs.conf"))){
3842 if(!parse_codec_cfg(MPLAYER_CONFDIR "/codecs.conf")){
3843 if(!parse_codec_cfg(NULL)){
3844 exit_player_with_rc(mpctx, EXIT_NONE, 0);
3846 mp_tmsg(MSGT_CPLAYER,MSGL_V,"Using built-in default codecs.conf.\n");
3849 free( mem_ptr ); // release the buffer created by get_path()
3852 if(audio_codec_list && strcmp(audio_codec_list[0],"help")==0){
3853 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available audio codecs:\n");
3854 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AUDIO_CODECS\n");
3855 list_codecs(1);
3856 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3857 opt_exit = 1;
3859 if(video_codec_list && strcmp(video_codec_list[0],"help")==0){
3860 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available video codecs:\n");
3861 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODECS\n");
3862 list_codecs(0);
3863 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3864 opt_exit = 1;
3866 if(video_fm_list && strcmp(video_fm_list[0],"help")==0){
3867 vfm_help();
3868 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3869 opt_exit = 1;
3871 if(audio_fm_list && strcmp(audio_fm_list[0],"help")==0){
3872 afm_help();
3873 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3874 opt_exit = 1;
3876 if(af_cfg.list && strcmp(af_cfg.list[0],"help")==0){
3877 af_help();
3878 printf("\n");
3879 opt_exit = 1;
3881 #ifdef CONFIG_X11
3882 if(vo_fstype_list && strcmp(vo_fstype_list[0],"help")==0){
3883 fstype_help();
3884 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3885 opt_exit = 1;
3887 #endif
3888 if((opts->demuxer_name && strcmp(opts->demuxer_name,"help")==0) ||
3889 (opts->audio_demuxer_name && strcmp(opts->audio_demuxer_name,"help")==0) ||
3890 (opts->sub_demuxer_name && strcmp(opts->sub_demuxer_name,"help")==0)){
3891 demuxer_help();
3892 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
3893 opt_exit = 1;
3895 if (opts->list_properties) {
3896 property_print_help();
3897 opt_exit = 1;
3900 if(opt_exit)
3901 exit_player(mpctx, EXIT_NONE);
3903 if (!mpctx->filename && !opts->player_idle_mode) {
3904 // no file/vcd/dvd -> show HELP:
3905 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", mp_gtext(help_text));
3906 exit_player_with_rc(mpctx, EXIT_NONE, 0);
3909 /* Display what configure line was used */
3910 mp_msg(MSGT_CPLAYER, MSGL_V, "Configuration: " CONFIGURATION "\n");
3912 // Many users forget to include command line in bugreports...
3913 if( mp_msg_test(MSGT_CPLAYER,MSGL_V) ){
3914 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "CommandLine:");
3915 for(i=1;i<argc;i++)mp_msg(MSGT_CPLAYER, MSGL_INFO," '%s'",argv[i]);
3916 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
3919 //------ load global data first ------
3921 mpctx->osd = osd_create();
3923 // check font
3924 #ifdef CONFIG_FREETYPE
3925 init_freetype();
3926 #endif
3927 #ifdef CONFIG_FONTCONFIG
3928 if(font_fontconfig <= 0)
3930 #endif
3931 #ifdef CONFIG_BITMAP_FONT
3932 if(font_name){
3933 vo_font=read_font_desc(font_name,font_factor,verbose>1);
3934 if(!vo_font) mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load bitmap font: %s\n",
3935 filename_recode(font_name));
3936 } else {
3937 // try default:
3938 vo_font=read_font_desc( mem_ptr=get_path("font/font.desc"),font_factor,verbose>1);
3939 free(mem_ptr); // release the buffer created by get_path()
3940 if(!vo_font)
3941 vo_font=read_font_desc(MPLAYER_DATADIR "/font/font.desc",font_factor,verbose>1);
3943 if (sub_font_name)
3944 mpctx->osd->sub_font = read_font_desc(sub_font_name, font_factor, verbose>1);
3945 else
3946 mpctx->osd->sub_font = vo_font;
3947 #endif
3948 #ifdef CONFIG_FONTCONFIG
3950 #endif
3952 #ifdef CONFIG_ASS
3953 ass_library = mp_ass_init();
3954 #endif
3956 #ifdef HAVE_RTC
3957 if(opts->rtc)
3959 char *rtc_device = opts->rtc_device;
3960 // seteuid(0); /* Can't hurt to try to get root here */
3961 if ((rtc_fd = open(rtc_device ? rtc_device : "/dev/rtc", O_RDONLY)) < 0)
3962 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Failed to open %s: %s (it should be readable by the user.)\n",
3963 rtc_device ? rtc_device : "/dev/rtc", strerror(errno));
3964 else {
3965 unsigned long irqp = 1024; /* 512 seemed OK. 128 is jerky. */
3967 if (ioctl(rtc_fd, RTC_IRQP_SET, irqp) < 0) {
3968 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Linux RTC init error in ioctl (rtc_irqp_set %lu): %s\n", irqp, strerror(errno));
3969 mp_tmsg(MSGT_CPLAYER, MSGL_HINT, "Try adding \"echo %lu > /proc/sys/dev/rtc/max-user-freq\" to your system startup scripts.\n", irqp);
3970 close (rtc_fd);
3971 rtc_fd = -1;
3972 } else if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
3973 /* variable only by the root */
3974 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC init error in ioctl (rtc_pie_on): %s\n", strerror(errno));
3975 close (rtc_fd);
3976 rtc_fd = -1;
3977 } else
3978 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Using Linux hardware RTC timing (%ldHz).\n", irqp);
3981 if(rtc_fd<0)
3982 #endif /* HAVE_RTC */
3983 mp_msg(MSGT_CPLAYER, MSGL_V, "Using %s timing\n",
3984 opts->softsleep ? "software" : timer_name);
3986 #ifdef HAVE_TERMCAP
3987 load_termcap(NULL); // load key-codes
3988 #endif
3990 // ========== Init keyboard FIFO (connection to libvo) ============
3992 // Init input system
3993 current_module = "init_input";
3994 mpctx->input = mp_input_init(&opts->input);
3995 mp_input_add_key_fd(mpctx->input, -1,0,mplayer_get_key,NULL, mpctx->key_fifo);
3996 if(slave_mode)
3997 mp_input_add_cmd_fd(mpctx->input, 0,USE_SELECT,MP_INPUT_SLAVE_CMD_FUNC,NULL);
3998 else if (opts->consolecontrols)
3999 mp_input_add_key_fd(mpctx->input, 0, 1, read_keys, NULL, mpctx->key_fifo);
4000 // Set the libstream interrupt callback
4001 stream_set_interrupt_callback(mp_input_check_interrupt, mpctx->input);
4003 #ifdef CONFIG_MENU
4004 if(use_menu) {
4005 if(menu_cfg && menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
4006 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
4007 else {
4008 menu_cfg = get_path("menu.conf");
4009 if(menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
4010 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
4011 else {
4012 if(menu_init(mpctx, mpctx->mconfig, mpctx->input,
4013 MPLAYER_CONFDIR "/menu.conf"))
4014 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", MPLAYER_CONFDIR"/menu.conf");
4015 else {
4016 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Menu init failed.\n");
4017 use_menu = 0;
4022 #endif
4024 current_module = NULL;
4026 /// Catch signals
4027 #ifndef __MINGW32__
4028 signal(SIGCHLD,child_sighandler);
4029 #endif
4031 #ifdef CONFIG_CRASH_DEBUG
4032 prog_path = argv[0];
4033 #endif
4034 //========= Catch terminate signals: ================
4035 // terminate requests:
4036 signal(SIGTERM,exit_sighandler); // kill
4037 signal(SIGHUP,exit_sighandler); // kill -HUP / xterm closed
4039 signal(SIGINT,exit_sighandler); // Interrupt from keyboard
4041 signal(SIGQUIT,exit_sighandler); // Quit from keyboard
4042 signal(SIGPIPE,exit_sighandler); // Some window managers cause this
4043 #ifdef CONFIG_SIGHANDLER
4044 // fatal errors:
4045 signal(SIGBUS,exit_sighandler); // bus error
4046 signal(SIGSEGV,exit_sighandler); // segfault
4047 signal(SIGILL,exit_sighandler); // illegal instruction
4048 signal(SIGFPE,exit_sighandler); // floating point exc.
4049 signal(SIGABRT,exit_sighandler); // abort()
4050 #ifdef CONFIG_CRASH_DEBUG
4051 if (crash_debug)
4052 signal(SIGTRAP,exit_sighandler);
4053 #endif
4054 #endif
4056 // ******************* Now, let's see the per-file stuff ********************
4058 play_next_file:
4060 // init global sub numbers
4061 mpctx->global_sub_size = 0;
4062 memset(mpctx->sub_counts, 0, sizeof(mpctx->sub_counts));
4064 if (mpctx->filename) {
4065 load_per_protocol_config (mpctx->mconfig, mpctx->filename);
4066 load_per_extension_config (mpctx->mconfig, mpctx->filename);
4067 load_per_file_config (mpctx->mconfig, mpctx->filename);
4070 if (opts->video_driver_list)
4071 load_per_output_config (mpctx->mconfig, PROFILE_CFG_VO, opts->video_driver_list[0]);
4072 if (opts->audio_driver_list)
4073 load_per_output_config (mpctx->mconfig, PROFILE_CFG_AO, opts->audio_driver_list[0]);
4075 // We must enable getch2 here to be able to interrupt network connection
4076 // or cache filling
4077 if (opts->consolecontrols && !slave_mode) {
4078 if(mpctx->initialized_flags&INITIALIZED_GETCH2)
4079 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"WARNING: getch2_init called twice!\n");
4080 else
4081 getch2_enable(); // prepare stdin for hotkeys...
4082 mpctx->initialized_flags|=INITIALIZED_GETCH2;
4083 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[init getch2]]]\n");
4086 // =================== GUI idle loop (STOP state) ===========================
4087 while (opts->player_idle_mode && !mpctx->filename) {
4088 play_tree_t * entry = NULL;
4089 mp_cmd_t * cmd;
4090 if (mpctx->video_out && mpctx->video_out->config_ok)
4091 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
4092 while (!(cmd = mp_input_get_cmd(mpctx->input, 0, 0))) { // wait for command
4093 if (mpctx->video_out)
4094 vo_check_events(mpctx->video_out);
4095 usec_sleep(20000);
4097 switch (cmd->id) {
4098 case MP_CMD_LOADFILE:
4099 // prepare a tree entry with the new filename
4100 entry = play_tree_new();
4101 play_tree_add_file(entry, cmd->args[0].v.s);
4102 // The entry is added to the main playtree after the switch().
4103 break;
4104 case MP_CMD_LOADLIST:
4105 entry = parse_playlist_file(mpctx->mconfig, cmd->args[0].v.s);
4106 break;
4107 case MP_CMD_QUIT:
4108 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
4109 break;
4110 case MP_CMD_VO_FULLSCREEN:
4111 case MP_CMD_GET_PROPERTY:
4112 case MP_CMD_SET_PROPERTY:
4113 case MP_CMD_STEP_PROPERTY:
4114 run_command(mpctx, cmd);
4115 break;
4118 mp_cmd_free(cmd);
4120 if (entry) { // user entered a command that gave a valid entry
4121 if (mpctx->playtree) // the playtree is always a node with one child. let's clear it
4122 play_tree_free_list(mpctx->playtree->child, 1);
4123 else mpctx->playtree=play_tree_new(); // .. or make a brand new playtree
4125 if (!mpctx->playtree) continue; // couldn't make playtree! wait for next command
4127 play_tree_set_child(mpctx->playtree, entry);
4129 /* Make iterator start at the top the of tree. */
4130 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree, mpctx->mconfig);
4131 if (!mpctx->playtree_iter) continue;
4133 // find the first real item in the tree
4134 if (play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
4135 // no items!
4136 play_tree_iter_free(mpctx->playtree_iter);
4137 mpctx->playtree_iter = NULL;
4138 continue; // wait for next command
4140 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, 1);
4143 //---------------------------------------------------------------------------
4145 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
4146 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL);
4148 if (mpctx->filename) {
4149 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nPlaying %s.\n",
4150 filename_recode(mpctx->filename));
4151 if(use_filename_title && opts->vo_wintitle == NULL)
4152 opts->vo_wintitle = strdup(mp_basename(mpctx->filename));
4155 if (edl_filename) {
4156 if (edl_records) free_edl(edl_records);
4157 next_edl_record = edl_records = edl_parse_file();
4159 if (edl_output_filename) {
4160 if (edl_fd) fclose(edl_fd);
4161 if ((edl_fd = fopen(edl_output_filename, "w")) == NULL)
4163 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Can't open EDL file [%s] for writing.\n",
4164 filename_recode(edl_output_filename));
4168 //==================== Open VOB-Sub ============================
4170 current_module="vobsub";
4171 if (opts->vobsub_name){
4172 vo_vobsub=vobsub_open(opts->vobsub_name,spudec_ifo,1,&vo_spudec);
4173 if(vo_vobsub==NULL)
4174 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load subtitles: %s\n",
4175 filename_recode(opts->vobsub_name));
4176 } else if (opts->sub_auto && mpctx->filename){
4177 char **vob = find_vob_subtitles(opts, mpctx->filename);
4178 for (int i = 0; i < MP_TALLOC_ELEMS(vob); i++) {
4179 vo_vobsub = vobsub_open(vob[i], spudec_ifo, 0, &vo_spudec);
4180 if (vo_vobsub)
4181 break;
4183 talloc_free(vob);
4185 if(vo_vobsub){
4186 mpctx->initialized_flags|=INITIALIZED_VOBSUB;
4187 vobsub_set_from_lang(vo_vobsub, opts->sub_lang);
4188 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
4190 // setup global sub numbering
4191 mpctx->sub_counts[SUB_SOURCE_VOBSUB] = vobsub_get_indexes_count(vo_vobsub);
4194 //============ Open & Sync STREAM --- fork cache2 ====================
4196 mpctx->stream=NULL;
4197 mpctx->demuxer=NULL;
4198 mpctx->d_audio=NULL;
4199 mpctx->d_video=NULL;
4200 mpctx->d_sub = NULL;
4201 mpctx->sh_audio=NULL;
4202 mpctx->sh_video=NULL;
4204 current_module="open_stream";
4205 mpctx->stream = open_stream(mpctx->filename, opts, &mpctx->file_format);
4206 if(!mpctx->stream) { // error...
4207 mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY);
4208 goto goto_next_file;
4210 mpctx->initialized_flags|=INITIALIZED_STREAM;
4212 if(mpctx->file_format == DEMUXER_TYPE_PLAYLIST) {
4213 mp_msg(MSGT_CPLAYER, MSGL_ERR, "\nThis looks like a playlist, but "
4214 "playlist support will not be used automatically.\n"
4215 "MPlayer's playlist code is unsafe and should only be used with "
4216 "trusted sources.\nPlayback will probably fail.\n\n");
4217 #if 0
4218 play_tree_t* entry;
4219 // Handle playlist
4220 current_module="handle_playlist";
4221 mp_msg(MSGT_CPLAYER,MSGL_V,"Parsing playlist %s...\n",
4222 filename_recode(mpctx->filename));
4223 entry = parse_playtree(mpctx->stream, mpctx->mconfig, 0);
4224 mpctx->eof=playtree_add_playlist(mpctx, entry);
4225 goto goto_next_file;
4226 #endif
4228 mpctx->stream->start_pos+=seek_to_byte;
4230 if(stream_dump_type==5){
4231 unsigned char buf[4096];
4232 int len;
4233 FILE *f;
4234 current_module="dumpstream";
4235 stream_reset(mpctx->stream);
4236 stream_seek(mpctx->stream,mpctx->stream->start_pos);
4237 f=fopen(opts->stream_dump_name,"wb");
4238 if(!f){
4239 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
4240 exit_player(mpctx, EXIT_ERROR);
4242 if (opts->chapterrange[0] > 1) {
4243 int chapter = opts->chapterrange[0] - 1;
4244 stream_control(mpctx->stream, STREAM_CTRL_SEEK_TO_CHAPTER, &chapter);
4246 while(!mpctx->stream->eof && !async_quit_request){
4247 len=stream_read(mpctx->stream,buf,4096);
4248 if(len>0) {
4249 if(fwrite(buf,len,1,f) != 1) {
4250 mp_tmsg(MSGT_GLOBAL,MSGL_FATAL,"%s: Error writing file.\n",opts->stream_dump_name);
4251 exit_player(mpctx, EXIT_ERROR);
4254 if (opts->chapterrange[1] > 0) {
4255 int chapter = -1;
4256 if (stream_control(mpctx->stream, STREAM_CTRL_GET_CURRENT_CHAPTER,
4257 &chapter) == STREAM_OK
4258 && chapter + 1 > opts->chapterrange[1])
4259 break;
4262 if(fclose(f)) {
4263 mp_tmsg(MSGT_GLOBAL,MSGL_FATAL,"%s: Error writing file.\n",opts->stream_dump_name);
4264 exit_player(mpctx, EXIT_ERROR);
4266 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Stream dump complete.\n");
4267 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4270 #ifdef CONFIG_DVDREAD
4271 if(mpctx->stream->type==STREAMTYPE_DVD){
4272 current_module="dvd lang->id";
4273 if(opts->audio_lang && opts->audio_id==-1) opts->audio_id=dvd_aid_from_lang(mpctx->stream,opts->audio_lang);
4274 if(opts->sub_lang && opts->sub_id==-1) opts->sub_id=dvd_sid_from_lang(mpctx->stream,opts->sub_lang);
4275 // setup global sub numbering
4276 mpctx->sub_counts[SUB_SOURCE_DEMUX] = dvd_number_of_subs(mpctx->stream);
4277 current_module=NULL;
4279 #endif
4281 #ifdef CONFIG_DVDNAV
4282 if(mpctx->stream->type==STREAMTYPE_DVDNAV){
4283 current_module="dvdnav lang->id";
4284 if(opts->audio_lang && opts->audio_id==-1) opts->audio_id=mp_dvdnav_aid_from_lang(mpctx->stream,opts->audio_lang);
4285 dvdsub_lang_id = -3;
4286 if(opts->sub_lang && opts->sub_id==-1)
4287 dvdsub_lang_id = opts->sub_id = mp_dvdnav_sid_from_lang(mpctx->stream,opts->sub_lang);
4288 // setup global sub numbering
4289 mpctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(mpctx->stream);
4290 current_module=NULL;
4292 #endif
4294 // CACHE2: initial prefill: 20% later: 5% (should be set by -cacheopts)
4295 goto_enable_cache:
4296 if(stream_cache_size>0){
4297 int res;
4298 float stream_cache_min_percent = opts->stream_cache_min_percent;
4299 float stream_cache_seek_min_percent = opts->stream_cache_seek_min_percent;
4300 current_module="enable_cache";
4301 res = stream_enable_cache(mpctx->stream,stream_cache_size*1024,
4302 stream_cache_size*1024*(stream_cache_min_percent / 100.0),
4303 stream_cache_size*1024*(stream_cache_seek_min_percent / 100.0));
4304 if(res == 0)
4305 if((mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY))) goto goto_next_file;
4308 //============ Open DEMUXERS --- DETECT file type =======================
4309 current_module="demux_open";
4311 mpctx->demuxer=demux_open(opts, mpctx->stream,mpctx->file_format,opts->audio_id,opts->video_id,opts->sub_id,mpctx->filename);
4313 // HACK to get MOV Reference Files working
4315 if (mpctx->demuxer && mpctx->demuxer->type==DEMUXER_TYPE_PLAYLIST)
4317 unsigned char* playlist_entry;
4318 play_tree_t *list = NULL, *entry = NULL;
4320 current_module="handle_demux_playlist";
4321 while (ds_get_packet(mpctx->demuxer->video,&playlist_entry)>0)
4323 char *temp;
4324 const char *bname;
4326 mp_msg(MSGT_CPLAYER,MSGL_V,"Adding file %s to element entry.\n",
4327 filename_recode(playlist_entry));
4329 bname=mp_basename(playlist_entry);
4330 if ((strlen(bname)>10) && !strncmp(bname,"qt",2) && !strncmp(bname+3,"gateQT",6))
4331 continue;
4333 if (!strcmp(playlist_entry, mpctx->filename)) // ignoring self-reference
4334 continue;
4336 entry = play_tree_new();
4338 if (mpctx->filename && !strcmp(mp_basename(playlist_entry),playlist_entry)) // add reference path of current file
4340 temp=malloc((strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))+strlen(playlist_entry)+1));
4341 if (temp)
4343 strncpy(temp, mpctx->filename, strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename)));
4344 temp[strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))]='\0';
4345 strcat(temp, playlist_entry);
4346 if (!strcmp(temp, mpctx->filename)) {
4347 free(temp);
4348 continue;
4350 play_tree_add_file(entry,temp);
4351 mp_msg(MSGT_CPLAYER,MSGL_V,"Resolving reference to %s.\n",temp);
4352 free(temp);
4355 else
4356 play_tree_add_file(entry,playlist_entry);
4358 if(!list)
4359 list = entry;
4360 else
4361 play_tree_append_entry(list,entry);
4363 free_demuxer(mpctx->demuxer);
4364 mpctx->demuxer = NULL;
4366 if (list)
4368 entry = play_tree_new();
4369 play_tree_set_child(entry,list);
4370 mpctx->stop_play = playtree_add_playlist(mpctx, entry);
4371 goto goto_next_file;
4375 if(!mpctx->demuxer) {
4376 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Failed to recognize file format.\n");
4377 goto goto_next_file;
4380 if (mpctx->demuxer->matroska_data.ordered_chapters)
4381 build_ordered_chapter_timeline(mpctx);
4383 if (mpctx->demuxer->type == DEMUXER_TYPE_EDL)
4384 build_edl_timeline(mpctx);
4386 if (mpctx->timeline) {
4387 mpctx->timeline_part = 0;
4388 mpctx->demuxer = mpctx->timeline[0].source->demuxer;
4390 int part_count = mpctx->num_timeline_parts;
4391 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline contains %d parts from %d "
4392 "sources. Total length %.3f seconds.\n", part_count,
4393 mpctx->num_sources, mpctx->timeline[part_count].start);
4394 mp_msg(MSGT_CPLAYER, MSGL_V, "Source files:\n");
4395 for (int i = 0; i < mpctx->num_sources; i++)
4396 mp_msg(MSGT_CPLAYER, MSGL_V, "%d: %s\n", i,
4397 filename_recode(mpctx->sources[i].demuxer->filename));
4398 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline parts: (number, start, "
4399 "source_start, source):\n");
4400 for (int i = 0; i < part_count; i++) {
4401 struct timeline_part *p = mpctx->timeline + i;
4402 mp_msg(MSGT_CPLAYER, MSGL_V, "%3d %9.3f %9.3f %3td\n", i, p->start,
4403 p->source_start, p->source - mpctx->sources);
4405 mp_msg(MSGT_CPLAYER, MSGL_V, "END %9.3f\n",
4406 mpctx->timeline[part_count].start);
4409 if (!mpctx->sources) {
4410 mpctx->sources = talloc_ptrtype(NULL, mpctx->sources);
4411 *mpctx->sources = (struct content_source){.stream = mpctx->stream,
4412 .demuxer = mpctx->demuxer};
4413 mpctx->num_sources = 1;
4416 mpctx->initialized_flags|=INITIALIZED_DEMUXER;
4418 #ifdef CONFIG_ASS
4419 if (opts->ass_enabled && ass_library) {
4420 for (int j = 0; j < mpctx->num_sources; j++) {
4421 struct demuxer *d = mpctx->sources[j].demuxer;
4422 for (int i = 0; i < d->num_attachments; i++) {
4423 struct demux_attachment *att = d->attachments + i;
4424 if (use_embedded_fonts && attachment_is_font(att))
4425 ass_add_font(ass_library, att->name, att->data, att->data_size);
4429 #endif
4431 current_module="demux_open2";
4433 mpctx->d_audio=mpctx->demuxer->audio;
4434 mpctx->d_video=mpctx->demuxer->video;
4435 mpctx->d_sub=mpctx->demuxer->sub;
4437 if (ts_prog) {
4438 int tmp = ts_prog;
4439 mp_property_do("switch_program", M_PROPERTY_SET, &tmp, mpctx);
4441 // select audio stream
4442 for (int i = 0; i < mpctx->num_sources; i++)
4443 select_audio(mpctx->sources[i].demuxer->audio->demuxer, opts->audio_id,
4444 opts->audio_lang);
4446 // DUMP STREAMS:
4447 if((stream_dump_type)&&(stream_dump_type<4)){
4448 FILE *f;
4449 demux_stream_t *ds=NULL;
4450 current_module="dump";
4451 // select stream to dump
4452 switch(stream_dump_type){
4453 case 1: ds=mpctx->d_audio;break;
4454 case 2: ds=mpctx->d_video;break;
4455 case 3: ds=mpctx->d_sub;break;
4457 if(!ds){
4458 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"dump: FATAL: Selected stream missing!\n");
4459 exit_player(mpctx, EXIT_ERROR);
4461 // disable other streams:
4462 if(mpctx->d_audio && mpctx->d_audio!=ds) {ds_free_packs(mpctx->d_audio); mpctx->d_audio->id=-2; }
4463 if(mpctx->d_video && mpctx->d_video!=ds) {ds_free_packs(mpctx->d_video); mpctx->d_video->id=-2; }
4464 if(mpctx->d_sub && mpctx->d_sub!=ds) {ds_free_packs(mpctx->d_sub); mpctx->d_sub->id=-2; }
4465 // let's dump it!
4466 f=fopen(opts->stream_dump_name,"wb");
4467 if(!f){
4468 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
4469 exit_player(mpctx, EXIT_ERROR);
4471 while(!ds->eof){
4472 unsigned char* start;
4473 int in_size=ds_get_packet(ds,&start);
4474 if( (mpctx->demuxer->file_format==DEMUXER_TYPE_AVI || mpctx->demuxer->file_format==DEMUXER_TYPE_ASF || mpctx->demuxer->file_format==DEMUXER_TYPE_MOV)
4475 && stream_dump_type==2) fwrite(&in_size,1,4,f);
4476 if(in_size>0) fwrite(start,in_size,1,f);
4477 if (opts->chapterrange[1] > 0) {
4478 int cur_chapter = demuxer_get_current_chapter(mpctx->demuxer, 0);
4479 if(cur_chapter!=-1 && cur_chapter+1 > opts->chapterrange[1])
4480 break;
4483 fclose(f);
4484 mp_tmsg(MSGT_CPLAYER ,MSGL_INFO, "Stream dump complete.\n");
4485 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4488 mpctx->sh_audio=mpctx->d_audio->sh;
4489 mpctx->sh_video=mpctx->d_video->sh;
4491 if(mpctx->sh_video){
4493 current_module="video_read_properties";
4494 if(!video_read_properties(mpctx->sh_video)) {
4495 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Video: Cannot read properties.\n");
4496 mpctx->sh_video=mpctx->d_video->sh=NULL;
4497 } else {
4498 mp_tmsg(MSGT_CPLAYER,MSGL_V,"[V] filefmt:%d fourcc:0x%X size:%dx%d fps:%5.3f ftime:=%6.4f\n",
4499 mpctx->demuxer->file_format,mpctx->sh_video->format, mpctx->sh_video->disp_w,mpctx->sh_video->disp_h,
4500 mpctx->sh_video->fps,mpctx->sh_video->frametime
4503 /* need to set fps here for output encoders to pick it up in their init */
4504 if(force_fps){
4505 mpctx->sh_video->fps=force_fps;
4506 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
4508 vo_fps = mpctx->sh_video->fps;
4510 if(!mpctx->sh_video->fps && !force_fps){
4511 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"FPS not specified in the header or invalid, use the -fps option.\n");
4512 mpctx->opts.correct_pts = 1;
4518 if(!mpctx->sh_video && !mpctx->sh_audio){
4519 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL, "No stream found.\n");
4520 #ifdef CONFIG_DVBIN
4521 if(mpctx->stream->type == STREAMTYPE_DVB)
4523 int dir;
4524 int v = mpctx->last_dvb_step;
4525 if(v > 0)
4526 dir = DVB_CHANNEL_HIGHER;
4527 else
4528 dir = DVB_CHANNEL_LOWER;
4530 if(dvb_step_channel(mpctx->stream, dir)) {
4531 mpctx->stop_play = PT_NEXT_ENTRY;
4532 mpctx->dvbin_reopen = 1;
4535 #endif
4536 goto goto_next_file; // exit_player(_("Fatal error"));
4539 /* display clip info */
4540 demux_info_print(mpctx->demuxer);
4542 //================== Read SUBTITLES (DVD & TEXT) ==========================
4543 if(vo_spudec==NULL &&
4544 (mpctx->stream->type==STREAMTYPE_DVD || mpctx->stream->type == STREAMTYPE_DVDNAV)){
4545 init_vo_spudec(mpctx);
4548 // after reading video params we should load subtitles because
4549 // we know fps so now we can adjust subtitle time to ~6 seconds AST
4550 // check .sub
4551 current_module="read_subtitles_file";
4552 double sub_fps = mpctx->sh_video ? mpctx->sh_video->fps : 25;
4553 if(opts->sub_name){
4554 for (i = 0; opts->sub_name[i] != NULL; ++i)
4555 add_subtitles(mpctx, opts->sub_name[i], sub_fps, 0);
4557 if(opts->sub_auto) { // auto load sub file ...
4558 char **tmp = find_text_subtitles(opts, mpctx->filename);
4559 int nsub = MP_TALLOC_ELEMS(tmp);
4560 for (int i = 0; i < nsub; i++)
4561 add_subtitles(mpctx, tmp[i], sub_fps, 1);
4562 talloc_free(tmp);
4564 if (mpctx->set_of_sub_size > 0)
4565 mpctx->sub_counts[SUB_SOURCE_SUBS] = mpctx->set_of_sub_size;
4567 if (select_subtitle(mpctx)) {
4568 if(mpctx->subdata)
4569 switch (stream_dump_type) {
4570 case 3: list_sub_file(mpctx->subdata); break;
4571 case 4: dump_mpsub(mpctx->subdata, mpctx->sh_video->fps); break;
4572 case 6: dump_srt(mpctx->subdata, mpctx->sh_video->fps); break;
4573 case 7: dump_microdvd(mpctx->subdata, mpctx->sh_video->fps); break;
4574 case 8: dump_jacosub(mpctx->subdata, mpctx->sh_video->fps); break;
4575 case 9: dump_sami(mpctx->subdata, mpctx->sh_video->fps); break;
4579 print_file_properties(mpctx, mpctx->filename);
4581 reinit_video_chain(mpctx);
4582 if (mpctx->sh_video) {
4583 if(mpctx->sh_video->output_flags & VFCAP_SPU && vo_spudec)
4584 spudec_set_hw_spu(vo_spudec,mpctx->video_out);
4585 #ifdef CONFIG_FREETYPE
4586 force_load_font = 1;
4587 #endif
4588 } else if (!mpctx->sh_audio)
4589 goto goto_next_file;
4591 //================== MAIN: ==========================
4592 current_module="main";
4594 if (opts->playing_msg) {
4595 char* msg = property_expand_string(mpctx, opts->playing_msg);
4596 mp_msg(MSGT_CPLAYER,MSGL_INFO,"%s",msg);
4597 free(msg);
4601 // Disable the term OSD in verbose mode
4602 if (verbose)
4603 opts->term_osd = 0;
4607 // Make sure old OSD does not stay around,
4608 // e.g. with -fixed-vo and same-resolution files
4609 clear_osd_msgs();
4610 update_osd_msg(mpctx);
4612 //================ SETUP AUDIO ==========================
4614 if(mpctx->sh_audio){
4615 reinit_audio_chain(mpctx);
4616 if (mpctx->sh_audio && mpctx->sh_audio->codec)
4617 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_CODEC=%s\n", mpctx->sh_audio->codec->name);
4620 current_module="av_init";
4622 if(mpctx->sh_video){
4623 mpctx->sh_video->timer=0;
4624 if (! ignore_start)
4625 audio_delay += mpctx->sh_video->stream_delay;
4627 if(mpctx->sh_audio){
4628 if (start_volume >= 0)
4629 mixer_setvolume(&mpctx->mixer, start_volume, start_volume);
4630 if (! ignore_start)
4631 audio_delay -= mpctx->sh_audio->stream_delay;
4632 mpctx->delay=-audio_delay;
4635 if(!mpctx->sh_audio){
4636 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Audio: no sound\n");
4637 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused audio chunks.\n",mpctx->d_audio->packs);
4638 ds_free_packs(mpctx->d_audio); // free buffered chunks
4639 //mpctx->d_audio->id=-2; // do not read audio chunks
4640 //uninit_player(mpctx, INITIALIZED_AO); // close device
4642 if(!mpctx->sh_video){
4643 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Video: no video\n");
4644 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused video chunks.\n",mpctx->d_video->packs);
4645 ds_free_packs(mpctx->d_video);
4646 mpctx->d_video->id=-2;
4647 //if(!fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
4650 if (!mpctx->sh_video && !mpctx->sh_audio)
4651 goto goto_next_file;
4653 //if(demuxer->file_format!=DEMUXER_TYPE_AVI) pts_from_bps=0; // it must be 0 for mpeg/asf!
4654 if(force_fps && mpctx->sh_video){
4655 vo_fps = mpctx->sh_video->fps=force_fps;
4656 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
4657 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"FPS forced to be %5.3f (ftime: %5.3f).\n",mpctx->sh_video->fps,mpctx->sh_video->frametime);
4660 mp_input_set_section(mpctx->input, NULL);
4661 //TODO: add desired (stream-based) sections here
4662 if (mpctx->stream->type==STREAMTYPE_TV) mp_input_set_section(mpctx->input, "tv");
4663 if (mpctx->stream->type==STREAMTYPE_DVDNAV) mp_input_set_section(mpctx->input, "dvdnav");
4665 //==================== START PLAYING =======================
4667 if(opts->loop_times>1) opts->loop_times--; else
4668 if(opts->loop_times==1) opts->loop_times = -1;
4670 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Starting playback...\n");
4672 total_time_usage_start=GetTimer();
4673 audio_time_usage=0; video_time_usage=0; vout_time_usage=0;
4674 total_frame_cnt=0; drop_frame_cnt=0; // fix for multifile fps benchmark
4675 play_n_frames=play_n_frames_mf;
4677 if(play_n_frames==0){
4678 mpctx->stop_play=PT_NEXT_ENTRY; goto goto_next_file;
4681 mpctx->time_frame = 0;
4682 mpctx->drop_message_shown = 0;
4683 mpctx->restart_playback = true;
4684 mpctx->video_pts = 0;
4685 mpctx->hrseek_active = false;
4686 mpctx->hrseek_framedrop = false;
4687 mpctx->step_frames = 0;
4688 mpctx->total_avsync_change = 0;
4689 mpctx->last_chapter_seek = -1;
4691 // If there's a timeline force an absolute seek to initialize state
4692 if (seek_to_sec || mpctx->timeline) {
4693 queue_seek(mpctx, MPSEEK_ABSOLUTE, seek_to_sec, 0);
4694 seek(mpctx, mpctx->seek, false);
4695 end_at.pos += seek_to_sec;
4697 if (opts->chapterrange[0] > 0) {
4698 double pts;
4699 if (seek_chapter(mpctx, opts->chapterrange[0]-1, &pts, NULL) >= 0
4700 && pts > -1.0) {
4701 queue_seek(mpctx, MPSEEK_ABSOLUTE, pts, 0);
4702 seek(mpctx, mpctx->seek, false);
4706 if (end_at.type == END_AT_SIZE) {
4707 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Option -endpos in MPlayer does not yet support size units.\n");
4708 end_at.type = END_AT_NONE;
4711 #ifdef CONFIG_DVDNAV
4712 mp_dvdnav_context_free(mpctx);
4713 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4714 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
4715 mp_dvdnav_cell_has_changed(mpctx->stream,1);
4717 #endif
4719 mpctx->seek = (struct seek_params){0};
4720 get_relative_time(mpctx); // reset current delta
4721 // Make sure VO knows current pause state
4722 if (mpctx->sh_video)
4723 vo_control(mpctx->video_out, mpctx->paused ? VOCTRL_PAUSE : VOCTRL_RESUME,
4724 NULL);
4726 while (!mpctx->stop_play)
4727 run_playloop(mpctx);
4729 mp_msg(MSGT_GLOBAL,MSGL_V,"EOF code: %d \n",mpctx->stop_play);
4731 #ifdef CONFIG_DVBIN
4732 if(mpctx->dvbin_reopen)
4734 mpctx->stop_play = 0;
4735 uninit_player(mpctx, INITIALIZED_ALL-(INITIALIZED_STREAM|INITIALIZED_GETCH2|(opts->fixed_vo?INITIALIZED_VO:0)));
4736 cache_uninit(mpctx->stream);
4737 mpctx->dvbin_reopen = 0;
4738 goto goto_enable_cache;
4740 #endif
4743 goto_next_file: // don't jump here after ao/vo/getch initialization!
4745 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\n");
4747 if (opts->benchmark) {
4748 double tot=video_time_usage+vout_time_usage+audio_time_usage;
4749 double total_time_usage;
4750 total_time_usage_start=GetTimer()-total_time_usage_start;
4751 total_time_usage = (float)total_time_usage_start*0.000001;
4752 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\nBENCHMARKs: VC:%8.3fs VO:%8.3fs A:%8.3fs Sys:%8.3fs = %8.3fs\n",
4753 video_time_usage,vout_time_usage,audio_time_usage,
4754 total_time_usage-tot,total_time_usage);
4755 if(total_time_usage>0.0)
4756 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARK%%: VC:%8.4f%% VO:%8.4f%% A:%8.4f%% Sys:%8.4f%% = %8.4f%%\n",
4757 100.0*video_time_usage/total_time_usage,
4758 100.0*vout_time_usage/total_time_usage,
4759 100.0*audio_time_usage/total_time_usage,
4760 100.0*(total_time_usage-tot)/total_time_usage,
4761 100.0);
4762 if(total_frame_cnt && frame_dropping)
4763 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARKn: disp: %d (%3.2f fps) drop: %d (%d%%) total: %d (%3.2f fps)\n",
4764 total_frame_cnt-drop_frame_cnt,
4765 (total_time_usage>0.5)?((total_frame_cnt-drop_frame_cnt)/total_time_usage):0,
4766 drop_frame_cnt,
4767 100*drop_frame_cnt/total_frame_cnt,
4768 total_frame_cnt,
4769 (total_time_usage>0.5)?(total_frame_cnt/total_time_usage):0);
4772 // time to uninit all, except global stuff:
4773 int uninitialize_parts = INITIALIZED_ALL;
4774 if (opts->fixed_vo)
4775 uninitialize_parts -= INITIALIZED_VO;
4776 if (opts->gapless_audio && mpctx->stop_play == AT_END_OF_FILE)
4777 uninitialize_parts -= INITIALIZED_AO;
4778 uninit_player(mpctx, uninitialize_parts);
4780 if(mpctx->set_of_sub_size > 0) {
4781 current_module="sub_free";
4782 for(i = 0; i < mpctx->set_of_sub_size; ++i) {
4783 sub_free(mpctx->set_of_subtitles[i]);
4784 #ifdef CONFIG_ASS
4785 if(mpctx->set_of_ass_tracks[i])
4786 ass_free_track( mpctx->set_of_ass_tracks[i] );
4787 #endif
4789 mpctx->set_of_sub_size = 0;
4791 mpctx->vo_sub_last = vo_sub=NULL;
4792 mpctx->subdata=NULL;
4793 #ifdef CONFIG_ASS
4794 mpctx->osd->ass_track = NULL;
4795 if(ass_library)
4796 ass_clear_fonts(ass_library);
4797 #endif
4799 if (!mpctx->stop_play) // In case some goto jumped here...
4800 mpctx->stop_play = PT_NEXT_ENTRY;
4802 int playtree_direction = 1;
4804 if(mpctx->stop_play == PT_NEXT_ENTRY || mpctx->stop_play == PT_PREV_ENTRY) {
4805 if(play_tree_iter_step(mpctx->playtree_iter,mpctx->play_tree_step,0) != PLAY_TREE_ITER_ENTRY) {
4806 play_tree_iter_free(mpctx->playtree_iter);
4807 mpctx->playtree_iter = NULL;
4809 mpctx->play_tree_step = 1;
4810 } else if(mpctx->stop_play == PT_UP_NEXT || mpctx->stop_play == PT_UP_PREV) {
4811 int direction = mpctx->stop_play == PT_UP_NEXT ? 1 : -1;
4812 if(mpctx->playtree_iter) {
4813 if(play_tree_iter_up_step(mpctx->playtree_iter,direction,0) != PLAY_TREE_ITER_ENTRY) {
4814 play_tree_iter_free(mpctx->playtree_iter);
4815 mpctx->playtree_iter = NULL;
4818 } else if (mpctx->stop_play == PT_STOP) {
4819 play_tree_iter_free(mpctx->playtree_iter);
4820 mpctx->playtree_iter = NULL;
4821 } else { // NEXT PREV SRC
4822 playtree_direction = mpctx->stop_play == PT_PREV_SRC ? -1 : 1;
4825 while(mpctx->playtree_iter != NULL) {
4826 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, playtree_direction);
4827 if(mpctx->filename == NULL) {
4828 if(play_tree_iter_step(mpctx->playtree_iter, playtree_direction, 0) != PLAY_TREE_ITER_ENTRY) {
4829 play_tree_iter_free(mpctx->playtree_iter);
4830 mpctx->playtree_iter = NULL;
4832 } else
4833 break;
4836 if (mpctx->playtree_iter != NULL || opts->player_idle_mode) {
4837 if(!mpctx->playtree_iter) mpctx->filename = NULL;
4838 mpctx->stop_play = 0;
4839 goto play_next_file;
4843 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4845 return 1;
4847 #endif /* DISABLE_MAIN */