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