EDL: add support for new EDL file format
[mplayer/greg.git] / mplayer.c
blob2afbbbb821b92a55a3283f9c60dbffceb55cb7aa
1 /*
2 * This file is part of MPlayer.
4 * MPlayer is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * MPlayer is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License along
15 * with MPlayer; if not, write to the Free Software Foundation, Inc.,
16 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 /// \file
20 /// \ingroup Properties Command2Property OSDMsgStack
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <stdbool.h>
25 #include <math.h>
27 #include "config.h"
28 #include "talloc.h"
30 #if defined(__MINGW32__) || defined(__CYGWIN__)
31 #define _UWIN 1 /*disable Non-underscored versions of non-ANSI functions as otherwise int eof would conflict with eof()*/
32 #include <windows.h>
33 #endif
34 #include <string.h>
35 #include <unistd.h>
37 // #include <sys/mman.h>
38 #include <sys/types.h>
39 #ifndef __MINGW32__
40 #include <sys/ioctl.h>
41 #include <sys/wait.h>
42 #else
43 #define SIGHUP 1 /* hangup */
44 #define SIGQUIT 3 /* quit */
45 #define SIGKILL 9 /* kill (cannot be caught or ignored) */
46 #define SIGBUS 10 /* bus error */
47 #define SIGPIPE 13 /* broken pipe */
48 #endif
50 #include <sys/time.h>
51 #include <sys/stat.h>
53 #include <signal.h>
54 #include <time.h>
55 #include <fcntl.h>
56 #include <limits.h>
58 #include <errno.h>
60 #include "mp_msg.h"
61 #include "av_log.h"
64 #include "m_option.h"
65 #include "m_config.h"
66 #include "mplayer.h"
67 #include "access_mpcontext.h"
68 #include "m_property.h"
70 #include "cfg-mplayer-def.h"
72 #include "libavutil/avstring.h"
74 #include "sub/subreader.h"
75 #include "sub/dec_sub.h"
77 #include "mp_osd.h"
78 #include "libvo/video_out.h"
80 #include "sub/font_load.h"
81 #include "sub/sub.h"
82 #include "ffmpeg_files/intreadwrite.h"
83 #include "sub/av_sub.h"
84 #include "libmpcodecs/dec_teletext.h"
85 #include "cpudetect.h"
86 #include "version.h"
88 #ifdef CONFIG_X11
89 #include "libvo/x11_common.h"
90 #endif
92 #include "libao2/audio_out.h"
94 #include "codec-cfg.h"
96 #include "edl.h"
98 #include "sub/spudec.h"
99 #include "sub/vobsub.h"
101 #include "osdep/getch2.h"
102 #include "osdep/timer.h"
104 #include "input/input.h"
106 int slave_mode=0;
107 int enable_mouse_movements=0;
108 float start_volume = -1;
110 #include "osdep/priority.h"
112 char *heartbeat_cmd;
114 #ifdef HAVE_RTC
115 #ifdef __linux__
116 #include <linux/rtc.h>
117 #else
118 #include <rtc.h>
119 #define RTC_IRQP_SET RTCIO_IRQP_SET
120 #define RTC_PIE_ON RTCIO_PIE_ON
121 #endif /* __linux__ */
122 #endif /* HAVE_RTC */
124 #include "stream/tv.h"
125 #include "stream/stream_radio.h"
126 #ifdef CONFIG_DVBIN
127 #include "stream/dvbin.h"
128 #endif
129 #include "stream/cache2.h"
131 //**************************************************************************//
132 // Playtree
133 //**************************************************************************//
134 #include "playtree.h"
135 #include "playtreeparser.h"
137 //**************************************************************************//
138 // Config
139 //**************************************************************************//
140 #include "parser-cfg.h"
141 #include "parser-mpcmd.h"
143 //**************************************************************************//
144 // Config file
145 //**************************************************************************//
147 static int cfg_inc_verbose(m_option_t *conf){ ++verbose; return 0;}
149 #include "path.h"
151 //**************************************************************************//
152 //**************************************************************************//
153 // Input media streaming & demultiplexer:
154 //**************************************************************************//
156 static int max_framesize=0;
158 #include "stream/stream.h"
159 #include "libmpdemux/demuxer.h"
160 #include "libmpdemux/stheader.h"
162 #ifdef CONFIG_DVDREAD
163 #include "stream/stream_dvd.h"
164 #endif
165 #include "stream/stream_dvdnav.h"
167 #include "libmpcodecs/dec_audio.h"
168 #include "libmpcodecs/dec_video.h"
169 #include "libmpcodecs/mp_image.h"
170 #include "libmpcodecs/vf.h"
171 #include "libmpcodecs/vd.h"
173 #include "mixer.h"
175 #include "mp_core.h"
176 #include "options.h"
177 #include "defaultopts.h"
179 static const char help_text[]=_(
180 "Usage: mplayer [options] [url|path/]filename\n"
181 "\n"
182 "Basic options: (complete list in the man page)\n"
183 " -vo <drv> select video output driver ('-vo help' for a list)\n"
184 " -ao <drv> select audio output driver ('-ao help' for a list)\n"
185 #ifdef CONFIG_VCD
186 " vcd://<trackno> play (S)VCD (Super Video CD) track (raw device, no mount)\n"
187 #endif
188 #ifdef CONFIG_DVDREAD
189 " dvd://<titleno> play DVD title from device instead of plain file\n"
190 #endif
191 " -alang/-slang select DVD audio/subtitle language (by 2-char country code)\n"
192 " -ss <position> seek to given (seconds or hh:mm:ss) position\n"
193 " -nosound do not play sound\n"
194 " -fs fullscreen playback (or -vm, -zoom, details in the man page)\n"
195 " -x <x> -y <y> set display resolution (for use with -vm or -zoom)\n"
196 " -sub <file> specify subtitle file to use (also see -subfps, -subdelay)\n"
197 " -playlist <file> specify playlist file\n"
198 " -vid x -aid y select video (x) and audio (y) stream to play\n"
199 " -fps x -srate y change video (x fps) and audio (y Hz) rate\n"
200 " -pp <quality> enable postprocessing filter (details in the man page)\n"
201 " -framedrop enable frame dropping (for slow machines)\n"
202 "\n"
203 "Basic keys: (complete list in the man page, also check input.conf)\n"
204 " <- or -> seek backward/forward 10 seconds\n"
205 " down or up seek backward/forward 1 minute\n"
206 " pgdown or pgup seek backward/forward 10 minutes\n"
207 " < or > step backward/forward in playlist\n"
208 " p or SPACE pause movie (press any key to continue)\n"
209 " q or ESC stop playing and quit program\n"
210 " + or - adjust audio delay by +/- 0.1 second\n"
211 " o cycle OSD mode: none / seekbar / seekbar + timer\n"
212 " * or / increase or decrease PCM volume\n"
213 " x or z adjust subtitle delay by +/- 0.1 second\n"
214 " r or t adjust subtitle position up/down, also see -vf expand\n"
215 "\n"
216 " * * * SEE THE MAN PAGE FOR DETAILS, FURTHER (ADVANCED) OPTIONS AND KEYS * * *\n"
217 "\n");
220 #define Exit_SIGILL_RTCpuSel _(\
221 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
222 " It may be a bug in our new runtime CPU-detection code...\n"\
223 " Please read DOCS/HTML/en/bugreports.html.\n")
225 #define Exit_SIGILL _(\
226 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
227 " It usually happens when you run it on a CPU different than the one it was\n"\
228 " compiled/optimized for.\n"\
229 " Verify this!\n")
231 #define Exit_SIGSEGV_SIGFPE _(\
232 "- MPlayer crashed by bad usage of CPU/FPU/RAM.\n"\
233 " Recompile MPlayer with --enable-debug and make a 'gdb' backtrace and\n"\
234 " disassembly. Details in DOCS/HTML/en/bugreports_what.html#bugreports_crash.\n")
236 #define Exit_SIGCRASH _(\
237 "- MPlayer crashed. This shouldn't happen.\n"\
238 " It can be a bug in the MPlayer code _or_ in your drivers _or_ in your\n"\
239 " gcc version. If you think it's MPlayer's fault, please read\n"\
240 " DOCS/HTML/en/bugreports.html and follow the instructions there. We can't and\n"\
241 " won't help unless you provide this information when reporting a possible bug.\n")
243 #define SystemTooSlow _("\n\n"\
244 " ************************************************\n"\
245 " **** Your system is too SLOW to play this! ****\n"\
246 " ************************************************\n\n"\
247 "Possible reasons, problems, workarounds:\n"\
248 "- Most common: broken/buggy _audio_ driver\n"\
249 " - Try -ao sdl or use the OSS emulation of ALSA.\n"\
250 " - Experiment with different values for -autosync, 30 is a good start.\n"\
251 "- Slow video output\n"\
252 " - Try a different -vo driver (-vo help for a list) or try -framedrop!\n"\
253 "- Slow CPU\n"\
254 " - Don't try to play a big DVD/DivX on a slow CPU! Try some of the lavdopts,\n"\
255 " e.g. -vfm ffmpeg -lavdopts lowres=1:fast:skiploopfilter=all.\n"\
256 "- Broken file\n"\
257 " - Try various combinations of -nobps -ni -forceidx -mc 0.\n"\
258 "- Slow media (NFS/SMB mounts, DVD, VCD etc)\n"\
259 " - Try -cache 8192.\n"\
260 "- Are you using -cache to play a non-interleaved AVI file?\n"\
261 " - Try -nocache.\n"\
262 "Read DOCS/HTML/en/video.html for tuning/speedup tips.\n"\
263 "If none of this helps you, read DOCS/HTML/en/bugreports.html.\n\n")
266 //**************************************************************************//
267 //**************************************************************************//
269 #include "mp_fifo.h"
271 // benchmark:
272 double video_time_usage=0;
273 double vout_time_usage=0;
274 static double audio_time_usage=0;
275 static int total_time_usage_start=0;
276 static int total_frame_cnt=0;
277 static int drop_frame_cnt=0; // total number of dropped frames
279 // options:
280 static int output_quality=0;
282 // seek:
283 static double seek_to_sec;
284 static off_t seek_to_byte=0;
285 static off_t step_sec=0;
287 static m_time_size_t end_at = { .type = END_AT_NONE, .pos = 0 };
289 // codecs:
290 char **audio_codec_list=NULL; // override audio codec
291 char **video_codec_list=NULL; // override video codec
292 char **audio_fm_list=NULL; // override audio codec family
293 char **video_fm_list=NULL; // override video codec family
295 // this dvdsub_id was selected via slang
296 // use this to allow dvdnav to follow -slang across stream resets,
297 // in particular the subtitle ID for a language changes
298 int dvdsub_lang_id;
299 int vobsub_id=-1;
300 static char* spudec_ifo=NULL;
301 int forced_subs_only=0;
302 int file_filter=1;
304 // cache2:
305 int stream_cache_size=-1;
307 // dump:
308 int stream_dump_type=0;
310 // A-V sync:
311 static float default_max_pts_correction=-1;//0.01f;
312 float audio_delay=0;
313 static int ignore_start=0;
315 double force_fps=0;
316 static int force_srate=0;
317 int frame_dropping=0; // option 0=no drop 1= drop vo 2= drop decode
318 static int play_n_frames=-1;
319 static int play_n_frames_mf=-1;
321 // sub:
322 char *font_name=NULL;
323 char *sub_font_name=NULL;
324 extern int font_fontconfig;
325 float font_factor=0.75;
326 char **sub_name=NULL;
327 float sub_delay=0;
328 float sub_fps=0;
329 int sub_auto = 1;
330 char *vobsub_name=NULL;
331 int subcc_enabled=0;
332 int suboverlap_enabled = 1;
334 #include "sub/ass_mp.h"
336 char* current_module=NULL; // for debugging
339 // ---
341 #ifdef CONFIG_MENU
342 #include "m_struct.h"
343 #include "libmenu/menu.h"
344 static const vf_info_t* const libmenu_vfs[] = {
345 &vf_info_menu,
346 NULL
348 static vf_instance_t* vf_menu = NULL;
349 int use_menu = 0;
350 static char* menu_cfg = NULL;
351 static char* menu_root = "main";
352 #endif
355 edl_record_ptr edl_records = NULL; ///< EDL entries memory area
356 edl_record_ptr next_edl_record = NULL; ///< only for traversing edl_records
357 FILE* edl_fd = NULL; ///< fd to write to when in -edlout mode.
358 int use_filedir_conf;
359 int use_filename_title;
361 #include "mpcommon.h"
362 #include "command.h"
364 #include "metadata.h"
366 const void *mpctx_get_video_out(MPContext *mpctx)
368 return mpctx->video_out;
371 const void *mpctx_get_audio_out(MPContext *mpctx)
373 return mpctx->audio_out;
376 void *mpctx_get_demuxer(MPContext *mpctx)
378 return mpctx->demuxer;
381 void *mpctx_get_playtree_iter(MPContext *mpctx)
383 return mpctx->playtree_iter;
386 void *mpctx_get_mixer(MPContext *mpctx)
388 return &mpctx->mixer;
391 int mpctx_get_global_sub_size(MPContext *mpctx)
393 return mpctx->global_sub_size;
396 int mpctx_get_osd_function(MPContext *mpctx)
398 return mpctx->osd_function;
401 static float get_relative_time(struct MPContext *mpctx)
403 unsigned int new_time = GetTimer();
404 unsigned int delta = new_time - mpctx->last_time;
405 mpctx->last_time = new_time;
406 return delta * 0.000001;
409 static int is_valid_metadata_type(struct MPContext *mpctx, metadata_t type) {
410 switch (type)
412 /* check for valid video stream */
413 case META_VIDEO_CODEC:
414 case META_VIDEO_BITRATE:
415 case META_VIDEO_RESOLUTION:
417 if (!mpctx->sh_video)
418 return 0;
419 break;
422 /* check for valid audio stream */
423 case META_AUDIO_CODEC:
424 case META_AUDIO_BITRATE:
425 case META_AUDIO_SAMPLES:
427 if (!mpctx->sh_audio)
428 return 0;
429 break;
432 /* check for valid demuxer */
433 case META_INFO_TITLE:
434 case META_INFO_ARTIST:
435 case META_INFO_ALBUM:
436 case META_INFO_YEAR:
437 case META_INFO_COMMENT:
438 case META_INFO_TRACK:
439 case META_INFO_GENRE:
441 if (!mpctx->demuxer)
442 return 0;
443 break;
446 default:
447 break;
450 return 1;
453 static char *get_demuxer_info(struct MPContext *mpctx, char *tag) {
454 char **info = mpctx->demuxer->info;
455 int n;
457 if (!info || !tag)
458 return talloc_strdup(NULL, "");
460 for (n = 0; info[2*n] != NULL ; n++)
461 if (!strcasecmp (info[2*n], tag))
462 break;
464 return talloc_strdup(NULL, info[2*n+1] ? info[2*n+1] : "");
467 char *get_metadata(struct MPContext *mpctx, metadata_t type)
469 sh_audio_t * const sh_audio = mpctx->sh_audio;
470 sh_video_t * const sh_video = mpctx->sh_video;
472 if (!is_valid_metadata_type(mpctx, type))
473 return NULL;
475 switch (type) {
476 case META_NAME:
477 return talloc_strdup(NULL, mp_basename(mpctx->filename));
478 case META_VIDEO_CODEC:
479 if (sh_video->format == 0x10000001)
480 return talloc_strdup(NULL, "mpeg1");
481 else if (sh_video->format == 0x10000002)
482 return talloc_strdup(NULL, "mpeg2");
483 else if (sh_video->format == 0x10000004)
484 return talloc_strdup(NULL, "mpeg4");
485 else if (sh_video->format == 0x10000005)
486 return talloc_strdup(NULL, "h264");
487 else if (sh_video->format >= 0x20202020)
488 return talloc_asprintf(NULL, "%.4s", (char *) &sh_video->format);
489 else
490 return talloc_asprintf(NULL, "0x%08X", sh_video->format);
491 case META_VIDEO_BITRATE:
492 return talloc_asprintf(NULL, "%d kbps",
493 (int) (sh_video->i_bps * 8 / 1024));
494 case META_VIDEO_RESOLUTION:
495 return talloc_asprintf(NULL, "%d x %d", sh_video->disp_w,
496 sh_video->disp_h);
497 case META_AUDIO_CODEC:
498 if (sh_audio->codec && sh_audio->codec->name)
499 return talloc_strdup(NULL, sh_audio->codec->name);
500 return talloc_strdup(NULL, "");
501 case META_AUDIO_BITRATE:
502 return talloc_asprintf(NULL, "%d kbps",
503 (int) (sh_audio->i_bps * 8/1000));
504 case META_AUDIO_SAMPLES:
505 return talloc_asprintf(NULL, "%d Hz, %d ch.", sh_audio->samplerate,
506 sh_audio->channels);
508 /* check for valid demuxer */
509 case META_INFO_TITLE:
510 return get_demuxer_info(mpctx, "Title");
512 case META_INFO_ARTIST:
513 return get_demuxer_info(mpctx, "Artist");
515 case META_INFO_ALBUM:
516 return get_demuxer_info(mpctx, "Album");
518 case META_INFO_YEAR:
519 return get_demuxer_info(mpctx, "Year");
521 case META_INFO_COMMENT:
522 return get_demuxer_info(mpctx, "Comment");
524 case META_INFO_TRACK:
525 return get_demuxer_info(mpctx, "Track");
527 case META_INFO_GENRE:
528 return get_demuxer_info(mpctx, "Genre");
530 default:
531 break;
534 return talloc_strdup(NULL, "");
537 static void print_file_properties(struct MPContext *mpctx, const char *filename)
539 double start_pts = MP_NOPTS_VALUE;
540 double video_start_pts = MP_NOPTS_VALUE;
541 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_FILENAME=%s\n",
542 filename_recode(filename));
543 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_DEMUXER=%s\n", mpctx->demuxer->desc->name);
544 if (mpctx->sh_video) {
545 /* Assume FOURCC if all bytes >= 0x20 (' ') */
546 if (mpctx->sh_video->format >= 0x20202020)
547 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=%.4s\n", (char *)&mpctx->sh_video->format);
548 else
549 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=0x%08X\n", mpctx->sh_video->format);
550 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_BITRATE=%d\n", mpctx->sh_video->i_bps*8);
551 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_WIDTH=%d\n", mpctx->sh_video->disp_w);
552 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_HEIGHT=%d\n", mpctx->sh_video->disp_h);
553 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FPS=%5.3f\n", mpctx->sh_video->fps);
554 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_ASPECT=%1.4f\n", mpctx->sh_video->aspect);
555 video_start_pts = ds_get_next_pts(mpctx->d_video);
557 if (mpctx->sh_audio) {
558 /* Assume FOURCC if all bytes >= 0x20 (' ') */
559 if (mpctx->sh_audio->format >= 0x20202020)
560 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_FORMAT=%.4s\n", (char *)&mpctx->sh_audio->format);
561 else
562 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_FORMAT=%d\n", mpctx->sh_audio->format);
563 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_BITRATE=%d\n", mpctx->sh_audio->i_bps*8);
564 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_RATE=%d\n", mpctx->sh_audio->samplerate);
565 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_NCH=%d\n", mpctx->sh_audio->channels);
566 start_pts = ds_get_next_pts(mpctx->d_audio);
568 if (video_start_pts != MP_NOPTS_VALUE) {
569 if (start_pts == MP_NOPTS_VALUE || !mpctx->sh_audio ||
570 (mpctx->sh_video && video_start_pts < start_pts))
571 start_pts = video_start_pts;
573 if (start_pts != MP_NOPTS_VALUE)
574 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_START_TIME=%.2f\n", start_pts);
575 else
576 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_START_TIME=unknown\n");
577 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_LENGTH=%.2f\n", get_time_length(mpctx));
578 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_SEEKABLE=%d\n",
579 mpctx->stream->seek && (!mpctx->demuxer || mpctx->demuxer->seekable));
580 if (mpctx->demuxer) {
581 if (mpctx->demuxer->num_chapters == 0)
582 stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_NUM_CHAPTERS, &mpctx->demuxer->num_chapters);
583 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_CHAPTERS=%d\n", mpctx->demuxer->num_chapters);
587 /// step size of mixer changes
588 int volstep = 3;
590 #ifdef CONFIG_DVDNAV
591 static void mp_dvdnav_context_free(MPContext *ctx){
592 if (ctx->nav_smpi) free_mp_image(ctx->nav_smpi);
593 ctx->nav_smpi = NULL;
594 free(ctx->nav_buffer);
595 ctx->nav_buffer = NULL;
596 ctx->nav_start = NULL;
597 ctx->nav_in_size = 0;
599 #endif
601 static void uninit_subs(struct demuxer *demuxer)
603 for (int i = 0; i < MAX_S_STREAMS; i++) {
604 struct sh_sub *sh = demuxer->s_streams[i];
605 if (sh && sh->initialized)
606 sub_uninit(sh);
610 void uninit_player(struct MPContext *mpctx, unsigned int mask){
611 mask &= mpctx->initialized_flags;
613 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n*** uninit(0x%X)\n",mask);
615 if(mask&INITIALIZED_ACODEC){
616 mpctx->initialized_flags&=~INITIALIZED_ACODEC;
617 current_module="uninit_acodec";
618 if(mpctx->sh_audio) uninit_audio(mpctx->sh_audio);
619 mpctx->sh_audio=NULL;
620 mpctx->mixer.afilter = NULL;
623 if (mask & INITIALIZED_SUB) {
624 mpctx->initialized_flags &= ~INITIALIZED_SUB;
625 if (mpctx->d_sub->sh)
626 sub_switchoff(mpctx->d_sub->sh, mpctx->osd);
629 if(mask&INITIALIZED_VCODEC){
630 mpctx->initialized_flags&=~INITIALIZED_VCODEC;
631 current_module="uninit_vcodec";
632 if(mpctx->sh_video) uninit_video(mpctx->sh_video);
633 mpctx->sh_video=NULL;
634 #ifdef CONFIG_MENU
635 vf_menu=NULL;
636 #endif
639 if(mask&INITIALIZED_DEMUXER){
640 mpctx->initialized_flags&=~INITIALIZED_DEMUXER;
641 current_module="free_demuxer";
642 if (mpctx->num_sources) {
643 mpctx->demuxer = mpctx->sources[0].demuxer;
644 for (int i = 1; i < mpctx->num_sources; i++) {
645 uninit_subs(mpctx->sources[i].demuxer);
646 free_stream(mpctx->sources[i].stream);
647 free_demuxer(mpctx->sources[i].demuxer);
650 talloc_free(mpctx->sources);
651 mpctx->sources = NULL;
652 mpctx->num_sources = 0;
653 talloc_free(mpctx->timeline);
654 mpctx->timeline = NULL;
655 mpctx->num_timeline_parts = 0;
656 talloc_free(mpctx->chapters);
657 mpctx->chapters = NULL;
658 mpctx->num_chapters = 0;
659 mpctx->video_offset = 0;
660 if(mpctx->demuxer){
661 mpctx->stream=mpctx->demuxer->stream;
662 uninit_subs(mpctx->demuxer);
663 free_demuxer(mpctx->demuxer);
665 mpctx->demuxer=NULL;
668 // kill the cache process:
669 if(mask&INITIALIZED_STREAM){
670 mpctx->initialized_flags&=~INITIALIZED_STREAM;
671 current_module="uninit_stream";
672 if(mpctx->stream) free_stream(mpctx->stream);
673 mpctx->stream=NULL;
676 if(mask&INITIALIZED_VO){
677 mpctx->initialized_flags&=~INITIALIZED_VO;
678 current_module="uninit_vo";
679 vo_destroy(mpctx->video_out);
680 mpctx->video_out=NULL;
681 #ifdef CONFIG_DVDNAV
682 mp_dvdnav_context_free(mpctx);
683 #endif
686 // Must be after libvo uninit, as few vo drivers (svgalib) have tty code.
687 if(mask&INITIALIZED_GETCH2){
688 mpctx->initialized_flags&=~INITIALIZED_GETCH2;
689 current_module="uninit_getch2";
690 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[uninit getch2]]]\n");
691 // restore terminal:
692 getch2_disable();
695 if(mask&INITIALIZED_VOBSUB){
696 mpctx->initialized_flags&=~INITIALIZED_VOBSUB;
697 current_module="uninit_vobsub";
698 if(vo_vobsub) vobsub_close(vo_vobsub);
699 vo_vobsub=NULL;
702 if (mask&INITIALIZED_SPUDEC){
703 mpctx->initialized_flags&=~INITIALIZED_SPUDEC;
704 current_module="uninit_spudec";
705 spudec_free(vo_spudec);
706 vo_spudec=NULL;
709 if(mask&INITIALIZED_AO){
710 mpctx->initialized_flags&=~INITIALIZED_AO;
711 current_module="uninit_ao";
712 if (mpctx->edl_muted) mixer_mute(&mpctx->mixer);
713 if (mpctx->audio_out)
714 mpctx->audio_out->uninit(mpctx->stop_play != AT_END_OF_FILE);
715 mpctx->audio_out=NULL;
718 current_module=NULL;
721 void exit_player_with_rc(struct MPContext *mpctx, enum exit_reason how, int rc)
723 if (mpctx->user_muted && !mpctx->edl_muted) mixer_mute(&mpctx->mixer);
724 uninit_player(mpctx, INITIALIZED_ALL);
725 #if defined(__MINGW32__) || defined(__CYGWIN__)
726 timeEndPeriod(1);
727 #endif
728 #ifdef CONFIG_X11
729 vo_uninit(mpctx->x11_state); // Close the X11 connection (if any is open).
730 #endif
732 current_module="uninit_input";
733 mp_input_uninit(mpctx->input);
734 #ifdef CONFIG_MENU
735 if (use_menu)
736 menu_uninit();
737 #endif
739 #ifdef CONFIG_FREETYPE
740 current_module="uninit_font";
741 if (mpctx->osd && mpctx->osd->sub_font != vo_font)
742 free_font_desc(mpctx->osd->sub_font);
743 free_font_desc(vo_font);
744 vo_font = NULL;
745 done_freetype();
746 #endif
747 osd_free(mpctx->osd);
749 #ifdef CONFIG_ASS
750 ass_library_done(ass_library);
751 ass_library = NULL;
752 #endif
754 current_module="exit_player";
756 // free mplayer config
757 if(mpctx->mconfig)
758 m_config_free(mpctx->mconfig);
759 mpctx->mconfig = NULL;
761 if(mpctx->playtree_iter)
762 play_tree_iter_free(mpctx->playtree_iter);
763 mpctx->playtree_iter = NULL;
764 if(mpctx->playtree)
765 play_tree_free(mpctx->playtree, 1);
766 mpctx->playtree = NULL;
768 talloc_free(mpctx->key_fifo);
770 free(edl_records); // free mem allocated for EDL
771 edl_records = NULL;
772 switch(how) {
773 case EXIT_QUIT:
774 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Quit");
775 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=QUIT\n");
776 break;
777 case EXIT_EOF:
778 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","End of file");
779 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=EOF\n");
780 break;
781 case EXIT_ERROR:
782 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Fatal error");
783 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=ERROR\n");
784 break;
785 default:
786 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=NONE\n");
788 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"max framesize was %d bytes\n",max_framesize);
790 exit(rc);
793 static void exit_player(struct MPContext *mpctx, enum exit_reason how)
795 exit_player_with_rc(mpctx, how, 1);
798 #ifndef __MINGW32__
799 static void child_sighandler(int x){
800 pid_t pid;
801 while((pid=waitpid(-1,NULL,WNOHANG)) > 0);
803 #endif
805 #ifdef CONFIG_CRASH_DEBUG
806 static char *prog_path;
807 static int crash_debug = 0;
808 #endif
810 static void exit_sighandler(int x){
811 static int sig_count=0;
812 #ifdef CONFIG_CRASH_DEBUG
813 if (!crash_debug || x != SIGTRAP)
814 #endif
815 ++sig_count;
816 if(sig_count==5)
818 /* We're crashing bad and can't uninit cleanly :(
819 * by popular request, we make one last (dirty)
820 * effort to restore the user's
821 * terminal. */
822 getch2_disable();
823 exit(1);
825 if(sig_count==6) exit(1);
826 if(sig_count>6){
827 // can't stop :(
828 #ifndef __MINGW32__
829 kill(getpid(),SIGKILL);
830 #endif
832 mp_msg(MSGT_CPLAYER, MSGL_FATAL, "\n");
833 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,
834 "\nMPlayer interrupted by signal %d in module: %s\n", x,
835 current_module ? current_module : "unknown");
836 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SIGNAL=%d\n", x);
837 if(sig_count<=1)
838 switch(x){
839 case SIGINT:
840 case SIGPIPE:
841 case SIGQUIT:
842 case SIGTERM:
843 case SIGKILL:
844 async_quit_request = 1;
845 return; // killed from keyboard (^C) or killed [-9]
846 case SIGILL:
847 #if CONFIG_RUNTIME_CPUDETECT
848 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL_RTCpuSel);
849 #else
850 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL);
851 #endif
852 case SIGFPE:
853 case SIGSEGV:
854 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGSEGV_SIGFPE);
855 default:
856 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGCRASH);
857 #ifdef CONFIG_CRASH_DEBUG
858 if (crash_debug) {
859 int gdb_pid;
860 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forking...\n");
861 gdb_pid = fork();
862 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forked...\n");
863 if (gdb_pid == 0) { // We are the child
864 char spid[20];
865 snprintf(spid, sizeof(spid), "%i", getppid());
866 getch2_disable(); // allow terminal to work properly with gdb
867 if (execlp("gdb", "gdb", prog_path, spid, "-ex", "bt", NULL) == -1)
868 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't start gdb\n");
869 } else if (gdb_pid < 0)
870 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't fork\n");
871 else {
872 waitpid(gdb_pid, NULL, 0);
874 if (x == SIGTRAP) return;
876 #endif
878 getch2_disable();
879 exit(1);
882 #include "cfg-mplayer.h"
884 static int cfg_include(m_option_t *conf, char *filename)
886 return m_config_parse_config_file(conf->priv, filename);
889 static void parse_cfgfiles(struct MPContext *mpctx, m_config_t* conf)
891 struct MPOpts *opts = &mpctx->opts;
892 char *conffile;
893 int conffile_fd;
894 if (!(opts->noconfig & 2) &&
895 m_config_parse_config_file(conf, MPLAYER_CONFDIR "/mplayer.conf") < 0)
896 exit_player(mpctx, EXIT_NONE);
897 if ((conffile = get_path("")) == NULL) {
898 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"Cannot find HOME directory.\n");
899 } else {
900 #ifdef __MINGW32__
901 mkdir(conffile);
902 #else
903 mkdir(conffile, 0777);
904 #endif
905 free(conffile);
906 if ((conffile = get_path("config")) == NULL) {
907 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"get_path(\"config\") problem\n");
908 } else {
909 if ((conffile_fd = open(conffile, O_CREAT | O_EXCL | O_WRONLY, 0666)) != -1) {
910 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Creating config file: %s\n", conffile);
911 write(conffile_fd, default_config, strlen(default_config));
912 close(conffile_fd);
914 if (!(opts->noconfig & 1) &&
915 m_config_parse_config_file(conf, conffile) < 0)
916 exit_player(mpctx, EXIT_NONE);
917 free(conffile);
922 #define PROFILE_CFG_PROTOCOL "protocol."
924 static void load_per_protocol_config (m_config_t* conf, const char *const file)
926 char *str;
927 char protocol[strlen (PROFILE_CFG_PROTOCOL) + strlen (file) + 1];
928 m_profile_t *p;
930 /* does filename actually uses a protocol ? */
931 str = strstr (file, "://");
932 if (!str)
933 return;
935 sprintf (protocol, "%s%s", PROFILE_CFG_PROTOCOL, file);
936 protocol[strlen (PROFILE_CFG_PROTOCOL)+strlen(file)-strlen(str)] = '\0';
937 p = m_config_get_profile (conf, protocol);
938 if (p)
940 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading protocol-related profile '%s'\n", protocol);
941 m_config_set_profile(conf,p);
945 #define PROFILE_CFG_EXTENSION "extension."
947 static void load_per_extension_config (m_config_t* conf, const char *const file)
949 char *str;
950 char extension[strlen (PROFILE_CFG_EXTENSION) + 8];
951 m_profile_t *p;
953 /* does filename actually have an extension ? */
954 str = strrchr (file, '.');
955 if (!str)
956 return;
958 sprintf (extension, PROFILE_CFG_EXTENSION);
959 strncat (extension, ++str, 7);
960 p = m_config_get_profile (conf, extension);
961 if (p)
963 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", extension);
964 m_config_set_profile(conf,p);
968 #define PROFILE_CFG_VO "vo."
969 #define PROFILE_CFG_AO "ao."
971 static void load_per_output_config (m_config_t* conf, char *cfg, char *out)
973 char profile[strlen (cfg) + strlen (out) + 1];
974 m_profile_t *p;
976 sprintf (profile, "%s%s", cfg, out);
977 p = m_config_get_profile (conf, profile);
978 if (p)
980 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", profile);
981 m_config_set_profile(conf,p);
986 * Tries to load a config file
987 * @return 0 if file was not found, 1 otherwise
989 static int try_load_config(m_config_t *conf, const char *file)
991 struct stat st;
992 if (stat(file, &st))
993 return 0;
994 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Loading config '%s'\n", file);
995 m_config_parse_config_file (conf, file);
996 return 1;
999 static void load_per_file_config (m_config_t* conf, const char *const file)
1001 char *confpath;
1002 char cfg[PATH_MAX];
1003 const char *name;
1005 if (strlen(file) > PATH_MAX - 14) {
1006 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Filename is too long, can not load file or directory specific config files\n");
1007 return;
1009 sprintf (cfg, "%s.conf", file);
1011 name = mp_basename(cfg);
1012 if (use_filedir_conf) {
1013 char dircfg[PATH_MAX];
1014 strcpy(dircfg, cfg);
1015 strcpy(dircfg + (name - cfg), "mplayer.conf");
1016 try_load_config(conf, dircfg);
1018 if (try_load_config(conf, cfg))
1019 return;
1022 if ((confpath = get_path (name)) != NULL)
1024 try_load_config(conf, confpath);
1026 free (confpath);
1030 /* When libmpdemux performs a blocking operation (network connection or
1031 * cache filling) if the operation fails we use this function to check
1032 * if it was interrupted by the user.
1033 * The function returns a new value for eof. */
1034 static int libmpdemux_was_interrupted(struct MPContext *mpctx, int stop_play)
1036 mp_cmd_t* cmd;
1037 if((cmd = mp_input_get_cmd(mpctx->input, 0, 0)) != NULL) {
1038 switch(cmd->id) {
1039 case MP_CMD_QUIT:
1040 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
1041 case MP_CMD_PLAY_TREE_STEP: {
1042 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_ENTRY : PT_PREV_ENTRY;
1043 mpctx->play_tree_step = (cmd->args[0].v.i == 0) ? 1 : cmd->args[0].v.i;
1044 } break;
1045 case MP_CMD_PLAY_TREE_UP_STEP: {
1046 stop_play = (cmd->args[0].v.i > 0) ? PT_UP_NEXT : PT_UP_PREV;
1047 } break;
1048 case MP_CMD_PLAY_ALT_SRC_STEP: {
1049 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_SRC : PT_PREV_SRC;
1050 } break;
1052 mp_cmd_free(cmd);
1054 return stop_play;
1057 static int playtree_add_playlist(struct MPContext *mpctx, play_tree_t* entry)
1059 play_tree_add_bpf(entry,mpctx->filename);
1062 if(!entry) {
1063 entry = mpctx->playtree_iter->tree;
1064 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1065 return PT_NEXT_ENTRY;
1067 if(mpctx->playtree_iter->tree == entry ) { // Loop with a single file
1068 if(play_tree_iter_up_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1069 return PT_NEXT_ENTRY;
1072 play_tree_remove(entry,1,1);
1073 return PT_NEXT_SRC;
1075 play_tree_insert_entry(mpctx->playtree_iter->tree,entry);
1076 play_tree_set_params_from(entry,mpctx->playtree_iter->tree);
1077 entry = mpctx->playtree_iter->tree;
1078 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1079 return PT_NEXT_ENTRY;
1081 play_tree_remove(entry,1,1);
1083 return PT_NEXT_SRC;
1086 void add_subtitles(struct MPContext *mpctx, char *filename, float fps, int noerr)
1088 struct MPOpts *opts = &mpctx->opts;
1089 sub_data *subd = NULL;
1090 struct ass_track *asst = NULL;
1091 bool is_native_ass = false;
1093 if (filename == NULL || mpctx->set_of_sub_size >= MAX_SUBTITLE_FILES)
1094 return;
1096 #ifdef CONFIG_ASS
1097 if (opts->ass_enabled) {
1098 #ifdef CONFIG_ICONV
1099 asst = mp_ass_read_stream(ass_library, filename, sub_cp);
1100 #else
1101 asst = mp_ass_read_stream(ass_library, filename, 0);
1102 #endif
1103 is_native_ass = asst;
1104 if (!asst) {
1105 subd = sub_read_file(filename, fps, &mpctx->opts);
1106 if (subd) {
1107 asst = mp_ass_read_subdata(ass_library, subd, fps);
1108 sub_free(subd);
1109 subd = NULL;
1112 } else
1113 #endif
1114 subd = sub_read_file(filename, fps, &mpctx->opts);
1117 if (!asst && !subd) {
1118 mp_tmsg(MSGT_CPLAYER, noerr ? MSGL_WARN : MSGL_ERR,
1119 "Cannot load subtitles: %s\n", filename_recode(filename));
1120 return;
1123 mpctx->set_of_ass_tracks[mpctx->set_of_sub_size] = asst;
1124 mpctx->set_of_subtitles[mpctx->set_of_sub_size] = subd;
1125 mpctx->track_was_native_ass[mpctx->set_of_sub_size] = is_native_ass;
1126 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_ID=%d\n", mpctx->set_of_sub_size);
1127 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_FILENAME=%s\n",
1128 filename_recode(filename));
1129 ++mpctx->set_of_sub_size;
1130 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "SUB: Added subtitle file (%d): %s\n", mpctx->set_of_sub_size,
1131 filename_recode(filename));
1134 void init_vo_spudec(struct MPContext *mpctx)
1136 spudec_free(vo_spudec);
1137 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
1138 vo_spudec = NULL;
1140 // we currently can't work without video stream
1141 if (!mpctx->sh_video)
1142 return;
1144 if (spudec_ifo) {
1145 unsigned int palette[16], width, height;
1146 current_module="spudec_init_vobsub";
1147 if (vobsub_parse_ifo(NULL,spudec_ifo, palette, &width, &height, 1, -1, NULL) >= 0)
1148 vo_spudec=spudec_new_scaled(palette, width, height, NULL, 0);
1151 #ifdef CONFIG_DVDREAD
1152 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVD) {
1153 current_module="spudec_init_dvdread";
1154 vo_spudec=spudec_new_scaled(((dvd_priv_t *)(mpctx->stream->priv))->cur_pgc->palette,
1155 mpctx->sh_video->disp_w, mpctx->sh_video->disp_h,
1156 NULL, 0);
1158 #endif
1160 #ifdef CONFIG_DVDNAV
1161 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVDNAV) {
1162 unsigned int *palette = mp_dvdnav_get_spu_clut(mpctx->stream);
1163 current_module="spudec_init_dvdnav";
1164 vo_spudec=spudec_new_scaled(palette, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, NULL, 0);
1166 #endif
1168 if (vo_spudec==NULL) {
1169 sh_sub_t *sh = mpctx->d_sub->sh;
1170 current_module="spudec_init_normal";
1171 vo_spudec=spudec_new_scaled(NULL, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, sh->extradata, sh->extradata_len);
1172 spudec_set_font_factor(vo_spudec,font_factor);
1175 if (vo_spudec!=NULL) {
1176 mpctx->initialized_flags|=INITIALIZED_SPUDEC;
1177 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
1182 * In Mac OS X the SDL-lib is built upon Cocoa. The easiest way to
1183 * make it all work is to use the builtin SDL-bootstrap code, which
1184 * will be done automatically by replacing our main() if we include SDL.h.
1186 #if defined(__APPLE__) && defined(CONFIG_SDL)
1187 #ifdef CONFIG_SDL_SDL_H
1188 #include <SDL/SDL.h>
1189 #else
1190 #include <SDL.h>
1191 #endif
1192 #endif
1195 * \brief append a formatted string
1196 * \param buf buffer to print into
1197 * \param pos position of terminating 0 in buf
1198 * \param len maximum number of characters in buf, not including terminating 0
1199 * \param format printf format string
1201 static void saddf(char *buf, unsigned *pos, int len, const char *format, ...)
1203 va_list va;
1204 va_start(va, format);
1205 *pos += vsnprintf(&buf[*pos], len - *pos, format, va);
1206 va_end(va);
1207 if (*pos >= len ) {
1208 buf[len] = 0;
1209 *pos = len;
1214 * \brief append time in the hh:mm:ss.f format
1215 * \param buf buffer to print into
1216 * \param pos position of terminating 0 in buf
1217 * \param len maximum number of characters in buf, not including terminating 0
1218 * \param time time value to convert/append
1220 static void sadd_hhmmssf(char *buf, unsigned *pos, int len, float time) {
1221 int64_t tenths = 10 * time;
1222 int f1 = tenths % 10;
1223 int ss = (tenths / 10) % 60;
1224 int mm = (tenths / 600) % 60;
1225 int hh = tenths / 36000;
1226 if (time <= 0) {
1227 saddf(buf, pos, len, "unknown");
1228 return;
1230 if (hh > 0)
1231 saddf(buf, pos, len, "%2d:", hh);
1232 if (hh > 0 || mm > 0)
1233 saddf(buf, pos, len, "%02d:", mm);
1234 saddf(buf, pos, len, "%02d.%1d", ss, f1);
1237 static void print_status(struct MPContext *mpctx, double a_pos, bool at_frame)
1239 struct MPOpts *opts = &mpctx->opts;
1240 sh_video_t * const sh_video = mpctx->sh_video;
1242 if (mpctx->sh_audio && a_pos == MP_NOPTS_VALUE)
1243 a_pos = playing_audio_pts(mpctx);
1244 if (mpctx->sh_audio && sh_video && at_frame) {
1245 mpctx->last_av_difference = a_pos - mpctx->video_pts - audio_delay;
1246 if (mpctx->time_frame > 0)
1247 mpctx->last_av_difference += mpctx->time_frame * opts->playback_speed;
1248 if (mpctx->last_av_difference > 0.5 && drop_frame_cnt > 50
1249 && !mpctx->drop_message_shown) {
1250 mp_tmsg(MSGT_AVSYNC,MSGL_WARN,SystemTooSlow);
1251 mpctx->drop_message_shown = true;
1254 if (opts->quiet)
1255 return;
1258 int width;
1259 char *line;
1260 unsigned pos = 0;
1261 get_screen_size();
1262 if (screen_width > 0)
1263 width = screen_width;
1264 else
1265 width = 80;
1266 #if defined(__MINGW32__) || defined(__CYGWIN__) || defined(__OS2__)
1267 /* Windows command line is broken (MinGW's rxvt works, but we
1268 * should not depend on that). */
1269 width--;
1270 #endif
1271 line = malloc(width + 1); // one additional char for the terminating null
1273 // Audio time
1274 if (mpctx->sh_audio) {
1275 saddf(line, &pos, width, "A:%6.1f ", a_pos);
1276 if (!sh_video) {
1277 float len = get_time_length(mpctx);
1278 saddf(line, &pos, width, "(");
1279 sadd_hhmmssf(line, &pos, width, a_pos);
1280 saddf(line, &pos, width, ") of %.1f (", len);
1281 sadd_hhmmssf(line, &pos, width, len);
1282 saddf(line, &pos, width, ") ");
1286 // Video time
1287 if (sh_video)
1288 saddf(line, &pos, width, "V:%6.1f ", mpctx->video_pts);
1290 // A-V sync
1291 if (mpctx->sh_audio && sh_video)
1292 saddf(line, &pos, width, "A-V:%7.3f ct:%7.3f ",
1293 mpctx->last_av_difference, mpctx->total_avsync_change);
1295 // Video stats
1296 if (sh_video)
1297 saddf(line, &pos, width, "%3d/%3d ",
1298 (int)sh_video->num_frames,
1299 (int)sh_video->num_frames_decoded);
1301 // CPU usage
1302 if (sh_video) {
1303 if (sh_video->timer > 0.5)
1304 saddf(line, &pos, width, "%2d%% %2d%% %4.1f%% ",
1305 (int)(100.0*video_time_usage*opts->playback_speed/(double)sh_video->timer),
1306 (int)(100.0*vout_time_usage*opts->playback_speed/(double)sh_video->timer),
1307 (100.0*audio_time_usage*opts->playback_speed/(double)sh_video->timer));
1308 else
1309 saddf(line, &pos, width, "??%% ??%% ??,?%% ");
1310 } else if (mpctx->sh_audio) {
1311 if (mpctx->delay > 0.5)
1312 saddf(line, &pos, width, "%4.1f%% ",
1313 100.0*audio_time_usage/(double)mpctx->delay);
1314 else
1315 saddf(line, &pos, width, "??,?%% ");
1318 // VO stats
1319 if (sh_video)
1320 saddf(line, &pos, width, "%d %d ", drop_frame_cnt, output_quality);
1322 #ifdef CONFIG_STREAM_CACHE
1323 // cache stats
1324 if (stream_cache_size > 0)
1325 saddf(line, &pos, width, "%d%% ", cache_fill_status(mpctx->stream));
1326 #endif
1328 // other
1329 if (opts->playback_speed != 1)
1330 saddf(line, &pos, width, "%4.2fx ", opts->playback_speed);
1332 // end
1333 if (erase_to_end_of_line) {
1334 line[pos] = 0;
1335 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s%s\r", line, erase_to_end_of_line);
1336 } else {
1337 memset(&line[pos], ' ', width - pos);
1338 line[width] = 0;
1339 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s\r", line);
1341 free(line);
1345 * \brief build a chain of audio filters that converts the input format
1346 * to the ao's format, taking into account the current playback_speed.
1347 * \param sh_audio describes the requested input format of the chain.
1348 * \param ao_data describes the requested output format of the chain.
1350 static int build_afilter_chain(struct MPContext *mpctx, sh_audio_t *sh_audio,
1351 ao_data_t *ao_data)
1353 struct MPOpts *opts = &mpctx->opts;
1354 int new_srate;
1355 int result;
1356 if (!sh_audio)
1358 mpctx->mixer.afilter = NULL;
1359 return 0;
1361 if(af_control_any_rev(sh_audio->afilter,
1362 AF_CONTROL_PLAYBACK_SPEED | AF_CONTROL_SET,
1363 &opts->playback_speed)) {
1364 new_srate = sh_audio->samplerate;
1365 } else {
1366 new_srate = sh_audio->samplerate * opts->playback_speed;
1367 if (new_srate != ao_data->samplerate) {
1368 // limits are taken from libaf/af_resample.c
1369 if (new_srate < 8000)
1370 new_srate = 8000;
1371 if (new_srate > 192000)
1372 new_srate = 192000;
1373 opts->playback_speed = (float)new_srate / (float)sh_audio->samplerate;
1376 result = init_audio_filters(sh_audio, new_srate,
1377 &ao_data->samplerate, &ao_data->channels, &ao_data->format);
1378 mpctx->mixer.afilter = sh_audio->afilter;
1379 return result;
1383 typedef struct mp_osd_msg mp_osd_msg_t;
1384 struct mp_osd_msg {
1385 /// Previous message on the stack.
1386 mp_osd_msg_t* prev;
1387 /// Message text.
1388 char msg[128];
1389 int id,level,started;
1390 /// Display duration in ms.
1391 unsigned time;
1394 /// OSD message stack.
1395 static mp_osd_msg_t* osd_msg_stack = NULL;
1398 * \brief Add a message on the OSD message stack
1400 * If a message with the same id is already present in the stack
1401 * it is pulled on top of the stack, otherwise a new message is created.
1404 static void set_osd_msg_va(int id, int level, int time, const char *fmt,
1405 va_list ap)
1407 mp_osd_msg_t *msg,*last=NULL;
1408 int r;
1410 // look if the id is already in the stack
1411 for(msg = osd_msg_stack ; msg && msg->id != id ;
1412 last = msg, msg = msg->prev);
1413 // not found: alloc it
1414 if(!msg) {
1415 msg = calloc(1,sizeof(mp_osd_msg_t));
1416 msg->prev = osd_msg_stack;
1417 osd_msg_stack = msg;
1418 } else if(last) { // found, but it's not on top of the stack
1419 last->prev = msg->prev;
1420 msg->prev = osd_msg_stack;
1421 osd_msg_stack = msg;
1423 // write the msg
1424 r = vsnprintf(msg->msg, 128, fmt, ap);
1425 if(r >= 128) msg->msg[127] = 0;
1426 // set id and time
1427 msg->id = id;
1428 msg->level = level;
1429 msg->time = time;
1433 void set_osd_msg(int id, int level, int time, const char *fmt, ...)
1435 va_list ap;
1436 va_start(ap, fmt);
1437 set_osd_msg_va(id, level, time, fmt, ap);
1438 va_end(ap);
1441 void set_osd_tmsg(int id, int level, int time, const char *fmt, ...)
1443 va_list ap;
1444 va_start(ap, fmt);
1445 set_osd_msg_va(id, level, time, mp_gtext(fmt), ap);
1446 va_end(ap);
1451 * \brief Remove a message from the OSD stack
1453 * This function can be used to get rid of a message right away.
1457 void rm_osd_msg(int id) {
1458 mp_osd_msg_t *msg,*last=NULL;
1460 // Search for the msg
1461 for(msg = osd_msg_stack ; msg && msg->id != id ;
1462 last = msg, msg = msg->prev);
1463 if(!msg) return;
1465 // Detach it from the stack and free it
1466 if(last)
1467 last->prev = msg->prev;
1468 else
1469 osd_msg_stack = msg->prev;
1470 free(msg);
1474 * \brief Remove all messages from the OSD stack
1478 static void clear_osd_msgs(void) {
1479 mp_osd_msg_t* msg = osd_msg_stack, *prev = NULL;
1480 while(msg) {
1481 prev = msg->prev;
1482 free(msg);
1483 msg = prev;
1485 osd_msg_stack = NULL;
1489 * \brief Get the current message from the OSD stack.
1491 * This function decrements the message timer and destroys the old ones.
1492 * The message that should be displayed is returned (if any).
1496 static mp_osd_msg_t* get_osd_msg(struct MPContext *mpctx)
1498 struct MPOpts *opts = &mpctx->opts;
1499 mp_osd_msg_t *msg,*prev,*last = NULL;
1500 static unsigned last_update = 0;
1501 unsigned now = GetTimerMS();
1502 unsigned diff;
1503 char hidden_dec_done = 0;
1505 if (mpctx->osd_visible) {
1506 // 36000000 means max timed visibility is 1 hour into the future, if
1507 // the difference is greater assume it's wrapped around from below 0
1508 if (mpctx->osd_visible - now > 36000000) {
1509 mpctx->osd_visible = 0;
1510 vo_osd_progbar_type = -1; // disable
1511 vo_osd_changed(OSDTYPE_PROGBAR);
1512 mpctx->osd_function = mpctx->paused ? OSD_PAUSE : OSD_PLAY;
1515 if (mpctx->osd_show_percentage_until - now > 36000000)
1516 mpctx->osd_show_percentage_until = 0;
1518 if(!last_update) last_update = now;
1519 diff = now >= last_update ? now - last_update : 0;
1521 last_update = now;
1523 // Look for the first message in the stack with high enough level.
1524 for(msg = osd_msg_stack ; msg ; last = msg, msg = prev) {
1525 prev = msg->prev;
1526 if (msg->level > opts->osd_level && hidden_dec_done)
1527 continue;
1528 // The message has a high enough level or it is the first hidden one
1529 // in both cases we decrement the timer or kill it.
1530 if(!msg->started || msg->time > diff) {
1531 if(msg->started) msg->time -= diff;
1532 else msg->started = 1;
1533 // display it
1534 if (msg->level <= opts->osd_level)
1535 return msg;
1536 hidden_dec_done = 1;
1537 continue;
1539 // kill the message
1540 free(msg);
1541 if(last) {
1542 last->prev = prev;
1543 msg = last;
1544 } else {
1545 osd_msg_stack = prev;
1546 msg = NULL;
1549 // Nothing found
1550 return NULL;
1554 * \brief Display the OSD bar.
1556 * Display the OSD bar or fall back on a simple message.
1560 void set_osd_bar(struct MPContext *mpctx, int type,const char* name,double min,double max,double val) {
1561 struct MPOpts *opts = &mpctx->opts;
1562 if (opts->osd_level < 1)
1563 return;
1565 if(mpctx->sh_video) {
1566 mpctx->osd_visible = (GetTimerMS() + 1000) | 1;
1567 vo_osd_progbar_type = type;
1568 vo_osd_progbar_value = 256*(val-min)/(max-min);
1569 vo_osd_changed(OSDTYPE_PROGBAR);
1570 return;
1573 set_osd_msg(OSD_MSG_BAR, 1, opts->osd_duration, "%s: %d %%",
1574 name, ROUND(100*(val-min)/(max-min)));
1578 * \brief Display text subtitles on the OSD
1580 void set_osd_subtitle(struct MPContext *mpctx, subtitle *subs)
1582 int i;
1583 vo_sub = subs;
1584 vo_osd_changed(OSDTYPE_SUBTITLE);
1585 if (!mpctx->sh_video) {
1586 // reverse order, since newest set_osd_msg is displayed first
1587 for (i = SUB_MAX_TEXT - 1; i >= 0; i--) {
1588 if (!subs || i >= subs->lines || !subs->text[i])
1589 rm_osd_msg(OSD_MSG_SUB_BASE + i);
1590 else {
1591 // HACK: currently display time for each sub line except the last is set to 2 seconds.
1592 int display_time = i == subs->lines - 1 ? 180000 : 2000;
1593 set_osd_msg(OSD_MSG_SUB_BASE + i, 1, display_time, "%s", subs->text[i]);
1600 * \brief Update the OSD message line.
1602 * This function displays the current message on the vo OSD or on the term.
1603 * If the stack is empty and the OSD level is high enough the timer
1604 * is displayed (only on the vo OSD).
1608 static void update_osd_msg(struct MPContext *mpctx)
1610 struct MPOpts *opts = &mpctx->opts;
1611 mp_osd_msg_t *msg;
1612 struct osd_state *osd = mpctx->osd;
1613 char osd_text_timer[128];
1615 if (mpctx->add_osd_seek_info) {
1616 double percentage = get_percent_pos(mpctx);
1617 set_osd_bar(mpctx, 0, "Position", 0, 100, percentage);
1618 if (mpctx->sh_video)
1619 mpctx->osd_show_percentage_until = (GetTimerMS() + 1000) | 1;
1620 mpctx->add_osd_seek_info = false;
1623 // Look if we have a msg
1624 if((msg = get_osd_msg(mpctx))) {
1625 if (strcmp(osd->osd_text, msg->msg)) {
1626 strncpy(osd->osd_text, msg->msg, 127);
1627 if(mpctx->sh_video) vo_osd_changed(OSDTYPE_OSD); else
1628 if(opts->term_osd)
1629 mp_msg(MSGT_CPLAYER,MSGL_STATUS, "%s%s\n", opts->term_osd_esc,
1630 msg->msg);
1632 return;
1635 if(mpctx->sh_video) {
1636 // fallback on the timer
1637 if (opts->osd_level >= 2) {
1638 int len = get_time_length(mpctx);
1639 int percentage = -1;
1640 char percentage_text[10];
1641 int pts = get_current_time(mpctx);
1643 if (mpctx->osd_show_percentage_until)
1644 percentage = get_percent_pos(mpctx);
1646 if (percentage >= 0)
1647 snprintf(percentage_text, 9, " (%d%%)", percentage);
1648 else
1649 percentage_text[0] = 0;
1651 if (opts->osd_level == 3)
1652 snprintf(osd_text_timer, 63,
1653 "%c %02d:%02d:%02d / %02d:%02d:%02d%s",
1654 mpctx->osd_function,pts/3600,(pts/60)%60,pts%60,
1655 len/3600,(len/60)%60,len%60,percentage_text);
1656 else
1657 snprintf(osd_text_timer, 63, "%c %02d:%02d:%02d%s",
1658 mpctx->osd_function,pts/3600,(pts/60)%60,
1659 pts%60,percentage_text);
1660 } else
1661 osd_text_timer[0]=0;
1663 if (strcmp(osd->osd_text, osd_text_timer)) {
1664 strncpy(osd->osd_text, osd_text_timer, 63);
1665 vo_osd_changed(OSDTYPE_OSD);
1667 return;
1670 // Clear the term osd line
1671 if (opts->term_osd && osd->osd_text[0]) {
1672 osd->osd_text[0] = 0;
1673 printf("%s\n", opts->term_osd_esc);
1677 ///@}
1678 // OSDMsgStack
1681 void reinit_audio_chain(struct MPContext *mpctx)
1683 struct MPOpts *opts = &mpctx->opts;
1684 if (!mpctx->sh_audio)
1685 return;
1686 if (!(mpctx->initialized_flags & INITIALIZED_ACODEC)) {
1687 current_module="init_audio_codec";
1688 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1689 if(!init_best_audio_codec(mpctx->sh_audio,audio_codec_list,audio_fm_list)){
1690 goto init_error;
1692 mpctx->initialized_flags|=INITIALIZED_ACODEC;
1693 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1697 current_module="af_preinit";
1698 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1699 ao_data.samplerate=force_srate;
1700 ao_data.channels=0;
1701 ao_data.format = opts->audio_output_format;
1703 // first init to detect best values
1704 if(!init_audio_filters(mpctx->sh_audio, // preliminary init
1705 // input:
1706 mpctx->sh_audio->samplerate,
1707 // output:
1708 &ao_data.samplerate, &ao_data.channels, &ao_data.format)){
1709 mp_tmsg(MSGT_CPLAYER,MSGL_ERR, "Error at audio filter chain "
1710 "pre-init!\n");
1711 exit_player(mpctx, EXIT_ERROR);
1713 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1714 current_module="ao2_init";
1715 ao_data.buffersize = opts->ao_buffersize;
1716 mpctx->audio_out = init_best_audio_out(opts->audio_driver_list,
1717 0, // plugin flag
1718 ao_data.samplerate,
1719 ao_data.channels,
1720 ao_data.format, 0);
1721 if(!mpctx->audio_out){
1722 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Could not open/initialize audio device -> no sound.\n");
1723 goto init_error;
1725 mpctx->initialized_flags|=INITIALIZED_AO;
1726 mp_msg(MSGT_CPLAYER,MSGL_INFO,"AO: [%s] %dHz %dch %s (%d bytes per sample)\n",
1727 mpctx->audio_out->info->short_name,
1728 ao_data.samplerate, ao_data.channels,
1729 af_fmt2str_short(ao_data.format),
1730 af_fmt2bits(ao_data.format)/8 );
1731 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Description: %s\nAO: Author: %s\n",
1732 mpctx->audio_out->info->name, mpctx->audio_out->info->author);
1733 if(strlen(mpctx->audio_out->info->comment) > 0)
1734 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Comment: %s\n", mpctx->audio_out->info->comment);
1737 // init audio filters:
1738 current_module="af_init";
1739 if(!build_afilter_chain(mpctx, mpctx->sh_audio, &ao_data)) {
1740 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Couldn't find matching filter/ao format!\n");
1741 goto init_error;
1743 mpctx->mixer.audio_out = mpctx->audio_out;
1744 mpctx->mixer.volstep = volstep;
1745 mpctx->syncing_audio = true;
1746 return;
1748 init_error:
1749 uninit_player(mpctx, INITIALIZED_ACODEC|INITIALIZED_AO); // close codec and possibly AO
1750 mpctx->sh_audio=mpctx->d_audio->sh=NULL; // -> nosound
1751 mpctx->d_audio->id = -2;
1755 ///@}
1756 // Command2Property
1759 // Return pts value corresponding to the end point of audio written to the
1760 // ao so far.
1761 static double written_audio_pts(struct MPContext *mpctx)
1763 sh_audio_t *sh_audio = mpctx->sh_audio;
1764 demux_stream_t *d_audio = mpctx->d_audio;
1765 double buffered_output;
1766 // first calculate the end pts of audio that has been output by decoder
1767 double a_pts = sh_audio->pts;
1768 if (a_pts != MP_NOPTS_VALUE)
1769 // Good, decoder supports new way of calculating audio pts.
1770 // sh_audio->pts is the timestamp of the latest input packet with
1771 // known pts that the decoder has decoded. sh_audio->pts_bytes is
1772 // the amount of bytes the decoder has written after that timestamp.
1773 a_pts += sh_audio->pts_bytes / (double) sh_audio->o_bps;
1774 else {
1775 // Decoder doesn't support new way of calculating pts (or we're
1776 // being called before it has decoded anything with known timestamp).
1777 // Use the old method of audio pts calculation: take the timestamp
1778 // of last packet with known pts the decoder has read data from,
1779 // and add amount of bytes read after the beginning of that packet
1780 // divided by input bps. This will be inaccurate if the input/output
1781 // ratio is not constant for every audio packet or if it is constant
1782 // but not accurately known in sh_audio->i_bps.
1784 a_pts = d_audio->pts;
1785 // ds_tell_pts returns bytes read after last timestamp from
1786 // demuxing layer, decoder might use sh_audio->a_in_buffer for bytes
1787 // it has read but not decoded
1788 if (sh_audio->i_bps)
1789 a_pts += (ds_tell_pts(d_audio) - sh_audio->a_in_buffer_len) /
1790 (double)sh_audio->i_bps;
1792 // Now a_pts hopefully holds the pts for end of audio from decoder.
1793 // Substract data in buffers between decoder and audio out.
1795 // Decoded but not filtered
1796 a_pts -= sh_audio->a_buffer_len / (double)sh_audio->o_bps;
1798 // Data buffered in audio filters, measured in bytes of "missing" output
1799 buffered_output = af_calc_delay(sh_audio->afilter);
1801 // Data that was ready for ao but was buffered because ao didn't fully
1802 // accept everything to internal buffers yet
1803 buffered_output += sh_audio->a_out_buffer_len;
1805 // Filters divide audio length by playback_speed, so multiply by it
1806 // to get the length in original units without speedup or slowdown
1807 a_pts -= buffered_output * mpctx->opts.playback_speed / ao_data.bps;
1809 return a_pts + mpctx->video_offset;
1812 // Return pts value corresponding to currently playing audio.
1813 double playing_audio_pts(struct MPContext *mpctx)
1815 return written_audio_pts(mpctx) - mpctx->opts.playback_speed *
1816 mpctx->audio_out->get_delay();
1819 static bool is_av_sub(int type)
1821 return type == 'b' || type == 'p' || type == 'x';
1824 void update_subtitles(struct MPContext *mpctx, double refpts,
1825 double sub_offset, bool reset)
1827 struct MPOpts *opts = &mpctx->opts;
1828 struct sh_video *sh_video = mpctx->sh_video;
1829 struct demux_stream *d_sub = mpctx->d_sub;
1830 double curpts = refpts + sub_delay;
1831 unsigned char *packet=NULL;
1832 int len;
1833 struct sh_sub *sh_sub = d_sub->sh;
1834 int type = sh_sub ? sh_sub->type : 'v';
1835 static subtitle subs;
1836 if (reset) {
1837 if (sh_sub)
1838 sub_reset(sh_sub, mpctx->osd);
1839 sub_clear_text(&subs, MP_NOPTS_VALUE);
1840 if (vo_sub)
1841 set_osd_subtitle(mpctx, NULL);
1842 if (vo_spudec) {
1843 spudec_reset(vo_spudec);
1844 vo_osd_changed(OSDTYPE_SPU);
1846 #ifdef CONFIG_FFMPEG
1847 if (is_av_sub(type))
1848 reset_avsub(sh_sub);
1849 #endif
1850 return;
1852 // find sub
1853 if (mpctx->subdata) {
1854 if (sub_fps==0) sub_fps = sh_video ? sh_video->fps : 25;
1855 current_module = "find_sub";
1856 find_sub(mpctx, mpctx->subdata, curpts *
1857 (mpctx->subdata->sub_uses_time ? 100. : sub_fps));
1858 if (vo_sub)
1859 mpctx->vo_sub_last = vo_sub;
1862 // DVD sub:
1863 if (vobsub_id >= 0 || type == 'v') {
1864 int timestamp;
1865 current_module = "spudec";
1866 /* Get a sub packet from the DVD or a vobsub */
1867 while(1) {
1868 // Vobsub
1869 len = 0;
1870 if (vo_vobsub) {
1871 if (curpts >= 0) {
1872 len = vobsub_get_packet(vo_vobsub, curpts,
1873 (void**)&packet, &timestamp);
1874 if (len > 0) {
1875 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);
1878 } else {
1879 // DVD sub
1880 len = ds_get_packet_sub(d_sub, (unsigned char**)&packet);
1881 if (len > 0) {
1882 // XXX This is wrong, sh_video->pts can be arbitrarily
1883 // much behind demuxing position. Unfortunately using
1884 // d_video->pts which would have been the simplest
1885 // improvement doesn't work because mpeg specific hacks
1886 // in video.c set d_video->pts to 0.
1887 float x = d_sub->pts - refpts;
1888 if (x > -20 && x < 20) // prevent missing subs on pts reset
1889 timestamp = 90000*d_sub->pts;
1890 else timestamp = 90000*curpts;
1891 mp_dbg(MSGT_CPLAYER, MSGL_V, "\rDVD sub: len=%d "
1892 "v_pts=%5.3f s_pts=%5.3f ts=%d \n", len,
1893 refpts, d_sub->pts, timestamp);
1896 if (len<=0 || !packet) break;
1897 // create it only here, since with some broken demuxers we might
1898 // type = v but no DVD sub and we currently do not change the
1899 // "original frame size" ever after init, leading to wrong-sized
1900 // PGS subtitles.
1901 if (!vo_spudec)
1902 vo_spudec = spudec_new(NULL);
1903 if (vo_vobsub || timestamp >= 0)
1904 spudec_assemble(vo_spudec, packet, len, timestamp);
1906 } else if (is_text_sub(type) || is_av_sub(type) || type == 'd') {
1907 if (type == 'd' && !d_sub->demuxer->teletext) {
1908 tt_stream_props tsp = {0};
1909 void *ptr = &tsp;
1910 if (teletext_control(NULL, TV_VBI_CONTROL_START, &ptr) == VBI_CONTROL_TRUE)
1911 d_sub->demuxer->teletext = ptr;
1913 if (d_sub->non_interleaved)
1914 ds_get_next_pts(d_sub);
1916 while (d_sub->first) {
1917 double subpts = ds_get_next_pts(d_sub) + sub_offset;
1918 if (subpts > curpts) {
1919 // Libass handled subs can be fed to it in advance
1920 if (!opts->ass_enabled || !is_text_sub(type))
1921 break;
1922 // Try to avoid demuxing whole file at once
1923 if (d_sub->non_interleaved && subpts > curpts + 1)
1924 break;
1926 double duration = d_sub->first->duration;
1927 len = ds_get_packet_sub(d_sub, &packet);
1928 if (is_av_sub(type)) {
1929 #ifdef CONFIG_FFMPEG
1930 int ret = decode_avsub(sh_sub, packet, len, subpts, duration);
1931 if (ret < 0)
1932 mp_msg(MSGT_SPUDEC, MSGL_WARN, "lavc failed decoding "
1933 "subtitle\n");
1934 #endif
1935 continue;
1937 if (type == 'm') {
1938 if (len < 2) continue;
1939 len = FFMIN(len - 2, AV_RB16(packet));
1940 packet += 2;
1942 if (type == 'd') {
1943 if (d_sub->demuxer->teletext) {
1944 uint8_t *p = packet;
1945 p++;
1946 len--;
1947 while (len >= 46) {
1948 int sublen = p[1];
1949 if (p[0] == 2 || p[0] == 3)
1950 teletext_control(d_sub->demuxer->teletext,
1951 TV_VBI_CONTROL_DECODE_DVB, p + 2);
1952 p += sublen + 2;
1953 len -= sublen + 2;
1956 continue;
1958 if (sh_sub && sh_sub->active) {
1959 sub_decode(sh_sub, mpctx->osd, packet, len, subpts, duration);
1960 continue;
1962 if (subpts != MP_NOPTS_VALUE) {
1963 if (duration < 0)
1964 sub_clear_text(&subs, MP_NOPTS_VALUE);
1965 if (type == 'a') { // ssa/ass subs without libass => convert to plaintext
1966 int i;
1967 unsigned char* p = packet;
1968 for (i=0; i < 8 && *p != '\0'; p++)
1969 if (*p == ',')
1970 i++;
1971 if (*p == '\0') /* Broken line? */
1972 continue;
1973 len -= p - packet;
1974 packet = p;
1976 double endpts = MP_NOPTS_VALUE;
1977 if (subpts != MP_NOPTS_VALUE && duration >= 0)
1978 endpts = subpts + duration;
1979 sub_add_text(&subs, packet, len, endpts);
1980 set_osd_subtitle(mpctx, &subs);
1982 if (d_sub->non_interleaved)
1983 ds_get_next_pts(d_sub);
1985 if (!opts->ass_enabled)
1986 if (sub_clear_text(&subs, curpts))
1987 set_osd_subtitle(mpctx, &subs);
1989 if (vo_spudec) {
1990 spudec_heartbeat(vo_spudec, 90000*curpts);
1991 if (spudec_changed(vo_spudec))
1992 vo_osd_changed(OSDTYPE_SPU);
1995 current_module=NULL;
1998 static void update_teletext(sh_video_t *sh_video, demuxer_t *demuxer, int reset)
2000 int page_changed;
2002 if (!demuxer->teletext)
2003 return;
2005 //Also forcing page update when such ioctl is not supported or call error occured
2006 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_IS_CHANGED,&page_changed)!=VBI_CONTROL_TRUE)
2007 page_changed=1;
2009 if(!page_changed)
2010 return;
2012 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_GET_VBIPAGE,&vo_osd_teletext_page)!=VBI_CONTROL_TRUE)
2013 vo_osd_teletext_page=NULL;
2014 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_GET_HALF_PAGE,&vo_osd_teletext_half)!=VBI_CONTROL_TRUE)
2015 vo_osd_teletext_half=0;
2016 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_GET_MODE,&vo_osd_teletext_mode)!=VBI_CONTROL_TRUE)
2017 vo_osd_teletext_mode=0;
2018 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_GET_FORMAT,&vo_osd_teletext_format)!=VBI_CONTROL_TRUE)
2019 vo_osd_teletext_format=0;
2020 vo_osd_changed(OSDTYPE_TELETEXT);
2022 teletext_control(demuxer->teletext,TV_VBI_CONTROL_MARK_UNCHANGED,NULL);
2025 static int check_framedrop(struct MPContext *mpctx, double frame_time) {
2026 struct MPOpts *opts = &mpctx->opts;
2027 // check for frame-drop:
2028 current_module = "check_framedrop";
2029 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
2030 static int dropped_frames;
2031 float delay = opts->playback_speed*mpctx->audio_out->get_delay();
2032 float d = delay-mpctx->delay;
2033 ++total_frame_cnt;
2034 // we should avoid dropping too many frames in sequence unless we
2035 // are too late. and we allow 100ms A-V delay here:
2036 if (d < -dropped_frames*frame_time-0.100 && !mpctx->paused
2037 && !mpctx->restart_playback) {
2038 ++drop_frame_cnt;
2039 ++dropped_frames;
2040 return frame_dropping;
2041 } else
2042 dropped_frames = 0;
2044 return 0;
2048 #ifdef HAVE_RTC
2049 int rtc_fd = -1;
2050 #endif
2052 static float timing_sleep(struct MPContext *mpctx, float time_frame)
2054 #ifdef HAVE_RTC
2055 if (rtc_fd >= 0){
2056 // -------- RTC -----------
2057 current_module="sleep_rtc";
2058 while (time_frame > 0.000) {
2059 unsigned long rtc_ts;
2060 if (read(rtc_fd, &rtc_ts, sizeof(rtc_ts)) <= 0)
2061 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC read error: %s\n", strerror(errno));
2062 time_frame -= get_relative_time(mpctx);
2064 } else
2065 #endif
2067 // assume kernel HZ=100 for softsleep, works with larger HZ but with
2068 // unnecessarily high CPU usage
2069 struct MPOpts *opts = &mpctx->opts;
2070 float margin = opts->softsleep ? 0.011 : 0;
2071 current_module = "sleep_timer";
2072 while (time_frame > margin) {
2073 usec_sleep(1000000 * (time_frame - margin));
2074 time_frame -= get_relative_time(mpctx);
2076 if (opts->softsleep){
2077 current_module = "sleep_soft";
2078 if (time_frame < 0)
2079 mp_tmsg(MSGT_AVSYNC, MSGL_WARN, "Warning! Softsleep underflow!\n");
2080 while (time_frame > 0)
2081 time_frame -= get_relative_time(mpctx); // burn the CPU
2084 return time_frame;
2087 static int select_subtitle(MPContext *mpctx)
2089 struct MPOpts *opts = &mpctx->opts;
2090 // find the best sub to use
2091 int id;
2092 int found = 0;
2093 mpctx->global_sub_pos = -1; // no subs by default
2094 if (vobsub_id >= 0) {
2095 // if user asks for a vobsub id, use that first.
2096 id = vobsub_id;
2097 found = mp_property_do("sub_vob", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
2100 if (!found && opts->sub_id >= 0) {
2101 // if user asks for a dvd sub id, use that next.
2102 id = opts->sub_id;
2103 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
2106 if (!found) {
2107 // if there are text subs to use, use those. (autosubs come last here)
2108 id = 0;
2109 found = mp_property_do("sub_file", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
2112 if (!found && opts->sub_id == -1) {
2113 // finally select subs by language and container hints
2114 if (opts->sub_id == -1)
2115 opts->sub_id =
2116 demuxer_sub_track_by_lang_and_default(mpctx->d_sub->demuxer,
2117 opts->sub_lang);
2118 if (opts->sub_id >= 0) {
2119 id = opts->sub_id;
2120 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
2123 return found;
2126 #ifdef CONFIG_DVDNAV
2127 #ifndef FF_B_TYPE
2128 #define FF_B_TYPE 3
2129 #endif
2130 /// store decoded video image
2131 static mp_image_t * mp_dvdnav_copy_mpi(mp_image_t *to_mpi,
2132 mp_image_t *from_mpi) {
2133 mp_image_t *mpi;
2135 /// Do not store B-frames
2136 if (from_mpi->pict_type == FF_B_TYPE)
2137 return to_mpi;
2139 if (to_mpi &&
2140 to_mpi->w == from_mpi->w &&
2141 to_mpi->h == from_mpi->h &&
2142 to_mpi->imgfmt == from_mpi->imgfmt)
2143 mpi = to_mpi;
2144 else {
2145 if (to_mpi)
2146 free_mp_image(to_mpi);
2147 if (from_mpi->w == 0 || from_mpi->h == 0)
2148 return NULL;
2149 mpi = alloc_mpi(from_mpi->w,from_mpi->h,from_mpi->imgfmt);
2152 copy_mpi(mpi,from_mpi);
2153 return mpi;
2156 static void mp_dvdnav_reset_stream (MPContext *ctx) {
2157 struct MPOpts *opts = &ctx->opts;
2158 if (ctx->sh_video) {
2159 /// clear video pts
2160 ctx->d_video->pts = 0.0f;
2161 ctx->sh_video->pts = 0.0f;
2162 ctx->sh_video->i_pts = 0.0f;
2163 ctx->sh_video->last_pts = 0.0f;
2164 ctx->sh_video->num_buffered_pts = 0;
2165 ctx->sh_video->num_frames = 0;
2166 ctx->sh_video->num_frames_decoded = 0;
2167 ctx->sh_video->timer = 0.0f;
2168 ctx->sh_video->stream_delay = 0.0f;
2169 ctx->sh_video->timer = 0;
2170 ctx->demuxer->stream_pts = MP_NOPTS_VALUE;
2173 if (ctx->sh_audio) {
2174 /// free audio packets and reset
2175 ds_free_packs(ctx->d_audio);
2176 audio_delay -= ctx->sh_audio->stream_delay;
2177 ctx->delay =- audio_delay;
2178 ctx->audio_out->reset();
2179 resync_audio_stream(ctx->sh_audio);
2182 audio_delay = 0.0f;
2183 ctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(ctx->stream);
2184 if (opts->sub_lang && opts->sub_id == dvdsub_lang_id) {
2185 dvdsub_lang_id = mp_dvdnav_sid_from_lang(ctx->stream, opts->sub_lang);
2186 if (dvdsub_lang_id != opts->sub_id) {
2187 opts->sub_id = dvdsub_lang_id;
2188 select_subtitle(ctx);
2192 /// clear all EOF related flags
2193 ctx->d_video->eof = ctx->d_audio->eof = ctx->stream->eof = 0;
2196 /// Restore last decoded DVDNAV (still frame)
2197 static mp_image_t *mp_dvdnav_restore_smpi(struct MPContext *mpctx,
2198 int *in_size,
2199 unsigned char **start,
2200 mp_image_t *decoded_frame)
2202 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2203 return decoded_frame;
2205 /// a change occured in dvdnav stream
2206 if (mp_dvdnav_cell_has_changed(mpctx->stream,0)) {
2207 mp_dvdnav_read_wait(mpctx->stream, 1, 1);
2208 mp_dvdnav_context_free(mpctx);
2209 mp_dvdnav_reset_stream(mpctx);
2210 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
2211 mp_dvdnav_cell_has_changed(mpctx->stream,1);
2214 if (*in_size < 0) {
2215 float len;
2217 /// Display still frame, if any
2218 if (mpctx->nav_smpi && !mpctx->nav_buffer)
2219 decoded_frame = mpctx->nav_smpi;
2221 /// increment video frame : continue playing after still frame
2222 len = get_time_length(mpctx);
2223 if (mpctx->sh_video->pts >= len &&
2224 mpctx->sh_video->pts > 0.0 && len > 0.0) {
2225 mp_dvdnav_skip_still(mpctx->stream);
2226 mp_dvdnav_skip_wait(mpctx->stream);
2228 mpctx->sh_video->pts += 1 / mpctx->sh_video->fps;
2230 if (mpctx->nav_buffer) {
2231 *start = mpctx->nav_start;
2232 *in_size = mpctx->nav_in_size;
2233 if (mpctx->nav_start)
2234 memcpy(*start,mpctx->nav_buffer,mpctx->nav_in_size);
2238 return decoded_frame;
2241 /// Save last decoded DVDNAV (still frame)
2242 static void mp_dvdnav_save_smpi(struct MPContext *mpctx, int in_size,
2243 unsigned char *start,
2244 mp_image_t *decoded_frame)
2246 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2247 return;
2249 free(mpctx->nav_buffer);
2251 mpctx->nav_buffer = malloc(in_size);
2252 mpctx->nav_start = start;
2253 mpctx->nav_in_size = mpctx->nav_buffer ? in_size : -1;
2254 if (mpctx->nav_buffer)
2255 memcpy(mpctx->nav_buffer,start,in_size);
2257 if (decoded_frame && mpctx->nav_smpi != decoded_frame)
2258 mpctx->nav_smpi = mp_dvdnav_copy_mpi(mpctx->nav_smpi,decoded_frame);
2260 #endif /* CONFIG_DVDNAV */
2262 /* Modify video timing to match the audio timeline. There are two main
2263 * reasons this is needed. First, video and audio can start from different
2264 * positions at beginning of file or after a seek (MPlayer starts both
2265 * immediately even if they have different pts). Second, the file can have
2266 * audio timestamps that are inconsistent with the duration of the audio
2267 * packets, for example two consecutive timestamp values differing by
2268 * one second but only a packet with enough samples for half a second
2269 * of playback between them.
2271 static void adjust_sync(struct MPContext *mpctx, double frame_time)
2273 current_module = "av_sync";
2275 if (!mpctx->sh_audio || mpctx->syncing_audio)
2276 return;
2278 double a_pts = written_audio_pts(mpctx) - mpctx->delay;
2279 double v_pts = mpctx->sh_video->pts;
2280 double av_delay = a_pts - v_pts;
2281 // Try to sync vo_flip() so it will *finish* at given time
2282 av_delay += mpctx->last_vo_flip_duration;
2283 av_delay -= audio_delay; // This much pts difference is desired
2285 double change = av_delay * 0.1;
2286 double max_change = default_max_pts_correction >= 0 ?
2287 default_max_pts_correction : frame_time * 0.1;
2288 if (change < -max_change)
2289 change = -max_change;
2290 else if (change > max_change)
2291 change = max_change;
2292 mpctx->delay += change;
2293 mpctx->total_avsync_change += change;
2296 #define ASYNC_PLAY_DONE -3
2297 static int audio_start_sync(struct MPContext *mpctx, int playsize)
2299 struct MPOpts *opts = &mpctx->opts;
2300 sh_audio_t * const sh_audio = mpctx->sh_audio;
2301 int res;
2303 // Timing info may not be set without
2304 res = decode_audio(sh_audio, 1);
2305 if (res < 0)
2306 return res;
2308 int bytes;
2309 bool did_retry = false;
2310 while (1) {
2311 double written_pts = written_audio_pts(mpctx);
2312 double ptsdiff = written_pts - mpctx->video_pts - mpctx->delay
2313 - audio_delay;
2314 bytes = ptsdiff * ao_data.bps / mpctx->opts.playback_speed;
2315 bytes -= bytes % (ao_data.channels * af_fmt2bits(ao_data.format) / 8);
2317 // ogg demuxers give packets without timing
2318 if (written_pts <= 1 && sh_audio->pts == MP_NOPTS_VALUE) {
2319 if (!did_retry) {
2320 // Try to read more data to see packets that have pts
2321 int res = decode_audio(sh_audio, ao_data.bps);
2322 if (res < 0)
2323 return res;
2324 did_retry = true;
2325 continue;
2327 bytes = 0;
2330 if (fabs(ptsdiff) > 300) // pts reset or just broken?
2331 bytes = 0;
2333 if (bytes > 0)
2334 break;
2336 mpctx->syncing_audio = false;
2337 int a = FFMIN(-bytes, FFMAX(playsize, 20000));
2338 int res = decode_audio(sh_audio, a);
2339 bytes += sh_audio->a_out_buffer_len;
2340 if (bytes >= 0) {
2341 memmove(sh_audio->a_out_buffer,
2342 sh_audio->a_out_buffer +
2343 sh_audio->a_out_buffer_len - bytes,
2344 bytes);
2345 sh_audio->a_out_buffer_len = bytes;
2346 if (res < 0)
2347 return res;
2348 return decode_audio(sh_audio, playsize);
2350 sh_audio->a_out_buffer_len = 0;
2351 if (res < 0)
2352 return res;
2354 int fillbyte = 0;
2355 if ((ao_data.format & AF_FORMAT_SIGN_MASK) == AF_FORMAT_US)
2356 fillbyte = 0x80;
2357 if (bytes >= playsize) {
2358 /* This case could fall back to the one below with
2359 * bytes = playsize, but then silence would keep accumulating
2360 * in a_out_buffer if the AO accepts less data than it asks for
2361 * in playsize. */
2362 char *p = malloc(playsize);
2363 memset(p, fillbyte, playsize);
2364 playsize = mpctx->audio_out->play(p, playsize, 0);
2365 free(p);
2366 mpctx->delay += opts->playback_speed*playsize/(double)ao_data.bps;
2367 return ASYNC_PLAY_DONE;
2369 mpctx->syncing_audio = false;
2370 decode_audio_prepend_bytes(sh_audio, bytes, fillbyte);
2371 return decode_audio(sh_audio, playsize);
2374 static int fill_audio_out_buffers(struct MPContext *mpctx)
2376 struct MPOpts *opts = &mpctx->opts;
2377 unsigned int t;
2378 double tt;
2379 int playsize;
2380 int playflags=0;
2381 int audio_eof=0;
2382 bool format_change = false;
2383 sh_audio_t * const sh_audio = mpctx->sh_audio;
2385 current_module="play_audio";
2387 while (1) {
2388 int sleep_time;
2389 // all the current uses of ao_data.pts seem to be in aos that handle
2390 // sync completely wrong; there should be no need to use ao_data.pts
2391 // in get_space()
2392 ao_data.pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2393 playsize = mpctx->audio_out->get_space();
2394 if (mpctx->sh_video || playsize >= ao_data.outburst)
2395 break;
2397 // handle audio-only case:
2398 // this is where mplayer sleeps during audio-only playback
2399 // to avoid 100% CPU use
2400 sleep_time = (ao_data.outburst - playsize) * 1000 / ao_data.bps;
2401 if (sleep_time < 10) sleep_time = 10; // limit to 100 wakeups per second
2402 usec_sleep(sleep_time * 1000);
2405 // Fill buffer if needed:
2406 current_module="decode_audio";
2407 t = GetTimer();
2409 if (!opts->initial_audio_sync || (ao_data.format & AF_FORMAT_SPECIAL_MASK))
2410 mpctx->syncing_audio = false;
2412 int res;
2413 if (mpctx->syncing_audio && mpctx->sh_video)
2414 res = audio_start_sync(mpctx, playsize);
2415 else
2416 res = decode_audio(sh_audio, playsize);
2417 if (res < 0) { // EOF, error or format change
2418 if (res == -2)
2419 format_change = true;
2420 else if (res == ASYNC_PLAY_DONE)
2421 return 1;
2422 else if (mpctx->d_audio->eof) {
2423 audio_eof = 1;
2424 int unitsize = ao_data.channels * af_fmt2bits(ao_data.format) / 8;
2425 if (sh_audio->a_out_buffer_len < unitsize)
2426 return 0;
2429 t = GetTimer() - t;
2430 tt = t*0.000001f; audio_time_usage+=tt;
2431 if (playsize > sh_audio->a_out_buffer_len) {
2432 playsize = sh_audio->a_out_buffer_len;
2433 if (audio_eof)
2434 playflags |= AOPLAY_FINAL_CHUNK;
2436 if (!playsize)
2437 return 1;
2439 // play audio:
2440 current_module="play_audio";
2442 // Is this pts value actually useful for the aos that access it?
2443 // They're obviously badly broken in the way they handle av sync;
2444 // would not having access to this make them more broken?
2445 ao_data.pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2446 playsize = mpctx->audio_out->play(sh_audio->a_out_buffer, playsize, playflags);
2448 if (playsize > 0) {
2449 sh_audio->a_out_buffer_len -= playsize;
2450 memmove(sh_audio->a_out_buffer, &sh_audio->a_out_buffer[playsize],
2451 sh_audio->a_out_buffer_len);
2452 mpctx->delay += opts->playback_speed*playsize/(double)ao_data.bps;
2453 } else if (audio_eof && mpctx->audio_out->get_delay() < .04) {
2454 // Sanity check to avoid hanging in case current ao doesn't output
2455 // partial chunks and doesn't check for AOPLAY_FINAL_CHUNK
2456 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Audio output truncated at end.\n");
2457 sh_audio->a_out_buffer_len = 0;
2460 /* The format change isn't handled too gracefully. A more precise
2461 * implementation would require draining buffered old-format audio
2462 * while displaying video, then doing the output format switch.
2464 if (format_change) {
2465 uninit_player(mpctx, INITIALIZED_AO);
2466 reinit_audio_chain(mpctx);
2469 return 1;
2472 static int sleep_until_near_frame(struct MPContext *mpctx, float *time_frame,
2473 float *aq_sleep_time)
2475 struct MPOpts *opts = &mpctx->opts;
2476 double audio_limit = 2;
2477 current_module="calc_sleep_time";
2479 if (mpctx->restart_playback)
2480 return 0;
2482 *time_frame -= get_relative_time(mpctx); // reset timer
2484 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
2485 float delay = mpctx->audio_out->get_delay();
2486 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "delay=%f\n", delay);
2488 if (opts->autosync) {
2490 * Adjust this raw delay value by calculating the expected
2491 * delay for this frame and generating a new value which is
2492 * weighted between the two. The higher autosync is, the
2493 * closer to the delay value gets to that which "-nosound"
2494 * would have used, and the longer it will take for A/V
2495 * sync to settle at the right value (but it eventually will.)
2496 * This settling time is very short for values below 100.
2498 float predicted = mpctx->delay / opts->playback_speed + *time_frame;
2499 float difference = delay - predicted;
2500 delay = predicted + difference / (float)opts->autosync;
2503 *time_frame = delay - mpctx->delay / opts->playback_speed;
2505 // delay = amount of audio buffered in soundcard/driver
2506 delay = FFMIN(delay, 0.5);
2507 delay = FFMAX(delay, 0.1);
2508 audio_limit = delay;
2509 } else {
2510 // If we're lagging more than 200 ms behind the right playback rate,
2511 // don't try to "catch up".
2512 // If benchmark is set always output frames as fast as possible
2513 // without sleeping.
2514 if (*time_frame < -0.2 || opts->benchmark)
2515 *time_frame = 0;
2518 double t = *time_frame - mpctx->video_out->flip_queue_offset;
2520 if (t <= 0.05)
2521 return 0;
2523 t -= 0.05;
2524 if (t > audio_limit * 0.6)
2525 t = audio_limit * 0.5;
2526 *aq_sleep_time += t;
2527 mp_input_get_cmd(mpctx->input, t * 1000 + 1, 1);
2528 return 1;
2531 int reinit_video_chain(struct MPContext *mpctx)
2533 struct MPOpts *opts = &mpctx->opts;
2534 sh_video_t * const sh_video = mpctx->sh_video;
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 return 0;
2804 mpctx->hrseek_active = false;
2805 sh_video->pts = pts;
2806 if (sh_video->last_pts == MP_NOPTS_VALUE)
2807 sh_video->last_pts = sh_video->pts;
2808 else if (sh_video->last_pts > sh_video->pts) {
2809 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Decreasing video pts: %f < %f\n",
2810 sh_video->pts, sh_video->last_pts);
2811 /* If the difference in pts is small treat it as jitter around the
2812 * right value (possibly caused by incorrect timestamp ordering) and
2813 * just show this frame immediately after the last one.
2814 * Treat bigger differences as timestamp resets and start counting
2815 * timing of later frames from the position of this one. */
2816 if (sh_video->last_pts - sh_video->pts > 0.5)
2817 sh_video->last_pts = sh_video->pts;
2818 else
2819 sh_video->pts = sh_video->last_pts;
2821 double frame_time = sh_video->pts - sh_video->last_pts;
2822 sh_video->last_pts = sh_video->pts;
2823 sh_video->timer += frame_time;
2824 if (mpctx->sh_audio)
2825 mpctx->delay -= frame_time;
2826 return frame_time;
2829 void pause_player(struct MPContext *mpctx)
2831 if (mpctx->paused)
2832 return;
2833 mpctx->paused = 1;
2834 mpctx->step_frames = 0;
2835 mpctx->time_frame -= get_relative_time(mpctx);
2837 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2838 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2840 if (mpctx->audio_out && mpctx->sh_audio)
2841 mpctx->audio_out->pause(); // pause audio, keep data if possible
2844 void unpause_player(struct MPContext *mpctx)
2846 if (!mpctx->paused)
2847 return;
2848 mpctx->paused = 0;
2850 if (mpctx->audio_out && mpctx->sh_audio)
2851 mpctx->audio_out->resume(); // resume audio
2852 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok
2853 && !mpctx->step_frames)
2854 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL); // resume video
2855 (void)get_relative_time(mpctx); // ignore time that passed during pause
2858 void add_step_frame(struct MPContext *mpctx)
2860 mpctx->step_frames++;
2861 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2862 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2863 unpause_player(mpctx);
2866 static void pause_loop(struct MPContext *mpctx)
2868 struct MPOpts *opts = &mpctx->opts;
2869 mp_cmd_t* cmd;
2870 #ifdef CONFIG_STREAM_CACHE
2871 int old_cache_fill = stream_cache_size > 0 ?
2872 cache_fill_status(mpctx->stream) : 0;
2873 #endif
2874 if (!opts->quiet) {
2875 if (opts->term_osd && !mpctx->sh_video) {
2876 set_osd_tmsg(OSD_MSG_PAUSE, 1, 0, " ===== PAUSE =====");
2877 update_osd_msg(mpctx);
2878 } else
2879 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "\n%s\r",
2880 mp_gtext(" ===== PAUSE ====="));
2881 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_PAUSED\n");
2884 while ( (cmd = mp_input_get_cmd(mpctx->input, 20, 1)) == NULL
2885 || cmd->id == MP_CMD_SET_MOUSE_POS || cmd->pausing == 4) {
2886 if (cmd) {
2887 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
2888 run_command(mpctx, cmd);
2889 mp_cmd_free(cmd);
2890 continue;
2892 if (mpctx->sh_video && mpctx->video_out)
2893 vo_check_events(mpctx->video_out);
2894 #ifdef CONFIG_MENU
2895 if (vf_menu)
2896 vf_menu_pause_update(vf_menu);
2897 #endif
2898 usec_sleep(20000);
2899 update_osd_msg(mpctx);
2900 int hack = vo_osd_changed(0);
2901 vo_osd_changed(hack);
2902 if (hack)
2903 break;
2904 #ifdef CONFIG_STREAM_CACHE
2905 if (!opts->quiet && stream_cache_size > 0) {
2906 int new_cache_fill = cache_fill_status(mpctx->stream);
2907 if (new_cache_fill != old_cache_fill) {
2908 if (opts->term_osd && !mpctx->sh_video) {
2909 set_osd_tmsg(OSD_MSG_PAUSE, 1, 0, "%s %d%%",
2910 mp_gtext(" ===== PAUSE ====="),
2911 new_cache_fill);
2912 update_osd_msg(mpctx);
2913 } else
2914 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "%s %d%%\r",
2915 mp_gtext(" ===== PAUSE ====="),
2916 new_cache_fill);
2917 old_cache_fill = new_cache_fill;
2920 #endif
2925 // Find the right mute status and record position for new file position
2926 static void edl_seek_reset(MPContext *mpctx)
2928 mpctx->edl_muted = 0;
2929 next_edl_record = edl_records;
2931 while (next_edl_record) {
2932 if (next_edl_record->start_sec >= get_current_time(mpctx))
2933 break;
2935 if (next_edl_record->action == EDL_MUTE)
2936 mpctx->edl_muted = !mpctx->edl_muted;
2937 next_edl_record = next_edl_record->next;
2939 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2940 mixer_mute(&mpctx->mixer);
2944 // Execute EDL command for the current position if one exists
2945 static void edl_update(MPContext *mpctx)
2947 if (!next_edl_record)
2948 return;
2950 if (!mpctx->sh_video) {
2951 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot use EDL without video, disabling.\n");
2952 free_edl(edl_records);
2953 next_edl_record = NULL;
2954 edl_records = NULL;
2955 return;
2958 if (get_current_time(mpctx) >= next_edl_record->start_sec) {
2959 if (next_edl_record->action == EDL_SKIP) {
2960 mpctx->osd_function = OSD_FFW;
2961 queue_seek(mpctx, MPSEEK_RELATIVE, next_edl_record->length_sec, 0);
2962 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_SKIP: start [%f], stop "
2963 "[%f], length [%f]\n", next_edl_record->start_sec,
2964 next_edl_record->stop_sec, next_edl_record->length_sec);
2966 else if (next_edl_record->action == EDL_MUTE) {
2967 mpctx->edl_muted = !mpctx->edl_muted;
2968 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2969 mixer_mute(&mpctx->mixer);
2970 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_MUTE: [%f]\n",
2971 next_edl_record->start_sec );
2973 next_edl_record = next_edl_record->next;
2977 static void reinit_decoders(struct MPContext *mpctx)
2979 reinit_video_chain(mpctx);
2980 reinit_audio_chain(mpctx);
2981 mp_property_do("sub", M_PROPERTY_SET, &(int){mpctx->global_sub_pos}, mpctx);
2984 static void seek_reset(struct MPContext *mpctx)
2986 if (mpctx->sh_video) {
2987 current_module = "seek_video_reset";
2988 resync_video_stream(mpctx->sh_video);
2989 mpctx->sh_video->timer = 0;
2990 vo_seek_reset(mpctx->video_out);
2991 mpctx->sh_video->timer = 0;
2992 mpctx->sh_video->num_buffered_pts = 0;
2993 mpctx->sh_video->last_pts = MP_NOPTS_VALUE;
2994 mpctx->delay = 0;
2995 mpctx->time_frame = 0;
2996 mpctx->restart_playback = true;
2997 // Not all demuxers set d_video->pts during seek, so this value
2998 // (which is used by at least vobsub and edl code below) may
2999 // be completely wrong (probably 0).
3000 mpctx->sh_video->pts = mpctx->d_video->pts + mpctx->video_offset;
3001 mpctx->video_pts = mpctx->sh_video->pts;
3002 update_subtitles(mpctx, mpctx->sh_video->pts, mpctx->video_offset,
3003 true);
3004 update_teletext(mpctx->sh_video, mpctx->demuxer, 1);
3007 if (mpctx->sh_audio) {
3008 current_module = "seek_audio_reset";
3009 resync_audio_stream(mpctx->sh_audio);
3010 mpctx->audio_out->reset(); // stop audio, throwing away buffered data
3011 mpctx->sh_audio->a_buffer_len = 0;
3012 mpctx->sh_audio->a_out_buffer_len = 0;
3013 if (!mpctx->sh_video)
3014 update_subtitles(mpctx, mpctx->sh_audio->pts,
3015 mpctx->video_offset, true);
3018 if (vo_vobsub && mpctx->sh_video) {
3019 current_module = "seek_vobsub_reset";
3020 vobsub_seek(vo_vobsub, mpctx->sh_video->pts);
3023 edl_seek_reset(mpctx);
3025 mpctx->hrseek_active = false;
3026 mpctx->hrseek_framedrop = false;
3027 mpctx->total_avsync_change = 0;
3028 audio_time_usage = 0; video_time_usage = 0; vout_time_usage = 0;
3029 drop_frame_cnt = 0;
3031 current_module = NULL;
3034 static bool timeline_set_part(struct MPContext *mpctx, int i)
3036 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
3037 struct timeline_part *n = mpctx->timeline + i;
3038 mpctx->timeline_part = i;
3039 mpctx->video_offset = n->start - n->source_start;
3040 if (n->source == p->source)
3041 return false;
3042 uninit_player(mpctx, INITIALIZED_VCODEC | (mpctx->opts.fixed_vo && mpctx->opts.video_id != -2 ? 0 : INITIALIZED_VO) | INITIALIZED_AO | INITIALIZED_ACODEC | INITIALIZED_SUB);
3043 mpctx->demuxer = n->source->demuxer;
3044 mpctx->d_video = mpctx->demuxer->video;
3045 mpctx->d_audio = mpctx->demuxer->audio;
3046 mpctx->d_sub = mpctx->demuxer->sub;
3047 mpctx->sh_video = mpctx->d_video->sh;
3048 mpctx->sh_audio = mpctx->d_audio->sh;
3049 return true;
3052 // Given pts, switch playback to the corresponding part.
3053 // Return offset within that part.
3054 static double timeline_set_from_time(struct MPContext *mpctx, double pts,
3055 bool *need_reset)
3057 if (pts < 0)
3058 pts = 0;
3059 for (int i = 0; i < mpctx->num_timeline_parts; i++) {
3060 struct timeline_part *p = mpctx->timeline + i;
3061 if (pts < (p+1)->start) {
3062 *need_reset = timeline_set_part(mpctx, i);
3063 return pts - p->start + p->source_start;
3066 return -1;
3070 // return -1 if seek failed (non-seekable stream?), 0 otherwise
3071 static int seek(MPContext *mpctx, struct seek_params seek)
3073 struct MPOpts *opts = &mpctx->opts;
3075 current_module = "seek";
3076 if (mpctx->stop_play == AT_END_OF_FILE)
3077 mpctx->stop_play = KEEP_PLAYING;
3078 bool hr_seek = mpctx->demuxer->accurate_seek && opts->correct_pts;
3079 hr_seek &= seek.exact >= 0 && seek.type != MPSEEK_FACTOR;
3080 hr_seek &= opts->hr_seek == 0 && seek.type == MPSEEK_ABSOLUTE
3081 || opts->hr_seek > 0 || seek.exact > 0;
3082 if (seek.type == MPSEEK_FACTOR
3083 || seek.type == MPSEEK_ABSOLUTE
3084 && seek.amount < mpctx->last_chapter_pts
3085 || seek.amount < 0)
3086 mpctx->last_chapter_seek = -1;
3087 if (mpctx->timeline && seek.type == MPSEEK_FACTOR) {
3088 seek.amount *= mpctx->timeline[mpctx->num_timeline_parts].start;
3089 seek.type = MPSEEK_ABSOLUTE;
3091 if ((mpctx->demuxer->accurate_seek || mpctx->timeline)
3092 && seek.type == MPSEEK_RELATIVE) {
3093 seek.type = MPSEEK_ABSOLUTE;
3094 seek.direction = seek.amount > 0 ? 1 : -1;
3095 seek.amount += get_current_time(mpctx);
3098 /* At least the liba52 decoder wants to read from the input stream
3099 * during initialization, so reinit must be done after the demux_seek()
3100 * call that clears possible stream EOF. */
3101 bool need_reset = false;
3102 double demuxer_amount = seek.amount;
3103 if (mpctx->timeline) {
3104 demuxer_amount = timeline_set_from_time(mpctx, seek.amount,
3105 &need_reset);
3106 if (demuxer_amount == -1) {
3107 mpctx->stop_play = AT_END_OF_FILE;
3108 // Clear audio from current position
3109 if (mpctx->sh_audio) {
3110 mpctx->audio_out->reset();
3111 mpctx->sh_audio->a_buffer_len = 0;
3112 mpctx->sh_audio->a_out_buffer_len = 0;
3114 return -1;
3117 int demuxer_style = 0;
3118 switch (seek.type) {
3119 case MPSEEK_FACTOR:
3120 demuxer_style |= SEEK_FACTOR; // fallthrough
3121 case MPSEEK_ABSOLUTE:
3122 demuxer_style |= SEEK_ABSOLUTE;
3124 if (hr_seek || seek.direction < 0)
3125 demuxer_style |= SEEK_BACKWARD;
3126 else if (seek.direction > 0)
3127 demuxer_style |= SEEK_FORWARD;
3129 int seekresult = demux_seek(mpctx->demuxer, demuxer_amount, audio_delay,
3130 demuxer_style);
3131 if (need_reset)
3132 reinit_decoders(mpctx);
3133 if (seekresult == 0)
3134 return -1;
3136 seek_reset(mpctx);
3138 /* Use the target time as "current position" for further relative
3139 * seeks etc until a new video frame has been decoded */
3140 if (seek.type == MPSEEK_ABSOLUTE)
3141 mpctx->video_pts = seek.amount;
3143 if (hr_seek) {
3144 mpctx->hrseek_active = true;
3145 mpctx->hrseek_framedrop = true;
3146 mpctx->hrseek_pts = seek.amount;
3149 mpctx->start_timestamp = GetTimerMS();
3151 return 0;
3154 void queue_seek(struct MPContext *mpctx, enum seek_type type, double amount,
3155 int exact)
3157 struct seek_params *seek = &mpctx->seek;
3158 switch (type) {
3159 case MPSEEK_RELATIVE:
3160 if (seek->type == MPSEEK_FACTOR)
3161 return; // Well... not common enough to bother doing better
3162 seek->amount += amount;
3163 seek->exact = FFMAX(seek->exact, exact);
3164 if (seek->type == MPSEEK_NONE)
3165 seek->exact = exact;
3166 if (seek->type == MPSEEK_ABSOLUTE)
3167 return;
3168 if (seek->amount == 0) {
3169 *seek = (struct seek_params){0};
3170 return;
3172 seek->type = MPSEEK_RELATIVE;
3173 return;
3174 case MPSEEK_ABSOLUTE:
3175 case MPSEEK_FACTOR:
3176 *seek = (struct seek_params) {
3177 .type = type,
3178 .amount = amount,
3179 .exact = exact,
3181 return;
3182 case MPSEEK_NONE:
3183 *seek = (struct seek_params){0};
3184 return;
3186 abort();
3190 double get_time_length(struct MPContext *mpctx)
3192 if (mpctx->timeline)
3193 return mpctx->timeline[mpctx->num_timeline_parts].start;
3195 struct demuxer *demuxer = mpctx->demuxer;
3196 double get_time_ans;
3197 // <= 0 means DEMUXER_CTRL_NOTIMPL or DEMUXER_CTRL_DONTKNOW
3198 if (demux_control(demuxer, DEMUXER_CTRL_GET_TIME_LENGTH,
3199 (void *) &get_time_ans) > 0)
3200 return get_time_ans;
3202 struct sh_video *sh_video = mpctx->d_video->sh;
3203 struct sh_audio *sh_audio = mpctx->d_audio->sh;
3204 if (sh_video && sh_video->i_bps && sh_audio && sh_audio->i_bps)
3205 return (double) (demuxer->movi_end - demuxer->movi_start) /
3206 (sh_video->i_bps + sh_audio->i_bps);
3207 if (sh_video && sh_video->i_bps)
3208 return (double) (demuxer->movi_end - demuxer->movi_start) /
3209 sh_video->i_bps;
3210 if (sh_audio && sh_audio->i_bps)
3211 return (double) (demuxer->movi_end - demuxer->movi_start) /
3212 sh_audio->i_bps;
3213 return 0;
3216 /* If there are timestamps from stream level then use those (for example
3217 * DVDs can have consistent times there while the MPEG-level timestamps
3218 * reset). */
3219 double get_current_time(struct MPContext *mpctx)
3221 struct demuxer *demuxer = mpctx->demuxer;
3222 if (demuxer->stream_pts != MP_NOPTS_VALUE)
3223 return demuxer->stream_pts;
3224 struct sh_video *sh_video = demuxer->video->sh;
3225 if (sh_video)
3226 return mpctx->video_pts;
3227 return playing_audio_pts(mpctx);
3230 int get_percent_pos(struct MPContext *mpctx)
3232 struct demuxer *demuxer = mpctx->demuxer;
3233 int ans = 0;
3234 if (mpctx->timeline)
3235 ans = get_current_time(mpctx) * 100 /
3236 mpctx->timeline[mpctx->num_timeline_parts].start;
3237 else if (demux_control(demuxer, DEMUXER_CTRL_GET_PERCENT_POS, &ans) > 0)
3239 else {
3240 int len = (demuxer->movi_end - demuxer->movi_start) / 100;
3241 off_t pos = demuxer->filepos > 0 ?
3242 demuxer->filepos : stream_tell(demuxer->stream);
3243 if (len > 0)
3244 ans = (pos - demuxer->movi_start) / len;
3245 else
3246 ans = 0;
3248 if (ans < 0)
3249 ans = 0;
3250 if (ans > 100)
3251 ans = 100;
3252 return ans;
3255 // -2 is no chapters, -1 is before first chapter
3256 int get_current_chapter(struct MPContext *mpctx)
3258 double current_pts = get_current_time(mpctx);
3259 if (!mpctx->chapters)
3260 return FFMAX(mpctx->last_chapter_seek,
3261 demuxer_get_current_chapter(mpctx->demuxer, current_pts));
3263 int i;
3264 for (i = 1; i < mpctx->num_chapters; i++)
3265 if (current_pts < mpctx->chapters[i].start)
3266 break;
3267 return FFMAX(mpctx->last_chapter_seek, i - 1);
3270 // currently returns a string allocated with malloc, not talloc
3271 char *chapter_display_name(struct MPContext *mpctx, int chapter)
3273 if (!mpctx->chapters || !mpctx->sh_video)
3274 return demuxer_chapter_display_name(mpctx->demuxer, chapter);
3275 return strdup(mpctx->chapters[chapter].name);
3278 int seek_chapter(struct MPContext *mpctx, int chapter, double *seek_pts,
3279 char **chapter_name)
3281 mpctx->last_chapter_seek = -1;
3282 if (!mpctx->chapters || !mpctx->sh_video) {
3283 int res = demuxer_seek_chapter(mpctx->demuxer, chapter, seek_pts,
3284 chapter_name);
3285 if (res >= 0) {
3286 if (*seek_pts == -1)
3287 seek_reset(mpctx);
3288 else {
3289 mpctx->last_chapter_seek = res;
3290 mpctx->last_chapter_pts = *seek_pts;
3293 return res;
3296 if (chapter >= mpctx->num_chapters)
3297 return -1;
3298 if (chapter < 0)
3299 chapter = 0;
3300 *seek_pts = mpctx->chapters[chapter].start;
3301 mpctx->last_chapter_seek = chapter;
3302 mpctx->last_chapter_pts = *seek_pts;
3303 if (chapter_name)
3304 *chapter_name = talloc_strdup(NULL, mpctx->chapters[chapter].name);
3305 return chapter;
3309 static void run_playloop(struct MPContext *mpctx)
3311 struct MPOpts *opts = &mpctx->opts;
3312 float aq_sleep_time = 0;
3314 if (opts->chapterrange[1] > 0) {
3315 int cur_chapter = get_current_chapter(mpctx);
3316 if (cur_chapter!=-1 && cur_chapter + 1 > opts->chapterrange[1])
3317 mpctx->stop_play = PT_NEXT_ENTRY;
3320 if (!mpctx->sh_audio && mpctx->d_audio->sh) {
3321 mpctx->sh_audio = mpctx->d_audio->sh;
3322 mpctx->sh_audio->ds = mpctx->d_audio;
3323 reinit_audio_chain(mpctx);
3326 /*========================== PLAY AUDIO ============================*/
3328 if (mpctx->sh_audio && !mpctx->paused
3329 && (!mpctx->restart_playback || !mpctx->sh_video))
3330 if (!fill_audio_out_buffers(mpctx))
3331 // at eof, all audio at least written to ao
3332 if (!mpctx->sh_video)
3333 mpctx->stop_play = AT_END_OF_FILE;
3336 if (!mpctx->sh_video) {
3337 mpctx->restart_playback = false;
3338 if (mpctx->step_frames) {
3339 mpctx->step_frames = 0;
3340 pause_player(mpctx);
3342 // handle audio-only case:
3343 double a_pos = 0;
3344 // sh_audio can be NULL due to video stream switching
3345 // TODO: handle this better
3346 if (mpctx->sh_audio)
3347 a_pos = playing_audio_pts(mpctx);
3349 print_status(mpctx, a_pos, false);
3351 if (end_at.type == END_AT_TIME && end_at.pos < a_pos)
3352 mpctx->stop_play = PT_NEXT_ENTRY;
3353 update_subtitles(mpctx, a_pos, mpctx->video_offset, false);
3354 update_osd_msg(mpctx);
3355 } else {
3357 /*========================== PLAY VIDEO ============================*/
3359 vo_pts = mpctx->sh_video->timer * 90000.0;
3360 vo_fps = mpctx->sh_video->fps;
3362 bool blit_frame = mpctx->video_out->frame_loaded;
3363 if (!blit_frame || mpctx->hrseek_active) {
3364 double frame_time = update_video(mpctx);
3365 blit_frame = mpctx->video_out->frame_loaded;
3366 blit_frame &= !mpctx->hrseek_active;
3367 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "*** ftime=%5.3f ***\n", frame_time);
3368 if (mpctx->sh_video->vf_initialized < 0) {
3369 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
3370 "\nFATAL: Could not initialize video filters (-vf) "
3371 "or video output (-vo).\n");
3372 mpctx->stop_play = PT_NEXT_ENTRY;
3373 return;
3375 if (frame_time < 0)
3376 mpctx->stop_play = AT_END_OF_FILE;
3377 else if (!mpctx->restart_playback) {
3378 mpctx->time_frame += frame_time / opts->playback_speed;
3379 adjust_sync(mpctx, frame_time);
3382 if (mpctx->timeline) {
3383 struct timeline_part *next =
3384 mpctx->timeline + mpctx->timeline_part + 1;
3385 if (mpctx->sh_video->pts >= next->start
3386 || mpctx->stop_play == AT_END_OF_FILE
3387 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts) {
3388 seek(mpctx, (struct seek_params){ .type = MPSEEK_ABSOLUTE,
3389 .amount = next->start });
3390 return;
3394 // ==========================================================================
3396 current_module = "vo_check_events";
3397 vo_check_events(mpctx->video_out);
3399 #ifdef CONFIG_X11
3400 if (stop_xscreensaver) {
3401 current_module = "stop_xscreensaver";
3402 xscreensaver_heartbeat(mpctx->x11_state);
3404 #endif
3405 if (heartbeat_cmd) {
3406 static unsigned last_heartbeat;
3407 unsigned now = GetTimerMS();
3408 if (now - last_heartbeat > 30000) {
3409 last_heartbeat = now;
3410 system(heartbeat_cmd);
3414 bool frame_time_remaining = sleep_until_near_frame(mpctx,
3415 &mpctx->time_frame,
3416 &aq_sleep_time);
3418 //====================== FLIP PAGE (VIDEO BLT): =========================
3420 current_module = "flip_page";
3421 if (!frame_time_remaining && blit_frame) {
3422 struct sh_video *sh_video = mpctx->sh_video;
3423 mpctx->video_pts = sh_video->pts;
3424 update_subtitles(mpctx, sh_video->pts, mpctx->video_offset, false);
3425 update_teletext(sh_video, mpctx->demuxer, 0);
3426 update_osd_msg(mpctx);
3427 struct vf_instance *vf = sh_video->vfilter;
3428 vf->control(vf, VFCTRL_DRAW_EOSD, mpctx->osd);
3429 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
3430 vo_osd_changed(0);
3432 mpctx->time_frame -= mpctx->video_out->flip_queue_offset;
3433 aq_sleep_time += mpctx->time_frame;
3434 // flag 256 means: libvo driver does its timing (dvb card)
3435 if (mpctx->time_frame > 0.001
3436 && !(mpctx->sh_video->output_flags & VFCAP_TIMER))
3437 mpctx->time_frame = timing_sleep(mpctx, mpctx->time_frame);
3438 mpctx->time_frame += mpctx->video_out->flip_queue_offset;
3440 unsigned int t2 = GetTimer();
3441 /* Playing with playback speed it's possible to get pathological
3442 * cases with mpctx->time_frame negative enough to cause an
3443 * overflow in pts_us calculation, thus the FFMAX. */
3444 double time_frame = FFMAX(mpctx->time_frame, -1);
3445 unsigned int pts_us = mpctx->last_time + time_frame * 1e6;
3446 int duration = -1;
3447 double pts2 = mpctx->video_out->next_pts2;
3448 if (pts2 != MP_NOPTS_VALUE && opts->correct_pts
3449 && !mpctx->restart_playback) {
3450 // expected A/V sync correction is ignored
3451 double diff = (pts2 - mpctx->video_pts);
3452 diff /= opts->playback_speed;
3453 if (mpctx->time_frame < 0)
3454 diff += mpctx->time_frame;
3455 if (diff < 0)
3456 diff = 0;
3457 if (diff > 10)
3458 diff = 10;
3459 duration = diff * 1e6;
3461 vo_flip_page(mpctx->video_out, pts_us | 1, duration);
3463 mpctx->last_vo_flip_duration = (GetTimer() - t2) * 0.000001;
3464 vout_time_usage += mpctx->last_vo_flip_duration;
3465 if (mpctx->video_out->driver->flip_page_timed) {
3466 // No need to adjust sync based on flip speed
3467 mpctx->last_vo_flip_duration = 0;
3468 // For print_status - VO call finishing early is OK for sync
3469 mpctx->time_frame -= get_relative_time(mpctx);
3471 if (mpctx->restart_playback) {
3472 mpctx->syncing_audio = true;
3473 if (mpctx->sh_audio && !mpctx->paused)
3474 fill_audio_out_buffers(mpctx);
3475 mpctx->restart_playback = false;
3476 mpctx->time_frame = 0;
3477 get_relative_time(mpctx);
3479 print_status(mpctx, MP_NOPTS_VALUE, true);
3480 } else
3481 print_status(mpctx, MP_NOPTS_VALUE, false);
3483 //============================ Auto QUALITY ============================
3485 /*Output quality adjustments:*/
3486 if (opts->auto_quality > 0) {
3487 current_module = "autoq";
3488 if (output_quality < opts->auto_quality && aq_sleep_time > 0)
3489 ++output_quality;
3490 else
3491 if (output_quality>1 && aq_sleep_time<0)
3492 --output_quality;
3493 else if (output_quality>0 && aq_sleep_time<-0.050f) // 50ms
3494 output_quality = 0;
3495 set_video_quality(mpctx->sh_video, output_quality);
3498 if (!frame_time_remaining && blit_frame) {
3499 if (play_n_frames >= 0) {
3500 --play_n_frames;
3501 if (play_n_frames <= 0)
3502 mpctx->stop_play = PT_NEXT_ENTRY;
3504 if (mpctx->step_frames > 0) {
3505 mpctx->step_frames--;
3506 if (mpctx->step_frames == 0)
3507 pause_player(mpctx);
3511 // FIXME: add size based support for -endpos
3512 if (end_at.type == END_AT_TIME &&
3513 !frame_time_remaining && end_at.pos <= mpctx->sh_video->pts)
3514 mpctx->stop_play = PT_NEXT_ENTRY;
3516 } // end if(mpctx->sh_video)
3518 #ifdef CONFIG_DVDNAV
3519 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
3520 nav_highlight_t hl;
3521 mp_dvdnav_get_highlight(mpctx->stream, &hl);
3522 if (!vo_spudec || !spudec_apply_palette_crop(vo_spudec, hl.palette, hl.sx, hl.sy, hl.ex, hl.ey)) {
3523 osd_set_nav_box(hl.sx, hl.sy, hl.ex, hl.ey);
3524 vo_osd_changed(OSDTYPE_DVDNAV);
3525 } else {
3526 osd_set_nav_box(0, 0, 0, 0);
3527 vo_osd_changed(OSDTYPE_DVDNAV);
3528 vo_osd_changed(OSDTYPE_SPU);
3531 if (mp_dvdnav_stream_has_changed(mpctx->stream)) {
3532 double ar = -1.0;
3533 if (mpctx->sh_video &&
3534 stream_control(mpctx->demuxer->stream,
3535 STREAM_CTRL_GET_ASPECT_RATIO, &ar)
3536 != STREAM_UNSUPPORTED)
3537 mpctx->sh_video->stream_aspect = ar;
3540 #endif
3542 //================= Keyboard events, SEEKing ====================
3544 current_module = "key_events";
3546 while (1) {
3547 mp_cmd_t *cmd;
3548 while ((cmd = mp_input_get_cmd(mpctx->input, 0, 1)) != NULL) {
3549 /* Allow running consecutive seek commands to combine them,
3550 * but execute the seek before running other commands.
3551 * If the user seeks continuously (keeps arrow key down)
3552 * try to finish showing a frame from one location before doing
3553 * another seek (which could lead to unchanging display). */
3554 if (mpctx->seek.type && cmd->id != MP_CMD_SEEK
3555 || mpctx->restart_playback && cmd->id == MP_CMD_SEEK
3556 && GetTimerMS() - mpctx->start_timestamp < 300)
3557 break;
3558 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
3559 run_command(mpctx, cmd);
3560 mp_cmd_free(cmd);
3561 if (mpctx->stop_play)
3562 break;
3564 if (!mpctx->paused || mpctx->stop_play || mpctx->seek.type
3565 || mpctx->restart_playback)
3566 break;
3567 if (mpctx->sh_video) {
3568 update_osd_msg(mpctx);
3569 int hack = vo_osd_changed(0);
3570 vo_osd_changed(hack);
3571 if (hack) {
3572 if (redraw_osd(mpctx->sh_video, mpctx->osd) < 0) {
3573 add_step_frame(mpctx);
3574 break;
3575 } else
3576 vo_osd_changed(0);
3579 pause_loop(mpctx);
3582 // handle -sstep
3583 if (step_sec > 0 && !mpctx->paused) {
3584 mpctx->osd_function = OSD_FFW;
3585 queue_seek(mpctx, MPSEEK_RELATIVE, step_sec, 0);
3588 edl_update(mpctx);
3590 /* Looping. */
3591 if (mpctx->stop_play==AT_END_OF_FILE && opts->loop_times>=0) {
3592 mp_msg(MSGT_CPLAYER, MSGL_V, "loop_times = %d\n", opts->loop_times);
3594 if (opts->loop_times>1)
3595 opts->loop_times--;
3596 else if (opts->loop_times==1)
3597 opts->loop_times = -1;
3598 play_n_frames = play_n_frames_mf;
3599 mpctx->stop_play = 0;
3600 queue_seek(mpctx, MPSEEK_ABSOLUTE, 0, 0);
3603 if (mpctx->seek.type) {
3604 seek(mpctx, mpctx->seek);
3605 mpctx->seek = (struct seek_params){0};
3610 static int read_keys(void *ctx, int fd)
3612 getch2(ctx);
3613 return mplayer_get_key(ctx, 0);
3616 static bool attachment_is_font(struct demux_attachment *att)
3618 if (!att->name || !att->type || !att->data || !att->data_size)
3619 return false;
3620 // match against MIME types
3621 if (strcmp(att->type, "application/x-truetype-font") == 0
3622 || strcmp(att->type, "application/x-font") == 0)
3623 return true;
3624 // fallback: match against file extension
3625 if (strlen(att->name) > 4) {
3626 char *ext = att->name + strlen(att->name) - 4;
3627 if (strcasecmp(ext, ".ttf") == 0 || strcasecmp(ext, ".ttc") == 0
3628 || strcasecmp(ext, ".otf") == 0)
3629 return true;
3631 return false;
3634 static int select_audio(demuxer_t *demuxer, int audio_id, char *audio_lang)
3636 if (audio_id == -1)
3637 audio_id = demuxer_audio_track_by_lang_and_default(demuxer, audio_lang);
3638 if (audio_id != -1) // -1 (automatic) is the default behaviour of demuxers
3639 demuxer_switch_audio(demuxer, audio_id);
3640 if (audio_id == -2) { // some demuxers don't yet know how to switch to no sound
3641 demuxer->audio->id = -2;
3642 demuxer->audio->sh = NULL;
3644 return demuxer->audio->id;
3647 static void print_version(const char* name)
3649 mp_msg(MSGT_CPLAYER, MSGL_INFO, MP_TITLE, name);
3651 /* Test for CPU capabilities (and corresponding OS support) for optimizing */
3652 GetCpuCaps(&gCpuCaps);
3653 #if ARCH_X86
3654 mp_msg(MSGT_CPLAYER, MSGL_V,
3655 "CPUflags: MMX: %d MMX2: %d 3DNow: %d 3DNowExt: %d SSE: %d SSE2: %d SSSE3: %d\n",
3656 gCpuCaps.hasMMX, gCpuCaps.hasMMX2,
3657 gCpuCaps.has3DNow, gCpuCaps.has3DNowExt,
3658 gCpuCaps.hasSSE, gCpuCaps.hasSSE2, gCpuCaps.hasSSSE3);
3659 #if CONFIG_RUNTIME_CPUDETECT
3660 mp_tmsg(MSGT_CPLAYER,MSGL_V, "Compiled with runtime CPU detection.\n");
3661 #else
3662 mp_tmsg(MSGT_CPLAYER,MSGL_V, "Compiled for x86 CPU with extensions:");
3663 if (HAVE_MMX)
3664 mp_msg(MSGT_CPLAYER,MSGL_V," MMX");
3665 if (HAVE_MMX2)
3666 mp_msg(MSGT_CPLAYER,MSGL_V," MMX2");
3667 if (HAVE_AMD3DNOW)
3668 mp_msg(MSGT_CPLAYER,MSGL_V," 3DNow");
3669 if (HAVE_AMD3DNOWEXT)
3670 mp_msg(MSGT_CPLAYER,MSGL_V," 3DNowExt");
3671 if (HAVE_SSE)
3672 mp_msg(MSGT_CPLAYER,MSGL_V," SSE");
3673 if (HAVE_SSE2)
3674 mp_msg(MSGT_CPLAYER,MSGL_V," SSE2");
3675 if (HAVE_SSSE3)
3676 mp_msg(MSGT_CPLAYER,MSGL_V," SSSE3");
3677 if (HAVE_CMOV)
3678 mp_msg(MSGT_CPLAYER,MSGL_V," CMOV");
3679 mp_msg(MSGT_CPLAYER,MSGL_V,"\n");
3680 #endif /* CONFIG_RUNTIME_CPUDETECT */
3681 #endif /* ARCH_X86 */
3684 /* This preprocessor directive is a hack to generate a mplayer-nomain.o object
3685 * file for some tools to link against. */
3686 #ifndef DISABLE_MAIN
3687 int main(int argc,char* argv[]){
3688 if (argc > 1 && !strcmp(argv[1], "-leak-report"))
3689 talloc_enable_leak_report();
3691 char * mem_ptr;
3693 // movie info:
3695 /* Flag indicating whether MPlayer should exit without playing anything. */
3696 int opt_exit = 0;
3697 int i;
3699 struct MPContext *mpctx = &(struct MPContext){
3700 .osd_function = OSD_PLAY,
3701 .begin_skip = MP_NOPTS_VALUE,
3702 .play_tree_step = 1,
3703 .global_sub_pos = -1,
3704 .set_of_sub_pos = -1,
3705 .file_format = DEMUXER_TYPE_UNKNOWN,
3706 .last_dvb_step = 1,
3709 InitTimer();
3710 srand(GetTimerMS());
3712 mp_msg_init();
3713 set_av_log_callback();
3715 #ifdef CONFIG_X11
3716 mpctx->x11_state = vo_x11_init_state();
3717 #endif
3718 struct MPOpts *opts = &mpctx->opts;
3719 set_default_mplayer_options(opts);
3720 // Create the config context and register the options
3721 mpctx->mconfig = m_config_new(opts, cfg_include);
3722 m_config_register_options(mpctx->mconfig,mplayer_opts);
3723 m_config_register_options(mpctx->mconfig, common_opts);
3724 mp_input_register_options(mpctx->mconfig);
3726 // Preparse the command line
3727 m_config_preparse_command_line(mpctx->mconfig,argc,argv);
3729 #if (defined(__MINGW32__) || defined(__CYGWIN__)) && defined(CONFIG_WIN32DLL)
3730 set_path_env();
3731 #endif
3733 #ifdef CONFIG_TV
3734 stream_tv_defaults.immediate = 1;
3735 #endif
3737 parse_cfgfiles(mpctx, mpctx->mconfig);
3739 mpctx->playtree = m_config_parse_mp_command_line(mpctx->mconfig, argc, argv);
3740 if(mpctx->playtree == NULL)
3741 opt_exit = 1;
3742 else {
3743 mpctx->playtree = play_tree_cleanup(mpctx->playtree);
3744 if(mpctx->playtree) {
3745 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,mpctx->mconfig);
3746 if(mpctx->playtree_iter) {
3747 if(play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
3748 play_tree_iter_free(mpctx->playtree_iter);
3749 mpctx->playtree_iter = NULL;
3751 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,1);
3755 mpctx->key_fifo = mp_fifo_create(opts);
3757 print_version("MPlayer2");
3759 #if defined(__MINGW32__) || defined(__CYGWIN__)
3761 HMODULE kernel32 = GetModuleHandle("Kernel32.dll");
3762 BOOL WINAPI (*setDEP)(DWORD) = NULL;
3763 BOOL WINAPI (*setDllDir)(LPCTSTR) = NULL;
3764 if (kernel32) {
3765 setDEP = GetProcAddress(kernel32, "SetProcessDEPPolicy");
3766 setDllDir = GetProcAddress(kernel32, "SetDllDirectoryA");
3768 if (setDEP) setDEP(3);
3769 if (setDllDir) setDllDir("");
3771 // stop Windows from showing all kinds of annoying error dialogs
3772 SetErrorMode(0x8003);
3773 // request 1ms timer resolution
3774 timeBeginPeriod(1);
3775 #endif
3777 #ifdef CONFIG_PRIORITY
3778 set_priority();
3779 #endif
3781 if (codec_path)
3782 set_codec_path(codec_path);
3784 if(opts->video_driver_list && strcmp(opts->video_driver_list[0],"help")==0){
3785 list_video_out();
3786 opt_exit = 1;
3789 if(opts->audio_driver_list && strcmp(opts->audio_driver_list[0],"help")==0){
3790 list_audio_out();
3791 opt_exit = 1;
3794 /* Check codecs.conf. */
3795 if(!codecs_file || !parse_codec_cfg(codecs_file)){
3796 if(!parse_codec_cfg(mem_ptr=get_path("codecs.conf"))){
3797 if(!parse_codec_cfg(MPLAYER_CONFDIR "/codecs.conf")){
3798 if(!parse_codec_cfg(NULL)){
3799 exit_player_with_rc(mpctx, EXIT_NONE, 0);
3801 mp_tmsg(MSGT_CPLAYER,MSGL_V,"Using built-in default codecs.conf.\n");
3804 free( mem_ptr ); // release the buffer created by get_path()
3807 if(audio_codec_list && strcmp(audio_codec_list[0],"help")==0){
3808 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available audio codecs:\n");
3809 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AUDIO_CODECS\n");
3810 list_codecs(1);
3811 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3812 opt_exit = 1;
3814 if(video_codec_list && strcmp(video_codec_list[0],"help")==0){
3815 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available video codecs:\n");
3816 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODECS\n");
3817 list_codecs(0);
3818 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3819 opt_exit = 1;
3821 if(video_fm_list && strcmp(video_fm_list[0],"help")==0){
3822 vfm_help();
3823 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3824 opt_exit = 1;
3826 if(audio_fm_list && strcmp(audio_fm_list[0],"help")==0){
3827 afm_help();
3828 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3829 opt_exit = 1;
3831 if(af_cfg.list && strcmp(af_cfg.list[0],"help")==0){
3832 af_help();
3833 printf("\n");
3834 opt_exit = 1;
3836 #ifdef CONFIG_X11
3837 if(vo_fstype_list && strcmp(vo_fstype_list[0],"help")==0){
3838 fstype_help();
3839 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
3840 opt_exit = 1;
3842 #endif
3843 if((opts->demuxer_name && strcmp(opts->demuxer_name,"help")==0) ||
3844 (opts->audio_demuxer_name && strcmp(opts->audio_demuxer_name,"help")==0) ||
3845 (opts->sub_demuxer_name && strcmp(opts->sub_demuxer_name,"help")==0)){
3846 demuxer_help();
3847 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
3848 opt_exit = 1;
3850 if (opts->list_properties) {
3851 property_print_help();
3852 opt_exit = 1;
3855 if(opt_exit)
3856 exit_player(mpctx, EXIT_NONE);
3858 if (!mpctx->filename && !opts->player_idle_mode) {
3859 // no file/vcd/dvd -> show HELP:
3860 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", mp_gtext(help_text));
3861 exit_player_with_rc(mpctx, EXIT_NONE, 0);
3864 /* Display what configure line was used */
3865 mp_msg(MSGT_CPLAYER, MSGL_V, "Configuration: " CONFIGURATION "\n");
3867 // Many users forget to include command line in bugreports...
3868 if( mp_msg_test(MSGT_CPLAYER,MSGL_V) ){
3869 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "CommandLine:");
3870 for(i=1;i<argc;i++)mp_msg(MSGT_CPLAYER, MSGL_INFO," '%s'",argv[i]);
3871 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
3874 //------ load global data first ------
3876 mpctx->osd = osd_create();
3878 // check font
3879 #ifdef CONFIG_FREETYPE
3880 init_freetype();
3881 #endif
3882 #ifdef CONFIG_FONTCONFIG
3883 if(font_fontconfig <= 0)
3885 #endif
3886 #ifdef CONFIG_BITMAP_FONT
3887 if(font_name){
3888 vo_font=read_font_desc(font_name,font_factor,verbose>1);
3889 if(!vo_font) mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load bitmap font: %s\n",
3890 filename_recode(font_name));
3891 } else {
3892 // try default:
3893 vo_font=read_font_desc( mem_ptr=get_path("font/font.desc"),font_factor,verbose>1);
3894 free(mem_ptr); // release the buffer created by get_path()
3895 if(!vo_font)
3896 vo_font=read_font_desc(MPLAYER_DATADIR "/font/font.desc",font_factor,verbose>1);
3898 if (sub_font_name)
3899 mpctx->osd->sub_font = read_font_desc(sub_font_name, font_factor, verbose>1);
3900 else
3901 mpctx->osd->sub_font = vo_font;
3902 #endif
3903 #ifdef CONFIG_FONTCONFIG
3905 #endif
3907 #ifdef CONFIG_ASS
3908 ass_library = mp_ass_init();
3909 #endif
3911 #ifdef HAVE_RTC
3912 if(opts->rtc)
3914 char *rtc_device = opts->rtc_device;
3915 // seteuid(0); /* Can't hurt to try to get root here */
3916 if ((rtc_fd = open(rtc_device ? rtc_device : "/dev/rtc", O_RDONLY)) < 0)
3917 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Failed to open %s: %s (it should be readable by the user.)\n",
3918 rtc_device ? rtc_device : "/dev/rtc", strerror(errno));
3919 else {
3920 unsigned long irqp = 1024; /* 512 seemed OK. 128 is jerky. */
3922 if (ioctl(rtc_fd, RTC_IRQP_SET, irqp) < 0) {
3923 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Linux RTC init error in ioctl (rtc_irqp_set %lu): %s\n", irqp, strerror(errno));
3924 mp_tmsg(MSGT_CPLAYER, MSGL_HINT, "Try adding \"echo %lu > /proc/sys/dev/rtc/max-user-freq\" to your system startup scripts.\n", irqp);
3925 close (rtc_fd);
3926 rtc_fd = -1;
3927 } else if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
3928 /* variable only by the root */
3929 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC init error in ioctl (rtc_pie_on): %s\n", strerror(errno));
3930 close (rtc_fd);
3931 rtc_fd = -1;
3932 } else
3933 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Using Linux hardware RTC timing (%ldHz).\n", irqp);
3936 if(rtc_fd<0)
3937 #endif /* HAVE_RTC */
3938 mp_msg(MSGT_CPLAYER, MSGL_V, "Using %s timing\n",
3939 opts->softsleep ? "software" : timer_name);
3941 #ifdef HAVE_TERMCAP
3942 load_termcap(NULL); // load key-codes
3943 #endif
3945 // ========== Init keyboard FIFO (connection to libvo) ============
3947 // Init input system
3948 current_module = "init_input";
3949 mpctx->input = mp_input_init(&opts->input);
3950 mp_input_add_key_fd(mpctx->input, -1,0,mplayer_get_key,NULL, mpctx->key_fifo);
3951 if(slave_mode)
3952 mp_input_add_cmd_fd(mpctx->input, 0,USE_SELECT,MP_INPUT_SLAVE_CMD_FUNC,NULL);
3953 else if (opts->consolecontrols)
3954 mp_input_add_key_fd(mpctx->input, 0, 1, read_keys, NULL, mpctx->key_fifo);
3955 // Set the libstream interrupt callback
3956 stream_set_interrupt_callback(mp_input_check_interrupt, mpctx->input);
3958 #ifdef CONFIG_MENU
3959 if(use_menu) {
3960 if(menu_cfg && menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
3961 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
3962 else {
3963 menu_cfg = get_path("menu.conf");
3964 if(menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
3965 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
3966 else {
3967 if(menu_init(mpctx, mpctx->mconfig, mpctx->input,
3968 MPLAYER_CONFDIR "/menu.conf"))
3969 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", MPLAYER_CONFDIR"/menu.conf");
3970 else {
3971 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Menu init failed.\n");
3972 use_menu = 0;
3977 #endif
3979 current_module = NULL;
3981 /// Catch signals
3982 #ifndef __MINGW32__
3983 signal(SIGCHLD,child_sighandler);
3984 #endif
3986 #ifdef CONFIG_CRASH_DEBUG
3987 prog_path = argv[0];
3988 #endif
3989 //========= Catch terminate signals: ================
3990 // terminate requests:
3991 signal(SIGTERM,exit_sighandler); // kill
3992 signal(SIGHUP,exit_sighandler); // kill -HUP / xterm closed
3994 signal(SIGINT,exit_sighandler); // Interrupt from keyboard
3996 signal(SIGQUIT,exit_sighandler); // Quit from keyboard
3997 signal(SIGPIPE,exit_sighandler); // Some window managers cause this
3998 #ifdef CONFIG_SIGHANDLER
3999 // fatal errors:
4000 signal(SIGBUS,exit_sighandler); // bus error
4001 signal(SIGSEGV,exit_sighandler); // segfault
4002 signal(SIGILL,exit_sighandler); // illegal instruction
4003 signal(SIGFPE,exit_sighandler); // floating point exc.
4004 signal(SIGABRT,exit_sighandler); // abort()
4005 #ifdef CONFIG_CRASH_DEBUG
4006 if (crash_debug)
4007 signal(SIGTRAP,exit_sighandler);
4008 #endif
4009 #endif
4011 // ******************* Now, let's see the per-file stuff ********************
4013 play_next_file:
4015 // init global sub numbers
4016 mpctx->global_sub_size = 0;
4017 memset(mpctx->sub_counts, 0, sizeof(mpctx->sub_counts));
4019 if (mpctx->filename) {
4020 load_per_protocol_config (mpctx->mconfig, mpctx->filename);
4021 load_per_extension_config (mpctx->mconfig, mpctx->filename);
4022 load_per_file_config (mpctx->mconfig, mpctx->filename);
4025 if (opts->video_driver_list)
4026 load_per_output_config (mpctx->mconfig, PROFILE_CFG_VO, opts->video_driver_list[0]);
4027 if (opts->audio_driver_list)
4028 load_per_output_config (mpctx->mconfig, PROFILE_CFG_AO, opts->audio_driver_list[0]);
4030 // We must enable getch2 here to be able to interrupt network connection
4031 // or cache filling
4032 if (opts->consolecontrols && !slave_mode) {
4033 if(mpctx->initialized_flags&INITIALIZED_GETCH2)
4034 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"WARNING: getch2_init called twice!\n");
4035 else
4036 getch2_enable(); // prepare stdin for hotkeys...
4037 mpctx->initialized_flags|=INITIALIZED_GETCH2;
4038 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[init getch2]]]\n");
4041 // =================== GUI idle loop (STOP state) ===========================
4042 while (opts->player_idle_mode && !mpctx->filename) {
4043 play_tree_t * entry = NULL;
4044 mp_cmd_t * cmd;
4045 if (mpctx->video_out && mpctx->video_out->config_ok)
4046 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
4047 while (!(cmd = mp_input_get_cmd(mpctx->input, 0, 0))) { // wait for command
4048 if (mpctx->video_out)
4049 vo_check_events(mpctx->video_out);
4050 usec_sleep(20000);
4052 switch (cmd->id) {
4053 case MP_CMD_LOADFILE:
4054 // prepare a tree entry with the new filename
4055 entry = play_tree_new();
4056 play_tree_add_file(entry, cmd->args[0].v.s);
4057 // The entry is added to the main playtree after the switch().
4058 break;
4059 case MP_CMD_LOADLIST:
4060 entry = parse_playlist_file(mpctx->mconfig, cmd->args[0].v.s);
4061 break;
4062 case MP_CMD_QUIT:
4063 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
4064 break;
4065 case MP_CMD_VO_FULLSCREEN:
4066 case MP_CMD_GET_PROPERTY:
4067 case MP_CMD_SET_PROPERTY:
4068 case MP_CMD_STEP_PROPERTY:
4069 run_command(mpctx, cmd);
4070 break;
4073 mp_cmd_free(cmd);
4075 if (entry) { // user entered a command that gave a valid entry
4076 if (mpctx->playtree) // the playtree is always a node with one child. let's clear it
4077 play_tree_free_list(mpctx->playtree->child, 1);
4078 else mpctx->playtree=play_tree_new(); // .. or make a brand new playtree
4080 if (!mpctx->playtree) continue; // couldn't make playtree! wait for next command
4082 play_tree_set_child(mpctx->playtree, entry);
4084 /* Make iterator start at the top the of tree. */
4085 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree, mpctx->mconfig);
4086 if (!mpctx->playtree_iter) continue;
4088 // find the first real item in the tree
4089 if (play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
4090 // no items!
4091 play_tree_iter_free(mpctx->playtree_iter);
4092 mpctx->playtree_iter = NULL;
4093 continue; // wait for next command
4095 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, 1);
4098 //---------------------------------------------------------------------------
4100 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
4101 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL);
4103 if (mpctx->filename) {
4104 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nPlaying %s.\n",
4105 filename_recode(mpctx->filename));
4106 if(use_filename_title && opts->vo_wintitle == NULL)
4107 opts->vo_wintitle = strdup(mp_basename(mpctx->filename));
4110 if (edl_filename) {
4111 if (edl_records) free_edl(edl_records);
4112 next_edl_record = edl_records = edl_parse_file();
4114 if (edl_output_filename) {
4115 if (edl_fd) fclose(edl_fd);
4116 if ((edl_fd = fopen(edl_output_filename, "w")) == NULL)
4118 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Can't open EDL file [%s] for writing.\n",
4119 filename_recode(edl_output_filename));
4123 //==================== Open VOB-Sub ============================
4125 current_module="vobsub";
4126 if (vobsub_name){
4127 vo_vobsub=vobsub_open(vobsub_name,spudec_ifo,1,&vo_spudec);
4128 if(vo_vobsub==NULL)
4129 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load subtitles: %s\n",
4130 filename_recode(vobsub_name));
4131 } else if (sub_auto && mpctx->filename){
4132 /* try to autodetect vobsub from movie filename ::atmos */
4133 char *buf = strdup(mpctx->filename), *psub;
4134 char *pdot = strrchr(buf, '.');
4135 char *pslash = strrchr(buf, '/');
4136 #if defined(__MINGW32__) || defined(__CYGWIN__)
4137 if (!pslash) pslash = strrchr(buf, '\\');
4138 #endif
4139 if (pdot && (!pslash || pdot > pslash))
4140 *pdot = '\0';
4141 vo_vobsub=vobsub_open(buf,spudec_ifo,0,&vo_spudec);
4142 /* try from ~/.mplayer/sub */
4143 if(!vo_vobsub && (psub = get_path( "sub/" ))) {
4144 const char *bname = mp_basename(buf);
4145 int l;
4146 l = strlen(psub) + strlen(bname) + 1;
4147 psub = realloc(psub,l);
4148 strcat(psub,bname);
4149 vo_vobsub=vobsub_open(psub,spudec_ifo,0,&vo_spudec);
4150 free(psub);
4152 free(buf);
4154 if(vo_vobsub){
4155 mpctx->initialized_flags|=INITIALIZED_VOBSUB;
4156 vobsub_set_from_lang(vo_vobsub, opts->sub_lang);
4157 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
4159 // setup global sub numbering
4160 mpctx->sub_counts[SUB_SOURCE_VOBSUB] = vobsub_get_indexes_count(vo_vobsub);
4163 //============ Open & Sync STREAM --- fork cache2 ====================
4165 mpctx->stream=NULL;
4166 mpctx->demuxer=NULL;
4167 mpctx->d_audio=NULL;
4168 mpctx->d_video=NULL;
4169 mpctx->d_sub = NULL;
4170 mpctx->sh_audio=NULL;
4171 mpctx->sh_video=NULL;
4173 current_module="open_stream";
4174 mpctx->stream = open_stream(mpctx->filename, opts, &mpctx->file_format);
4175 if(!mpctx->stream) { // error...
4176 mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY);
4177 goto goto_next_file;
4179 mpctx->initialized_flags|=INITIALIZED_STREAM;
4181 if(mpctx->file_format == DEMUXER_TYPE_PLAYLIST) {
4182 mp_msg(MSGT_CPLAYER, MSGL_ERR, "\nThis looks like a playlist, but "
4183 "playlist support will not be used automatically.\n"
4184 "MPlayer's playlist code is unsafe and should only be used with "
4185 "trusted sources.\nPlayback will probably fail.\n\n");
4186 #if 0
4187 play_tree_t* entry;
4188 // Handle playlist
4189 current_module="handle_playlist";
4190 mp_msg(MSGT_CPLAYER,MSGL_V,"Parsing playlist %s...\n",
4191 filename_recode(mpctx->filename));
4192 entry = parse_playtree(mpctx->stream, mpctx->mconfig, 0);
4193 mpctx->eof=playtree_add_playlist(mpctx, entry);
4194 goto goto_next_file;
4195 #endif
4197 mpctx->stream->start_pos+=seek_to_byte;
4199 if(stream_dump_type==5){
4200 unsigned char buf[4096];
4201 int len;
4202 FILE *f;
4203 current_module="dumpstream";
4204 stream_reset(mpctx->stream);
4205 stream_seek(mpctx->stream,mpctx->stream->start_pos);
4206 f=fopen(opts->stream_dump_name,"wb");
4207 if(!f){
4208 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
4209 exit_player(mpctx, EXIT_ERROR);
4211 if (opts->chapterrange[0] > 1) {
4212 int chapter = opts->chapterrange[0] - 1;
4213 stream_control(mpctx->stream, STREAM_CTRL_SEEK_TO_CHAPTER, &chapter);
4215 while(!mpctx->stream->eof && !async_quit_request){
4216 len=stream_read(mpctx->stream,buf,4096);
4217 if(len>0) {
4218 if(fwrite(buf,len,1,f) != 1) {
4219 mp_tmsg(MSGT_GLOBAL,MSGL_FATAL,"%s: Error writing file.\n",opts->stream_dump_name);
4220 exit_player(mpctx, EXIT_ERROR);
4223 if (opts->chapterrange[1] > 0) {
4224 int chapter = -1;
4225 if (stream_control(mpctx->stream, STREAM_CTRL_GET_CURRENT_CHAPTER,
4226 &chapter) == STREAM_OK
4227 && chapter + 1 > opts->chapterrange[1])
4228 break;
4231 if(fclose(f)) {
4232 mp_tmsg(MSGT_GLOBAL,MSGL_FATAL,"%s: Error writing file.\n",opts->stream_dump_name);
4233 exit_player(mpctx, EXIT_ERROR);
4235 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Stream dump complete.\n");
4236 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4239 #ifdef CONFIG_DVDREAD
4240 if(mpctx->stream->type==STREAMTYPE_DVD){
4241 current_module="dvd lang->id";
4242 if(opts->audio_lang && opts->audio_id==-1) opts->audio_id=dvd_aid_from_lang(mpctx->stream,opts->audio_lang);
4243 if(opts->sub_lang && opts->sub_id==-1) opts->sub_id=dvd_sid_from_lang(mpctx->stream,opts->sub_lang);
4244 // setup global sub numbering
4245 mpctx->sub_counts[SUB_SOURCE_DEMUX] = dvd_number_of_subs(mpctx->stream);
4246 current_module=NULL;
4248 #endif
4250 #ifdef CONFIG_DVDNAV
4251 if(mpctx->stream->type==STREAMTYPE_DVDNAV){
4252 current_module="dvdnav lang->id";
4253 if(opts->audio_lang && opts->audio_id==-1) opts->audio_id=mp_dvdnav_aid_from_lang(mpctx->stream,opts->audio_lang);
4254 dvdsub_lang_id = -3;
4255 if(opts->sub_lang && opts->sub_id==-1)
4256 dvdsub_lang_id = opts->sub_id = mp_dvdnav_sid_from_lang(mpctx->stream,opts->sub_lang);
4257 // setup global sub numbering
4258 mpctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(mpctx->stream);
4259 current_module=NULL;
4261 #endif
4263 // CACHE2: initial prefill: 20% later: 5% (should be set by -cacheopts)
4264 goto_enable_cache:
4265 if(stream_cache_size>0){
4266 int res;
4267 float stream_cache_min_percent = opts->stream_cache_min_percent;
4268 float stream_cache_seek_min_percent = opts->stream_cache_seek_min_percent;
4269 current_module="enable_cache";
4270 res = stream_enable_cache(mpctx->stream,stream_cache_size*1024,
4271 stream_cache_size*1024*(stream_cache_min_percent / 100.0),
4272 stream_cache_size*1024*(stream_cache_seek_min_percent / 100.0));
4273 if(res == 0)
4274 if((mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY))) goto goto_next_file;
4277 //============ Open DEMUXERS --- DETECT file type =======================
4278 current_module="demux_open";
4280 mpctx->demuxer=demux_open(opts, mpctx->stream,mpctx->file_format,opts->audio_id,opts->video_id,opts->sub_id,mpctx->filename);
4282 // HACK to get MOV Reference Files working
4284 if (mpctx->demuxer && mpctx->demuxer->type==DEMUXER_TYPE_PLAYLIST)
4286 unsigned char* playlist_entry;
4287 play_tree_t *list = NULL, *entry = NULL;
4289 current_module="handle_demux_playlist";
4290 while (ds_get_packet(mpctx->demuxer->video,&playlist_entry)>0)
4292 char *temp;
4293 const char *bname;
4295 mp_msg(MSGT_CPLAYER,MSGL_V,"Adding file %s to element entry.\n",
4296 filename_recode(playlist_entry));
4298 bname=mp_basename(playlist_entry);
4299 if ((strlen(bname)>10) && !strncmp(bname,"qt",2) && !strncmp(bname+3,"gateQT",6))
4300 continue;
4302 if (!strcmp(playlist_entry, mpctx->filename)) // ignoring self-reference
4303 continue;
4305 entry = play_tree_new();
4307 if (mpctx->filename && !strcmp(mp_basename(playlist_entry),playlist_entry)) // add reference path of current file
4309 temp=malloc((strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))+strlen(playlist_entry)+1));
4310 if (temp)
4312 strncpy(temp, mpctx->filename, strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename)));
4313 temp[strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))]='\0';
4314 strcat(temp, playlist_entry);
4315 if (!strcmp(temp, mpctx->filename)) {
4316 free(temp);
4317 continue;
4319 play_tree_add_file(entry,temp);
4320 mp_msg(MSGT_CPLAYER,MSGL_V,"Resolving reference to %s.\n",temp);
4321 free(temp);
4324 else
4325 play_tree_add_file(entry,playlist_entry);
4327 if(!list)
4328 list = entry;
4329 else
4330 play_tree_append_entry(list,entry);
4332 free_demuxer(mpctx->demuxer);
4333 mpctx->demuxer = NULL;
4335 if (list)
4337 entry = play_tree_new();
4338 play_tree_set_child(entry,list);
4339 mpctx->stop_play = playtree_add_playlist(mpctx, entry);
4340 goto goto_next_file;
4344 if(!mpctx->demuxer) {
4345 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Failed to recognize file format.\n");
4346 goto goto_next_file;
4349 if (mpctx->demuxer->matroska_data.ordered_chapters)
4350 build_ordered_chapter_timeline(mpctx);
4352 if (mpctx->demuxer->type == DEMUXER_TYPE_EDL)
4353 build_edl_timeline(mpctx);
4355 if (mpctx->timeline) {
4356 mpctx->timeline_part = 0;
4357 mpctx->demuxer = mpctx->timeline[0].source->demuxer;
4359 int part_count = mpctx->num_timeline_parts;
4360 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline contains %d parts from %d "
4361 "sources. Total length %.3f seconds.\n", part_count,
4362 mpctx->num_sources, mpctx->timeline[part_count].start);
4363 mp_msg(MSGT_CPLAYER, MSGL_V, "Source files:\n");
4364 for (int i = 0; i < mpctx->num_sources; i++)
4365 mp_msg(MSGT_CPLAYER, MSGL_V, "%d: %s\n", i,
4366 filename_recode(mpctx->sources[i].demuxer->filename));
4367 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline parts: (number, start, "
4368 "source_start, source):\n");
4369 for (int i = 0; i < part_count; i++) {
4370 struct timeline_part *p = mpctx->timeline + i;
4371 mp_msg(MSGT_CPLAYER, MSGL_V, "%3d %9.3f %9.3f %3td\n", i, p->start,
4372 p->source_start, p->source - mpctx->sources);
4374 mp_msg(MSGT_CPLAYER, MSGL_V, "END %9.3f\n",
4375 mpctx->timeline[part_count].start);
4378 if (!mpctx->sources) {
4379 mpctx->sources = talloc_ptrtype(NULL, mpctx->sources);
4380 *mpctx->sources = (struct content_source){.stream = mpctx->stream,
4381 .demuxer = mpctx->demuxer};
4382 mpctx->num_sources = 1;
4385 mpctx->initialized_flags|=INITIALIZED_DEMUXER;
4387 #ifdef CONFIG_ASS
4388 if (opts->ass_enabled && ass_library) {
4389 for (int j = 0; j < mpctx->num_sources; j++) {
4390 struct demuxer *d = mpctx->sources[j].demuxer;
4391 for (int i = 0; i < d->num_attachments; i++) {
4392 struct demux_attachment *att = d->attachments + i;
4393 if (use_embedded_fonts && attachment_is_font(att))
4394 ass_add_font(ass_library, att->name, att->data, att->data_size);
4398 #endif
4400 current_module="demux_open2";
4402 mpctx->d_audio=mpctx->demuxer->audio;
4403 mpctx->d_video=mpctx->demuxer->video;
4404 mpctx->d_sub=mpctx->demuxer->sub;
4406 if (ts_prog) {
4407 int tmp = ts_prog;
4408 mp_property_do("switch_program", M_PROPERTY_SET, &tmp, mpctx);
4410 // select audio stream
4411 if (mpctx->num_sources)
4412 for (int i = 0; i < mpctx->num_sources; i++)
4413 select_audio(mpctx->sources[i].demuxer, opts->audio_id,
4414 opts->audio_lang);
4415 else
4416 select_audio(mpctx->d_audio->demuxer, opts->audio_id, opts->audio_lang);
4418 // DUMP STREAMS:
4419 if((stream_dump_type)&&(stream_dump_type<4)){
4420 FILE *f;
4421 demux_stream_t *ds=NULL;
4422 current_module="dump";
4423 // select stream to dump
4424 switch(stream_dump_type){
4425 case 1: ds=mpctx->d_audio;break;
4426 case 2: ds=mpctx->d_video;break;
4427 case 3: ds=mpctx->d_sub;break;
4429 if(!ds){
4430 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"dump: FATAL: Selected stream missing!\n");
4431 exit_player(mpctx, EXIT_ERROR);
4433 // disable other streams:
4434 if(mpctx->d_audio && mpctx->d_audio!=ds) {ds_free_packs(mpctx->d_audio); mpctx->d_audio->id=-2; }
4435 if(mpctx->d_video && mpctx->d_video!=ds) {ds_free_packs(mpctx->d_video); mpctx->d_video->id=-2; }
4436 if(mpctx->d_sub && mpctx->d_sub!=ds) {ds_free_packs(mpctx->d_sub); mpctx->d_sub->id=-2; }
4437 // let's dump it!
4438 f=fopen(opts->stream_dump_name,"wb");
4439 if(!f){
4440 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
4441 exit_player(mpctx, EXIT_ERROR);
4443 while(!ds->eof){
4444 unsigned char* start;
4445 int in_size=ds_get_packet(ds,&start);
4446 if( (mpctx->demuxer->file_format==DEMUXER_TYPE_AVI || mpctx->demuxer->file_format==DEMUXER_TYPE_ASF || mpctx->demuxer->file_format==DEMUXER_TYPE_MOV)
4447 && stream_dump_type==2) fwrite(&in_size,1,4,f);
4448 if(in_size>0) fwrite(start,in_size,1,f);
4449 if (opts->chapterrange[1] > 0) {
4450 int cur_chapter = demuxer_get_current_chapter(mpctx->demuxer, 0);
4451 if(cur_chapter!=-1 && cur_chapter+1 > opts->chapterrange[1])
4452 break;
4455 fclose(f);
4456 mp_tmsg(MSGT_CPLAYER ,MSGL_INFO, "Stream dump complete.\n");
4457 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4460 mpctx->sh_audio=mpctx->d_audio->sh;
4461 mpctx->sh_video=mpctx->d_video->sh;
4463 if(mpctx->sh_video){
4465 current_module="video_read_properties";
4466 if(!video_read_properties(mpctx->sh_video)) {
4467 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Video: Cannot read properties.\n");
4468 mpctx->sh_video=mpctx->d_video->sh=NULL;
4469 } else {
4470 mp_tmsg(MSGT_CPLAYER,MSGL_V,"[V] filefmt:%d fourcc:0x%X size:%dx%d fps:%5.3f ftime:=%6.4f\n",
4471 mpctx->demuxer->file_format,mpctx->sh_video->format, mpctx->sh_video->disp_w,mpctx->sh_video->disp_h,
4472 mpctx->sh_video->fps,mpctx->sh_video->frametime
4475 /* need to set fps here for output encoders to pick it up in their init */
4476 if(force_fps){
4477 mpctx->sh_video->fps=force_fps;
4478 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
4480 vo_fps = mpctx->sh_video->fps;
4482 if(!mpctx->sh_video->fps && !force_fps){
4483 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"FPS not specified in the header or invalid, use the -fps option.\n");
4484 mpctx->opts.correct_pts = 1;
4490 if(!mpctx->sh_video && !mpctx->sh_audio){
4491 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL, "No stream found.\n");
4492 #ifdef CONFIG_DVBIN
4493 if(mpctx->stream->type == STREAMTYPE_DVB)
4495 int dir;
4496 int v = mpctx->last_dvb_step;
4497 if(v > 0)
4498 dir = DVB_CHANNEL_HIGHER;
4499 else
4500 dir = DVB_CHANNEL_LOWER;
4502 if(dvb_step_channel(mpctx->stream, dir)) {
4503 mpctx->stop_play = PT_NEXT_ENTRY;
4504 mpctx->dvbin_reopen = 1;
4507 #endif
4508 goto goto_next_file; // exit_player(_("Fatal error"));
4511 /* display clip info */
4512 demux_info_print(mpctx->demuxer);
4514 //================== Read SUBTITLES (DVD & TEXT) ==========================
4515 if(vo_spudec==NULL &&
4516 (mpctx->stream->type==STREAMTYPE_DVD || mpctx->stream->type == STREAMTYPE_DVDNAV)){
4517 init_vo_spudec(mpctx);
4520 // after reading video params we should load subtitles because
4521 // we know fps so now we can adjust subtitle time to ~6 seconds AST
4522 // check .sub
4523 current_module="read_subtitles_file";
4524 double sub_fps = mpctx->sh_video ? mpctx->sh_video->fps : 25;
4525 if(sub_name){
4526 for (i = 0; sub_name[i] != NULL; ++i)
4527 add_subtitles(mpctx, sub_name[i], sub_fps, 0);
4529 if(sub_auto) { // auto load sub file ...
4530 char *psub = get_path( "sub/" );
4531 char **tmp = sub_filenames((psub ? psub : ""), mpctx->filename);
4532 int i = 0;
4533 free(psub); // release the buffer created by get_path() above
4534 while (tmp[i]) {
4535 add_subtitles(mpctx, tmp[i], sub_fps, 1);
4536 free(tmp[i++]);
4538 free(tmp);
4540 if (mpctx->set_of_sub_size > 0)
4541 mpctx->sub_counts[SUB_SOURCE_SUBS] = mpctx->set_of_sub_size;
4543 if (select_subtitle(mpctx)) {
4544 if(mpctx->subdata)
4545 switch (stream_dump_type) {
4546 case 3: list_sub_file(mpctx->subdata); break;
4547 case 4: dump_mpsub(mpctx->subdata, mpctx->sh_video->fps); break;
4548 case 6: dump_srt(mpctx->subdata, mpctx->sh_video->fps); break;
4549 case 7: dump_microdvd(mpctx->subdata, mpctx->sh_video->fps); break;
4550 case 8: dump_jacosub(mpctx->subdata, mpctx->sh_video->fps); break;
4551 case 9: dump_sami(mpctx->subdata, mpctx->sh_video->fps); break;
4555 print_file_properties(mpctx, mpctx->filename);
4557 if (mpctx->sh_video)
4558 reinit_video_chain(mpctx);
4559 if (mpctx->sh_video) {
4560 if(mpctx->sh_video->output_flags & VFCAP_SPU && vo_spudec)
4561 spudec_set_hw_spu(vo_spudec,mpctx->video_out);
4562 #ifdef CONFIG_FREETYPE
4563 force_load_font = 1;
4564 #endif
4565 } else if (!mpctx->sh_audio)
4566 goto goto_next_file;
4568 //================== MAIN: ==========================
4569 current_module="main";
4571 if (opts->playing_msg) {
4572 char* msg = property_expand_string(mpctx, opts->playing_msg);
4573 mp_msg(MSGT_CPLAYER,MSGL_INFO,"%s",msg);
4574 free(msg);
4578 // Disable the term OSD in verbose mode
4579 if (verbose)
4580 opts->term_osd = 0;
4584 // Make sure old OSD does not stay around,
4585 // e.g. with -fixed-vo and same-resolution files
4586 clear_osd_msgs();
4587 update_osd_msg(mpctx);
4589 //================ SETUP AUDIO ==========================
4591 if(mpctx->sh_audio){
4592 reinit_audio_chain(mpctx);
4593 if (mpctx->sh_audio && mpctx->sh_audio->codec)
4594 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_CODEC=%s\n", mpctx->sh_audio->codec->name);
4597 current_module="av_init";
4599 if(mpctx->sh_video){
4600 mpctx->sh_video->timer=0;
4601 if (! ignore_start)
4602 audio_delay += mpctx->sh_video->stream_delay;
4604 if(mpctx->sh_audio){
4605 if (start_volume >= 0)
4606 mixer_setvolume(&mpctx->mixer, start_volume, start_volume);
4607 if (! ignore_start)
4608 audio_delay -= mpctx->sh_audio->stream_delay;
4609 mpctx->delay=-audio_delay;
4612 if(!mpctx->sh_audio){
4613 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Audio: no sound\n");
4614 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused audio chunks.\n",mpctx->d_audio->packs);
4615 ds_free_packs(mpctx->d_audio); // free buffered chunks
4616 //mpctx->d_audio->id=-2; // do not read audio chunks
4617 //uninit_player(mpctx, INITIALIZED_AO); // close device
4619 if(!mpctx->sh_video){
4620 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Video: no video\n");
4621 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused video chunks.\n",mpctx->d_video->packs);
4622 ds_free_packs(mpctx->d_video);
4623 mpctx->d_video->id=-2;
4624 //if(!fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
4627 if (!mpctx->sh_video && !mpctx->sh_audio)
4628 goto goto_next_file;
4630 //if(demuxer->file_format!=DEMUXER_TYPE_AVI) pts_from_bps=0; // it must be 0 for mpeg/asf!
4631 if(force_fps && mpctx->sh_video){
4632 vo_fps = mpctx->sh_video->fps=force_fps;
4633 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
4634 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"FPS forced to be %5.3f (ftime: %5.3f).\n",mpctx->sh_video->fps,mpctx->sh_video->frametime);
4637 mp_input_set_section(mpctx->input, NULL);
4638 //TODO: add desired (stream-based) sections here
4639 if (mpctx->stream->type==STREAMTYPE_TV) mp_input_set_section(mpctx->input, "tv");
4640 if (mpctx->stream->type==STREAMTYPE_DVDNAV) mp_input_set_section(mpctx->input, "dvdnav");
4642 //==================== START PLAYING =======================
4644 if(opts->loop_times>1) opts->loop_times--; else
4645 if(opts->loop_times==1) opts->loop_times = -1;
4647 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Starting playback...\n");
4649 total_time_usage_start=GetTimer();
4650 audio_time_usage=0; video_time_usage=0; vout_time_usage=0;
4651 total_frame_cnt=0; drop_frame_cnt=0; // fix for multifile fps benchmark
4652 play_n_frames=play_n_frames_mf;
4654 if(play_n_frames==0){
4655 mpctx->stop_play=PT_NEXT_ENTRY; goto goto_next_file;
4658 mpctx->time_frame = 0;
4659 mpctx->drop_message_shown = 0;
4660 mpctx->restart_playback = true;
4661 mpctx->video_pts = 0;
4662 mpctx->hrseek_active = false;
4663 mpctx->hrseek_framedrop = false;
4664 mpctx->step_frames = 0;
4665 mpctx->total_avsync_change = 0;
4666 mpctx->last_chapter_seek = -1;
4668 // If there's a timeline force an absolute seek to initialize state
4669 if (seek_to_sec || mpctx->timeline) {
4670 queue_seek(mpctx, MPSEEK_ABSOLUTE, seek_to_sec, 0);
4671 seek(mpctx, mpctx->seek);
4672 end_at.pos += seek_to_sec;
4674 if (opts->chapterrange[0] > 0) {
4675 double pts;
4676 if (seek_chapter(mpctx, opts->chapterrange[0]-1, &pts, NULL) >= 0
4677 && pts > -1.0) {
4678 queue_seek(mpctx, MPSEEK_ABSOLUTE, pts, 0);
4679 seek(mpctx, mpctx->seek);
4683 if (end_at.type == END_AT_SIZE) {
4684 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Option -endpos in MPlayer does not yet support size units.\n");
4685 end_at.type = END_AT_NONE;
4688 #ifdef CONFIG_DVDNAV
4689 mp_dvdnav_context_free(mpctx);
4690 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4691 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
4692 mp_dvdnav_cell_has_changed(mpctx->stream,1);
4694 #endif
4696 mpctx->seek = (struct seek_params){0};
4697 get_relative_time(mpctx); // reset current delta
4698 // Make sure VO knows current pause state
4699 if (mpctx->sh_video)
4700 vo_control(mpctx->video_out, mpctx->paused ? VOCTRL_PAUSE : VOCTRL_RESUME,
4701 NULL);
4703 while (!mpctx->stop_play)
4704 run_playloop(mpctx);
4706 mp_msg(MSGT_GLOBAL,MSGL_V,"EOF code: %d \n",mpctx->stop_play);
4708 #ifdef CONFIG_DVBIN
4709 if(mpctx->dvbin_reopen)
4711 mpctx->stop_play = 0;
4712 uninit_player(mpctx, INITIALIZED_ALL-(INITIALIZED_STREAM|INITIALIZED_GETCH2|(opts->fixed_vo?INITIALIZED_VO:0)));
4713 cache_uninit(mpctx->stream);
4714 mpctx->dvbin_reopen = 0;
4715 goto goto_enable_cache;
4717 #endif
4720 goto_next_file: // don't jump here after ao/vo/getch initialization!
4722 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\n");
4724 if (opts->benchmark) {
4725 double tot=video_time_usage+vout_time_usage+audio_time_usage;
4726 double total_time_usage;
4727 total_time_usage_start=GetTimer()-total_time_usage_start;
4728 total_time_usage = (float)total_time_usage_start*0.000001;
4729 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\nBENCHMARKs: VC:%8.3fs VO:%8.3fs A:%8.3fs Sys:%8.3fs = %8.3fs\n",
4730 video_time_usage,vout_time_usage,audio_time_usage,
4731 total_time_usage-tot,total_time_usage);
4732 if(total_time_usage>0.0)
4733 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARK%%: VC:%8.4f%% VO:%8.4f%% A:%8.4f%% Sys:%8.4f%% = %8.4f%%\n",
4734 100.0*video_time_usage/total_time_usage,
4735 100.0*vout_time_usage/total_time_usage,
4736 100.0*audio_time_usage/total_time_usage,
4737 100.0*(total_time_usage-tot)/total_time_usage,
4738 100.0);
4739 if(total_frame_cnt && frame_dropping)
4740 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARKn: disp: %d (%3.2f fps) drop: %d (%d%%) total: %d (%3.2f fps)\n",
4741 total_frame_cnt-drop_frame_cnt,
4742 (total_time_usage>0.5)?((total_frame_cnt-drop_frame_cnt)/total_time_usage):0,
4743 drop_frame_cnt,
4744 100*drop_frame_cnt/total_frame_cnt,
4745 total_frame_cnt,
4746 (total_time_usage>0.5)?(total_frame_cnt/total_time_usage):0);
4749 // time to uninit all, except global stuff:
4750 int uninitialize_parts = INITIALIZED_ALL;
4751 if (opts->fixed_vo)
4752 uninitialize_parts -= INITIALIZED_VO;
4753 if (opts->gapless_audio && mpctx->stop_play == AT_END_OF_FILE)
4754 uninitialize_parts -= INITIALIZED_AO;
4755 uninit_player(mpctx, uninitialize_parts);
4757 if(mpctx->set_of_sub_size > 0) {
4758 current_module="sub_free";
4759 for(i = 0; i < mpctx->set_of_sub_size; ++i) {
4760 sub_free(mpctx->set_of_subtitles[i]);
4761 #ifdef CONFIG_ASS
4762 if(mpctx->set_of_ass_tracks[i])
4763 ass_free_track( mpctx->set_of_ass_tracks[i] );
4764 #endif
4766 mpctx->set_of_sub_size = 0;
4768 mpctx->vo_sub_last = vo_sub=NULL;
4769 mpctx->subdata=NULL;
4770 #ifdef CONFIG_ASS
4771 mpctx->osd->ass_track = NULL;
4772 if(ass_library)
4773 ass_clear_fonts(ass_library);
4774 #endif
4776 if (!mpctx->stop_play) // In case some goto jumped here...
4777 mpctx->stop_play = PT_NEXT_ENTRY;
4779 int playtree_direction = 1;
4781 if(mpctx->stop_play == PT_NEXT_ENTRY || mpctx->stop_play == PT_PREV_ENTRY) {
4782 if(play_tree_iter_step(mpctx->playtree_iter,mpctx->play_tree_step,0) != PLAY_TREE_ITER_ENTRY) {
4783 play_tree_iter_free(mpctx->playtree_iter);
4784 mpctx->playtree_iter = NULL;
4786 mpctx->play_tree_step = 1;
4787 } else if(mpctx->stop_play == PT_UP_NEXT || mpctx->stop_play == PT_UP_PREV) {
4788 int direction = mpctx->stop_play == PT_UP_NEXT ? 1 : -1;
4789 if(mpctx->playtree_iter) {
4790 if(play_tree_iter_up_step(mpctx->playtree_iter,direction,0) != PLAY_TREE_ITER_ENTRY) {
4791 play_tree_iter_free(mpctx->playtree_iter);
4792 mpctx->playtree_iter = NULL;
4795 } else if (mpctx->stop_play == PT_STOP) {
4796 play_tree_iter_free(mpctx->playtree_iter);
4797 mpctx->playtree_iter = NULL;
4798 } else { // NEXT PREV SRC
4799 playtree_direction = mpctx->stop_play == PT_PREV_SRC ? -1 : 1;
4802 while(mpctx->playtree_iter != NULL) {
4803 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, playtree_direction);
4804 if(mpctx->filename == NULL) {
4805 if(play_tree_iter_step(mpctx->playtree_iter, playtree_direction, 0) != PLAY_TREE_ITER_ENTRY) {
4806 play_tree_iter_free(mpctx->playtree_iter);
4807 mpctx->playtree_iter = NULL;
4809 } else
4810 break;
4813 if (mpctx->playtree_iter != NULL || opts->player_idle_mode) {
4814 if(!mpctx->playtree_iter) mpctx->filename = NULL;
4815 mpctx->stop_play = 0;
4816 goto play_next_file;
4820 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4822 return 1;
4824 #endif /* DISABLE_MAIN */