core: move most mpcommon.c contents to mplayer.c
[mplayer/glamo.git] / mplayer.c
blob091287c1fd164885cecc5a59b9fafea9b93864a0
1 /*
2 * This file is part of MPlayer.
4 * MPlayer is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * MPlayer is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License along
15 * with MPlayer; if not, write to the Free Software Foundation, Inc.,
16 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 /// \file
20 /// \ingroup Properties Command2Property OSDMsgStack
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <stdbool.h>
25 #include <math.h>
27 #include "config.h"
28 #include "talloc.h"
30 #if defined(__MINGW32__) || defined(__CYGWIN__)
31 #define _UWIN 1 /*disable Non-underscored versions of non-ANSI functions as otherwise int eof would conflict with eof()*/
32 #include <windows.h>
33 #endif
34 #include <string.h>
35 #include <unistd.h>
37 // #include <sys/mman.h>
38 #include <sys/types.h>
39 #ifndef __MINGW32__
40 #include <sys/ioctl.h>
41 #include <sys/wait.h>
42 #else
43 #define SIGHUP 1 /* hangup */
44 #define SIGQUIT 3 /* quit */
45 #define SIGKILL 9 /* kill (cannot be caught or ignored) */
46 #define SIGBUS 10 /* bus error */
47 #define SIGPIPE 13 /* broken pipe */
48 #endif
50 #include <sys/time.h>
51 #include <sys/stat.h>
53 #include <signal.h>
54 #include <time.h>
55 #include <fcntl.h>
56 #include <limits.h>
58 #include <errno.h>
60 #include "mp_msg.h"
61 #include "av_log.h"
64 #include "m_option.h"
65 #include "m_config.h"
66 #include "mplayer.h"
67 #include "access_mpcontext.h"
68 #include "m_property.h"
70 #include "cfg-mplayer-def.h"
72 #include "libavutil/avstring.h"
74 #include "subreader.h"
76 #include "mp_osd.h"
77 #include "libvo/video_out.h"
79 #include "libvo/font_load.h"
80 #include "libvo/sub.h"
81 #include "ffmpeg_files/intreadwrite.h"
82 #include "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 "spudec.h"
98 #include "vobsub.h"
100 #include "osdep/getch2.h"
101 #include "osdep/timer.h"
102 #include "osdep/findfiles.h"
104 #include "input/input.h"
106 const int under_mencoder = 0;
107 int slave_mode=0;
108 int enable_mouse_movements=0;
109 float start_volume = -1;
111 #include "osdep/priority.h"
113 char *heartbeat_cmd;
115 #define ROUND(x) ((int)((x)<0 ? (x)-0.5 : (x)+0.5))
117 #ifdef HAVE_RTC
118 #ifdef __linux__
119 #include <linux/rtc.h>
120 #else
121 #include <rtc.h>
122 #define RTC_IRQP_SET RTCIO_IRQP_SET
123 #define RTC_PIE_ON RTCIO_PIE_ON
124 #endif /* __linux__ */
125 #endif /* HAVE_RTC */
127 #include "stream/tv.h"
128 #include "stream/stream_radio.h"
129 #ifdef CONFIG_DVBIN
130 #include "stream/dvbin.h"
131 #endif
132 #include "stream/cache2.h"
134 //**************************************************************************//
135 // Playtree
136 //**************************************************************************//
137 #include "playtree.h"
138 #include "playtreeparser.h"
140 //**************************************************************************//
141 // Config
142 //**************************************************************************//
143 #include "parser-cfg.h"
144 #include "parser-mpcmd.h"
146 //**************************************************************************//
147 // Config file
148 //**************************************************************************//
150 static int cfg_inc_verbose(m_option_t *conf){ ++verbose; return 0;}
152 #include "path.h"
154 //**************************************************************************//
155 //**************************************************************************//
156 // Input media streaming & demultiplexer:
157 //**************************************************************************//
159 static int max_framesize=0;
161 #include "stream/stream.h"
162 #include "libmpdemux/demuxer.h"
163 #include "libmpdemux/stheader.h"
165 #ifdef CONFIG_DVDREAD
166 #include "stream/stream_dvd.h"
167 #endif
168 #include "stream/stream_dvdnav.h"
170 #include "libmpcodecs/dec_audio.h"
171 #include "libmpcodecs/dec_video.h"
172 #include "libmpcodecs/mp_image.h"
173 #include "libmpcodecs/vf.h"
174 #include "libmpcodecs/vd.h"
176 #include "mixer.h"
178 #include "mp_core.h"
179 #include "options.h"
180 #include "defaultopts.h"
182 static const char help_text[]=_(
183 "Usage: mplayer [options] [url|path/]filename\n"
184 "\n"
185 "Basic options: (complete list in the man page)\n"
186 " -vo <drv> select video output driver ('-vo help' for a list)\n"
187 " -ao <drv> select audio output driver ('-ao help' for a list)\n"
188 #ifdef CONFIG_VCD
189 " vcd://<trackno> play (S)VCD (Super Video CD) track (raw device, no mount)\n"
190 #endif
191 #ifdef CONFIG_DVDREAD
192 " dvd://<titleno> play DVD title from device instead of plain file\n"
193 #endif
194 " -alang/-slang select DVD audio/subtitle language (by 2-char country code)\n"
195 " -ss <position> seek to given (seconds or hh:mm:ss) position\n"
196 " -nosound do not play sound\n"
197 " -fs fullscreen playback (or -vm, -zoom, details in the man page)\n"
198 " -x <x> -y <y> set display resolution (for use with -vm or -zoom)\n"
199 " -sub <file> specify subtitle file to use (also see -subfps, -subdelay)\n"
200 " -playlist <file> specify playlist file\n"
201 " -vid x -aid y select video (x) and audio (y) stream to play\n"
202 " -fps x -srate y change video (x fps) and audio (y Hz) rate\n"
203 " -pp <quality> enable postprocessing filter (details in the man page)\n"
204 " -framedrop enable frame dropping (for slow machines)\n"
205 "\n"
206 "Basic keys: (complete list in the man page, also check input.conf)\n"
207 " <- or -> seek backward/forward 10 seconds\n"
208 " down or up seek backward/forward 1 minute\n"
209 " pgdown or pgup seek backward/forward 10 minutes\n"
210 " < or > step backward/forward in playlist\n"
211 " p or SPACE pause movie (press any key to continue)\n"
212 " q or ESC stop playing and quit program\n"
213 " + or - adjust audio delay by +/- 0.1 second\n"
214 " o cycle OSD mode: none / seekbar / seekbar + timer\n"
215 " * or / increase or decrease PCM volume\n"
216 " x or z adjust subtitle delay by +/- 0.1 second\n"
217 " r or t adjust subtitle position up/down, also see -vf expand\n"
218 "\n"
219 " * * * SEE THE MAN PAGE FOR DETAILS, FURTHER (ADVANCED) OPTIONS AND KEYS * * *\n"
220 "\n");
223 #define Exit_SIGILL_RTCpuSel _(\
224 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
225 " It may be a bug in our new runtime CPU-detection code...\n"\
226 " Please read DOCS/HTML/en/bugreports.html.\n")
228 #define Exit_SIGILL _(\
229 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
230 " It usually happens when you run it on a CPU different than the one it was\n"\
231 " compiled/optimized for.\n"\
232 " Verify this!\n")
234 #define Exit_SIGSEGV_SIGFPE _(\
235 "- MPlayer crashed by bad usage of CPU/FPU/RAM.\n"\
236 " Recompile MPlayer with --enable-debug and make a 'gdb' backtrace and\n"\
237 " disassembly. Details in DOCS/HTML/en/bugreports_what.html#bugreports_crash.\n")
239 #define Exit_SIGCRASH _(\
240 "- MPlayer crashed. This shouldn't happen.\n"\
241 " It can be a bug in the MPlayer code _or_ in your drivers _or_ in your\n"\
242 " gcc version. If you think it's MPlayer's fault, please read\n"\
243 " DOCS/HTML/en/bugreports.html and follow the instructions there. We can't and\n"\
244 " won't help unless you provide this information when reporting a possible bug.\n")
246 #define SystemTooSlow _("\n\n"\
247 " ************************************************\n"\
248 " **** Your system is too SLOW to play this! ****\n"\
249 " ************************************************\n\n"\
250 "Possible reasons, problems, workarounds:\n"\
251 "- Most common: broken/buggy _audio_ driver\n"\
252 " - Try -ao sdl or use the OSS emulation of ALSA.\n"\
253 " - Experiment with different values for -autosync, 30 is a good start.\n"\
254 "- Slow video output\n"\
255 " - Try a different -vo driver (-vo help for a list) or try -framedrop!\n"\
256 "- Slow CPU\n"\
257 " - Don't try to play a big DVD/DivX on a slow CPU! Try some of the lavdopts,\n"\
258 " e.g. -vfm ffmpeg -lavdopts lowres=1:fast:skiploopfilter=all.\n"\
259 "- Broken file\n"\
260 " - Try various combinations of -nobps -ni -forceidx -mc 0.\n"\
261 "- Slow media (NFS/SMB mounts, DVD, VCD etc)\n"\
262 " - Try -cache 8192.\n"\
263 "- Are you using -cache to play a non-interleaved AVI file?\n"\
264 " - Try -nocache.\n"\
265 "Read DOCS/HTML/en/video.html for tuning/speedup tips.\n"\
266 "If none of this helps you, read DOCS/HTML/en/bugreports.html.\n\n")
269 //**************************************************************************//
270 //**************************************************************************//
272 #include "mp_fifo.h"
274 // benchmark:
275 double video_time_usage=0;
276 double vout_time_usage=0;
277 static double audio_time_usage=0;
278 static int total_time_usage_start=0;
279 static int total_frame_cnt=0;
280 static int drop_frame_cnt=0; // total number of dropped frames
282 // options:
283 static int output_quality=0;
285 // seek:
286 static double seek_to_sec;
287 static off_t seek_to_byte=0;
288 static off_t step_sec=0;
290 static m_time_size_t end_at = { .type = END_AT_NONE, .pos = 0 };
292 // codecs:
293 char **audio_codec_list=NULL; // override audio codec
294 char **video_codec_list=NULL; // override video codec
295 char **audio_fm_list=NULL; // override audio codec family
296 char **video_fm_list=NULL; // override video codec family
298 // this dvdsub_id was selected via slang
299 // use this to allow dvdnav to follow -slang across stream resets,
300 // in particular the subtitle ID for a language changes
301 int dvdsub_lang_id;
302 int vobsub_id=-1;
303 static char* spudec_ifo=NULL;
304 int forced_subs_only=0;
305 int file_filter=1;
307 // cache2:
308 int stream_cache_size=-1;
310 // dump:
311 int stream_dump_type=0;
313 // A-V sync:
314 static float default_max_pts_correction=-1;//0.01f;
315 float audio_delay=0;
316 static int ignore_start=0;
318 double force_fps=0;
319 static int force_srate=0;
320 int frame_dropping=0; // option 0=no drop 1= drop vo 2= drop decode
321 static int play_n_frames=-1;
322 static int play_n_frames_mf=-1;
324 // sub:
325 char *font_name=NULL;
326 char *sub_font_name=NULL;
327 extern int font_fontconfig;
328 float font_factor=0.75;
329 char **sub_name=NULL;
330 float sub_delay=0;
331 float sub_fps=0;
332 int sub_auto = 1;
333 char *vobsub_name=NULL;
334 int subcc_enabled=0;
335 int suboverlap_enabled = 1;
337 #include "ass_mp.h"
338 #ifdef CONFIG_ASS
339 ASS_Track *ass_track = 0; // current track to render
340 #endif
342 char* current_module=NULL; // for debugging
345 // ---
347 #ifdef CONFIG_MENU
348 #include "m_struct.h"
349 #include "libmenu/menu.h"
350 static const vf_info_t* const libmenu_vfs[] = {
351 &vf_info_menu,
352 NULL
354 static vf_instance_t* vf_menu = NULL;
355 int use_menu = 0;
356 static char* menu_cfg = NULL;
357 static char* menu_root = "main";
358 #endif
361 edl_record_ptr edl_records = NULL; ///< EDL entries memory area
362 edl_record_ptr next_edl_record = NULL; ///< only for traversing edl_records
363 FILE* edl_fd = NULL; ///< fd to write to when in -edlout mode.
364 int use_filedir_conf;
365 int use_filename_title;
367 #include "mpcommon.h"
368 #include "command.h"
370 #include "metadata.h"
372 const void *mpctx_get_video_out(MPContext *mpctx)
374 return mpctx->video_out;
377 const void *mpctx_get_audio_out(MPContext *mpctx)
379 return mpctx->audio_out;
382 void *mpctx_get_demuxer(MPContext *mpctx)
384 return mpctx->demuxer;
387 void *mpctx_get_playtree_iter(MPContext *mpctx)
389 return mpctx->playtree_iter;
392 void *mpctx_get_mixer(MPContext *mpctx)
394 return &mpctx->mixer;
397 int mpctx_get_global_sub_size(MPContext *mpctx)
399 return mpctx->global_sub_size;
402 int mpctx_get_osd_function(MPContext *mpctx)
404 return mpctx->osd_function;
407 static float get_relative_time(struct MPContext *mpctx)
409 unsigned int new_time = GetTimer();
410 unsigned int delta = new_time - mpctx->last_time;
411 mpctx->last_time = new_time;
412 return delta * 0.000001;
415 static int is_valid_metadata_type(struct MPContext *mpctx, metadata_t type) {
416 switch (type)
418 /* check for valid video stream */
419 case META_VIDEO_CODEC:
420 case META_VIDEO_BITRATE:
421 case META_VIDEO_RESOLUTION:
423 if (!mpctx->sh_video)
424 return 0;
425 break;
428 /* check for valid audio stream */
429 case META_AUDIO_CODEC:
430 case META_AUDIO_BITRATE:
431 case META_AUDIO_SAMPLES:
433 if (!mpctx->sh_audio)
434 return 0;
435 break;
438 /* check for valid demuxer */
439 case META_INFO_TITLE:
440 case META_INFO_ARTIST:
441 case META_INFO_ALBUM:
442 case META_INFO_YEAR:
443 case META_INFO_COMMENT:
444 case META_INFO_TRACK:
445 case META_INFO_GENRE:
447 if (!mpctx->demuxer)
448 return 0;
449 break;
452 default:
453 break;
456 return 1;
459 static char *get_demuxer_info(struct MPContext *mpctx, char *tag) {
460 char **info = mpctx->demuxer->info;
461 int n;
463 if (!info || !tag)
464 return talloc_strdup(NULL, "");
466 for (n = 0; info[2*n] != NULL ; n++)
467 if (!strcasecmp (info[2*n], tag))
468 break;
470 return talloc_strdup(NULL, info[2*n+1] ? info[2*n+1] : "");
473 char *get_metadata(struct MPContext *mpctx, metadata_t type)
475 sh_audio_t * const sh_audio = mpctx->sh_audio;
476 sh_video_t * const sh_video = mpctx->sh_video;
478 if (!is_valid_metadata_type(mpctx, type))
479 return NULL;
481 switch (type) {
482 case META_NAME:
483 return talloc_strdup(NULL, mp_basename(mpctx->filename));
484 case META_VIDEO_CODEC:
485 if (sh_video->format == 0x10000001)
486 return talloc_strdup(NULL, "mpeg1");
487 else if (sh_video->format == 0x10000002)
488 return talloc_strdup(NULL, "mpeg2");
489 else if (sh_video->format == 0x10000004)
490 return talloc_strdup(NULL, "mpeg4");
491 else if (sh_video->format == 0x10000005)
492 return talloc_strdup(NULL, "h264");
493 else if (sh_video->format >= 0x20202020)
494 return talloc_asprintf(NULL, "%.4s", (char *) &sh_video->format);
495 else
496 return talloc_asprintf(NULL, "0x%08X", sh_video->format);
497 case META_VIDEO_BITRATE:
498 return talloc_asprintf(NULL, "%d kbps",
499 (int) (sh_video->i_bps * 8 / 1024));
500 case META_VIDEO_RESOLUTION:
501 return talloc_asprintf(NULL, "%d x %d", sh_video->disp_w,
502 sh_video->disp_h);
503 case META_AUDIO_CODEC:
504 if (sh_audio->codec && sh_audio->codec->name)
505 return talloc_strdup(NULL, sh_audio->codec->name);
506 return talloc_strdup(NULL, "");
507 case META_AUDIO_BITRATE:
508 return talloc_asprintf(NULL, "%d kbps",
509 (int) (sh_audio->i_bps * 8/1000));
510 case META_AUDIO_SAMPLES:
511 return talloc_asprintf(NULL, "%d Hz, %d ch.", sh_audio->samplerate,
512 sh_audio->channels);
514 /* check for valid demuxer */
515 case META_INFO_TITLE:
516 return get_demuxer_info(mpctx, "Title");
518 case META_INFO_ARTIST:
519 return get_demuxer_info(mpctx, "Artist");
521 case META_INFO_ALBUM:
522 return get_demuxer_info(mpctx, "Album");
524 case META_INFO_YEAR:
525 return get_demuxer_info(mpctx, "Year");
527 case META_INFO_COMMENT:
528 return get_demuxer_info(mpctx, "Comment");
530 case META_INFO_TRACK:
531 return get_demuxer_info(mpctx, "Track");
533 case META_INFO_GENRE:
534 return get_demuxer_info(mpctx, "Genre");
536 default:
537 break;
540 return talloc_strdup(NULL, "");
543 static void print_file_properties(struct MPContext *mpctx, const char *filename)
545 double start_pts = MP_NOPTS_VALUE;
546 double video_start_pts = MP_NOPTS_VALUE;
547 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_FILENAME=%s\n",
548 filename_recode(filename));
549 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_DEMUXER=%s\n", mpctx->demuxer->desc->name);
550 if (mpctx->sh_video) {
551 /* Assume FOURCC if all bytes >= 0x20 (' ') */
552 if (mpctx->sh_video->format >= 0x20202020)
553 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=%.4s\n", (char *)&mpctx->sh_video->format);
554 else
555 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FORMAT=0x%08X\n", mpctx->sh_video->format);
556 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_BITRATE=%d\n", mpctx->sh_video->i_bps*8);
557 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_WIDTH=%d\n", mpctx->sh_video->disp_w);
558 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_HEIGHT=%d\n", mpctx->sh_video->disp_h);
559 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_FPS=%5.3f\n", mpctx->sh_video->fps);
560 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_VIDEO_ASPECT=%1.4f\n", mpctx->sh_video->aspect);
561 video_start_pts = ds_get_next_pts(mpctx->d_video);
563 if (mpctx->sh_audio) {
564 /* Assume FOURCC if all bytes >= 0x20 (' ') */
565 if (mpctx->sh_audio->format >= 0x20202020)
566 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_FORMAT=%.4s\n", (char *)&mpctx->sh_audio->format);
567 else
568 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_FORMAT=%d\n", mpctx->sh_audio->format);
569 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_BITRATE=%d\n", mpctx->sh_audio->i_bps*8);
570 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_RATE=%d\n", mpctx->sh_audio->samplerate);
571 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_NCH=%d\n", mpctx->sh_audio->channels);
572 start_pts = ds_get_next_pts(mpctx->d_audio);
574 if (video_start_pts != MP_NOPTS_VALUE) {
575 if (start_pts == MP_NOPTS_VALUE || !mpctx->sh_audio ||
576 (mpctx->sh_video && video_start_pts < start_pts))
577 start_pts = video_start_pts;
579 if (start_pts != MP_NOPTS_VALUE)
580 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_START_TIME=%.2f\n", start_pts);
581 else
582 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_START_TIME=unknown\n");
583 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_LENGTH=%.2f\n", get_time_length(mpctx));
584 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_SEEKABLE=%d\n",
585 mpctx->stream->seek && (!mpctx->demuxer || mpctx->demuxer->seekable));
586 if (mpctx->demuxer) {
587 if (mpctx->demuxer->num_chapters == 0)
588 stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_NUM_CHAPTERS, &mpctx->demuxer->num_chapters);
589 mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_CHAPTERS=%d\n", mpctx->demuxer->num_chapters);
593 /// step size of mixer changes
594 int volstep = 3;
596 #ifdef CONFIG_DVDNAV
597 static void mp_dvdnav_context_free(MPContext *ctx){
598 if (ctx->nav_smpi) free_mp_image(ctx->nav_smpi);
599 ctx->nav_smpi = NULL;
600 free(ctx->nav_buffer);
601 ctx->nav_buffer = NULL;
602 ctx->nav_start = NULL;
603 ctx->nav_in_size = 0;
605 #endif
607 void uninit_player(struct MPContext *mpctx, unsigned int mask){
608 mask &= mpctx->initialized_flags;
610 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n*** uninit(0x%X)\n",mask);
612 if(mask&INITIALIZED_ACODEC){
613 mpctx->initialized_flags&=~INITIALIZED_ACODEC;
614 current_module="uninit_acodec";
615 if(mpctx->sh_audio) uninit_audio(mpctx->sh_audio);
616 mpctx->sh_audio=NULL;
617 mpctx->mixer.afilter = NULL;
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 free_stream(mpctx->sources[i].stream);
637 free_demuxer(mpctx->sources[i].demuxer);
640 talloc_free(mpctx->sources);
641 mpctx->sources = NULL;
642 mpctx->num_sources = 0;
643 talloc_free(mpctx->timeline);
644 mpctx->timeline = NULL;
645 mpctx->num_timeline_parts = 0;
646 talloc_free(mpctx->chapters);
647 mpctx->chapters = NULL;
648 mpctx->num_chapters = 0;
649 mpctx->video_offset = 0;
650 if(mpctx->demuxer){
651 mpctx->stream=mpctx->demuxer->stream;
652 free_demuxer(mpctx->demuxer);
654 mpctx->demuxer=NULL;
657 // kill the cache process:
658 if(mask&INITIALIZED_STREAM){
659 mpctx->initialized_flags&=~INITIALIZED_STREAM;
660 current_module="uninit_stream";
661 if(mpctx->stream) free_stream(mpctx->stream);
662 mpctx->stream=NULL;
665 if(mask&INITIALIZED_VO){
666 mpctx->initialized_flags&=~INITIALIZED_VO;
667 current_module="uninit_vo";
668 vo_destroy(mpctx->video_out);
669 mpctx->video_out=NULL;
670 #ifdef CONFIG_DVDNAV
671 mp_dvdnav_context_free(mpctx);
672 #endif
675 // Must be after libvo uninit, as few vo drivers (svgalib) have tty code.
676 if(mask&INITIALIZED_GETCH2){
677 mpctx->initialized_flags&=~INITIALIZED_GETCH2;
678 current_module="uninit_getch2";
679 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[uninit getch2]]]\n");
680 // restore terminal:
681 getch2_disable();
684 if(mask&INITIALIZED_VOBSUB){
685 mpctx->initialized_flags&=~INITIALIZED_VOBSUB;
686 current_module="uninit_vobsub";
687 if(vo_vobsub) vobsub_close(vo_vobsub);
688 vo_vobsub=NULL;
691 if (mask&INITIALIZED_SPUDEC){
692 mpctx->initialized_flags&=~INITIALIZED_SPUDEC;
693 current_module="uninit_spudec";
694 spudec_free(vo_spudec);
695 vo_spudec=NULL;
698 if(mask&INITIALIZED_AO){
699 mpctx->initialized_flags&=~INITIALIZED_AO;
700 current_module="uninit_ao";
701 if (mpctx->edl_muted) mixer_mute(&mpctx->mixer);
702 if (mpctx->audio_out)
703 mpctx->audio_out->uninit(mpctx->stop_play != AT_END_OF_FILE);
704 mpctx->audio_out=NULL;
707 current_module=NULL;
710 void exit_player_with_rc(struct MPContext *mpctx, enum exit_reason how, int rc)
712 if (mpctx->user_muted && !mpctx->edl_muted) mixer_mute(&mpctx->mixer);
713 uninit_player(mpctx, INITIALIZED_ALL);
714 #if defined(__MINGW32__) || defined(__CYGWIN__)
715 timeEndPeriod(1);
716 #endif
717 #ifdef CONFIG_X11
718 vo_uninit(mpctx->x11_state); // Close the X11 connection (if any is open).
719 #endif
721 current_module="uninit_input";
722 mp_input_uninit(mpctx->input);
723 #ifdef CONFIG_MENU
724 if (use_menu)
725 menu_uninit();
726 #endif
728 #ifdef CONFIG_FREETYPE
729 current_module="uninit_font";
730 if (mpctx->osd && mpctx->osd->sub_font != vo_font)
731 free_font_desc(mpctx->osd->sub_font);
732 free_font_desc(vo_font);
733 vo_font = NULL;
734 done_freetype();
735 #endif
736 osd_free(mpctx->osd);
738 #ifdef CONFIG_ASS
739 ass_library_done(ass_library);
740 ass_library = NULL;
741 #endif
743 current_module="exit_player";
745 // free mplayer config
746 if(mpctx->mconfig)
747 m_config_free(mpctx->mconfig);
748 mpctx->mconfig = NULL;
750 if(mpctx->playtree_iter)
751 play_tree_iter_free(mpctx->playtree_iter);
752 mpctx->playtree_iter = NULL;
753 if(mpctx->playtree)
754 play_tree_free(mpctx->playtree, 1);
755 mpctx->playtree = NULL;
757 talloc_free(mpctx->key_fifo);
759 free(edl_records); // free mem allocated for EDL
760 edl_records = NULL;
761 switch(how) {
762 case EXIT_QUIT:
763 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Quit");
764 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=QUIT\n");
765 break;
766 case EXIT_EOF:
767 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","End of file");
768 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=EOF\n");
769 break;
770 case EXIT_ERROR:
771 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nExiting... (%s)\n","Fatal error");
772 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=ERROR\n");
773 break;
774 default:
775 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=NONE\n");
777 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"max framesize was %d bytes\n",max_framesize);
779 exit(rc);
782 static void exit_player(struct MPContext *mpctx, enum exit_reason how)
784 exit_player_with_rc(mpctx, how, 1);
787 #ifndef __MINGW32__
788 static void child_sighandler(int x){
789 pid_t pid;
790 while((pid=waitpid(-1,NULL,WNOHANG)) > 0);
792 #endif
794 #ifdef CONFIG_CRASH_DEBUG
795 static char *prog_path;
796 static int crash_debug = 0;
797 #endif
799 static void exit_sighandler(int x){
800 static int sig_count=0;
801 #ifdef CONFIG_CRASH_DEBUG
802 if (!crash_debug || x != SIGTRAP)
803 #endif
804 ++sig_count;
805 if(sig_count==5)
807 /* We're crashing bad and can't uninit cleanly :(
808 * by popular request, we make one last (dirty)
809 * effort to restore the user's
810 * terminal. */
811 getch2_disable();
812 exit(1);
814 if(sig_count==6) exit(1);
815 if(sig_count>6){
816 // can't stop :(
817 #ifndef __MINGW32__
818 kill(getpid(),SIGKILL);
819 #endif
821 mp_msg(MSGT_CPLAYER, MSGL_FATAL, "\n");
822 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,
823 "\nMPlayer interrupted by signal %d in module: %s\n", x,
824 current_module ? current_module : "unknown");
825 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SIGNAL=%d\n", x);
826 if(sig_count<=1)
827 switch(x){
828 case SIGINT:
829 case SIGPIPE:
830 case SIGQUIT:
831 case SIGTERM:
832 case SIGKILL:
833 async_quit_request = 1;
834 return; // killed from keyboard (^C) or killed [-9]
835 case SIGILL:
836 #if CONFIG_RUNTIME_CPUDETECT
837 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL_RTCpuSel);
838 #else
839 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGILL);
840 #endif
841 case SIGFPE:
842 case SIGSEGV:
843 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGSEGV_SIGFPE);
844 default:
845 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,Exit_SIGCRASH);
846 #ifdef CONFIG_CRASH_DEBUG
847 if (crash_debug) {
848 int gdb_pid;
849 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forking...\n");
850 gdb_pid = fork();
851 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forked...\n");
852 if (gdb_pid == 0) { // We are the child
853 char spid[20];
854 snprintf(spid, sizeof(spid), "%i", getppid());
855 getch2_disable(); // allow terminal to work properly with gdb
856 if (execlp("gdb", "gdb", prog_path, spid, "-ex", "bt", NULL) == -1)
857 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't start gdb\n");
858 } else if (gdb_pid < 0)
859 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't fork\n");
860 else {
861 waitpid(gdb_pid, NULL, 0);
863 if (x == SIGTRAP) return;
865 #endif
867 getch2_disable();
868 exit(1);
871 #include "cfg-mplayer.h"
873 static int cfg_include(m_option_t *conf, char *filename)
875 return m_config_parse_config_file(conf->priv, filename);
878 static void parse_cfgfiles(struct MPContext *mpctx, m_config_t* conf)
880 struct MPOpts *opts = &mpctx->opts;
881 char *conffile;
882 int conffile_fd;
883 if (!(opts->noconfig & 2) &&
884 m_config_parse_config_file(conf, MPLAYER_CONFDIR "/mplayer.conf") < 0)
885 exit_player(mpctx, EXIT_NONE);
886 if ((conffile = get_path("")) == NULL) {
887 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"Cannot find HOME directory.\n");
888 } else {
889 #ifdef __MINGW32__
890 mkdir(conffile);
891 #else
892 mkdir(conffile, 0777);
893 #endif
894 free(conffile);
895 if ((conffile = get_path("config")) == NULL) {
896 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"get_path(\"config\") problem\n");
897 } else {
898 if ((conffile_fd = open(conffile, O_CREAT | O_EXCL | O_WRONLY, 0666)) != -1) {
899 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Creating config file: %s\n", conffile);
900 write(conffile_fd, default_config, strlen(default_config));
901 close(conffile_fd);
903 if (!(opts->noconfig & 1) &&
904 m_config_parse_config_file(conf, conffile) < 0)
905 exit_player(mpctx, EXIT_NONE);
906 free(conffile);
911 #define PROFILE_CFG_PROTOCOL "protocol."
913 static void load_per_protocol_config (m_config_t* conf, const char *const file)
915 char *str;
916 char protocol[strlen (PROFILE_CFG_PROTOCOL) + strlen (file) + 1];
917 m_profile_t *p;
919 /* does filename actually uses a protocol ? */
920 str = strstr (file, "://");
921 if (!str)
922 return;
924 sprintf (protocol, "%s%s", PROFILE_CFG_PROTOCOL, file);
925 protocol[strlen (PROFILE_CFG_PROTOCOL)+strlen(file)-strlen(str)] = '\0';
926 p = m_config_get_profile (conf, protocol);
927 if (p)
929 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading protocol-related profile '%s'\n", protocol);
930 m_config_set_profile(conf,p);
934 #define PROFILE_CFG_EXTENSION "extension."
936 static void load_per_extension_config (m_config_t* conf, const char *const file)
938 char *str;
939 char extension[strlen (PROFILE_CFG_EXTENSION) + 8];
940 m_profile_t *p;
942 /* does filename actually have an extension ? */
943 str = strrchr (file, '.');
944 if (!str)
945 return;
947 sprintf (extension, PROFILE_CFG_EXTENSION);
948 strncat (extension, ++str, 7);
949 p = m_config_get_profile (conf, extension);
950 if (p)
952 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", extension);
953 m_config_set_profile(conf,p);
957 #define PROFILE_CFG_VO "vo."
958 #define PROFILE_CFG_AO "ao."
960 static void load_per_output_config (m_config_t* conf, char *cfg, char *out)
962 char profile[strlen (cfg) + strlen (out) + 1];
963 m_profile_t *p;
965 sprintf (profile, "%s%s", cfg, out);
966 p = m_config_get_profile (conf, profile);
967 if (p)
969 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Loading extension-related profile '%s'\n", profile);
970 m_config_set_profile(conf,p);
975 * Tries to load a config file
976 * @return 0 if file was not found, 1 otherwise
978 static int try_load_config(m_config_t *conf, const char *file)
980 struct stat st;
981 if (stat(file, &st))
982 return 0;
983 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Loading config '%s'\n", file);
984 m_config_parse_config_file (conf, file);
985 return 1;
988 static void load_per_file_config (m_config_t* conf, const char *const file)
990 char *confpath;
991 char cfg[PATH_MAX];
992 const char *name;
994 if (strlen(file) > PATH_MAX - 14) {
995 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Filename is too long, can not load file or directory specific config files\n");
996 return;
998 sprintf (cfg, "%s.conf", file);
1000 name = mp_basename(cfg);
1001 if (use_filedir_conf) {
1002 char dircfg[PATH_MAX];
1003 strcpy(dircfg, cfg);
1004 strcpy(dircfg + (name - cfg), "mplayer.conf");
1005 try_load_config(conf, dircfg);
1007 if (try_load_config(conf, cfg))
1008 return;
1011 if ((confpath = get_path (name)) != NULL)
1013 try_load_config(conf, confpath);
1015 free (confpath);
1019 /* When libmpdemux performs a blocking operation (network connection or
1020 * cache filling) if the operation fails we use this function to check
1021 * if it was interrupted by the user.
1022 * The function returns a new value for eof. */
1023 static int libmpdemux_was_interrupted(struct MPContext *mpctx, int stop_play)
1025 mp_cmd_t* cmd;
1026 if((cmd = mp_input_get_cmd(mpctx->input, 0, 0)) != NULL) {
1027 switch(cmd->id) {
1028 case MP_CMD_QUIT:
1029 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
1030 case MP_CMD_PLAY_TREE_STEP: {
1031 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_ENTRY : PT_PREV_ENTRY;
1032 mpctx->play_tree_step = (cmd->args[0].v.i == 0) ? 1 : cmd->args[0].v.i;
1033 } break;
1034 case MP_CMD_PLAY_TREE_UP_STEP: {
1035 stop_play = (cmd->args[0].v.i > 0) ? PT_UP_NEXT : PT_UP_PREV;
1036 } break;
1037 case MP_CMD_PLAY_ALT_SRC_STEP: {
1038 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_SRC : PT_PREV_SRC;
1039 } break;
1041 mp_cmd_free(cmd);
1043 return stop_play;
1046 static int playtree_add_playlist(struct MPContext *mpctx, play_tree_t* entry)
1048 play_tree_add_bpf(entry,mpctx->filename);
1051 if(!entry) {
1052 entry = mpctx->playtree_iter->tree;
1053 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1054 return PT_NEXT_ENTRY;
1056 if(mpctx->playtree_iter->tree == entry ) { // Loop with a single file
1057 if(play_tree_iter_up_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1058 return PT_NEXT_ENTRY;
1061 play_tree_remove(entry,1,1);
1062 return PT_NEXT_SRC;
1064 play_tree_insert_entry(mpctx->playtree_iter->tree,entry);
1065 play_tree_set_params_from(entry,mpctx->playtree_iter->tree);
1066 entry = mpctx->playtree_iter->tree;
1067 if(play_tree_iter_step(mpctx->playtree_iter,1,0) != PLAY_TREE_ITER_ENTRY) {
1068 return PT_NEXT_ENTRY;
1070 play_tree_remove(entry,1,1);
1072 return PT_NEXT_SRC;
1075 void add_subtitles(struct MPContext *mpctx, char *filename, float fps, int noerr)
1077 struct MPOpts *opts = &mpctx->opts;
1078 sub_data *subd = NULL;
1079 struct ass_track *asst = NULL;
1081 if (filename == NULL || mpctx->set_of_sub_size >= MAX_SUBTITLE_FILES) {
1082 return;
1085 #ifdef CONFIG_ASS
1086 if (opts->ass_enabled) {
1087 #ifdef CONFIG_ICONV
1088 asst = ass_read_stream(ass_library, filename, sub_cp);
1089 #else
1090 asst = ass_read_stream(ass_library, filename, 0);
1091 #endif
1092 if (!asst) {
1093 subd = sub_read_file(filename, fps);
1094 if (subd) {
1095 asst = ass_read_subdata(ass_library, subd, fps);
1096 if (asst) {
1097 sub_free(subd);
1098 subd = NULL;
1102 } else
1103 #endif
1104 subd = sub_read_file(filename, fps);
1107 if (!asst && !subd) {
1108 mp_tmsg(MSGT_CPLAYER, noerr ? MSGL_WARN : MSGL_ERR,
1109 "Cannot load subtitles: %s\n", filename_recode(filename));
1110 return;
1113 mpctx->set_of_ass_tracks[mpctx->set_of_sub_size] = asst;
1114 mpctx->set_of_subtitles[mpctx->set_of_sub_size] = subd;
1115 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_ID=%d\n", mpctx->set_of_sub_size);
1116 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_FILENAME=%s\n",
1117 filename_recode(filename));
1118 ++mpctx->set_of_sub_size;
1119 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "SUB: Added subtitle file (%d): %s\n", mpctx->set_of_sub_size,
1120 filename_recode(filename));
1123 void init_vo_spudec(struct MPContext *mpctx)
1125 spudec_free(vo_spudec);
1126 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
1127 vo_spudec = NULL;
1129 // we currently can't work without video stream
1130 if (!mpctx->sh_video)
1131 return;
1133 if (spudec_ifo) {
1134 unsigned int palette[16], width, height;
1135 current_module="spudec_init_vobsub";
1136 if (vobsub_parse_ifo(NULL,spudec_ifo, palette, &width, &height, 1, -1, NULL) >= 0)
1137 vo_spudec=spudec_new_scaled(palette, width, height, NULL, 0);
1140 #ifdef CONFIG_DVDREAD
1141 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVD) {
1142 current_module="spudec_init_dvdread";
1143 vo_spudec=spudec_new_scaled(((dvd_priv_t *)(mpctx->stream->priv))->cur_pgc->palette,
1144 mpctx->sh_video->disp_w, mpctx->sh_video->disp_h,
1145 NULL, 0);
1147 #endif
1149 #ifdef CONFIG_DVDNAV
1150 if (vo_spudec==NULL && mpctx->stream->type==STREAMTYPE_DVDNAV) {
1151 unsigned int *palette = mp_dvdnav_get_spu_clut(mpctx->stream);
1152 current_module="spudec_init_dvdnav";
1153 vo_spudec=spudec_new_scaled(palette, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, NULL, 0);
1155 #endif
1157 if (vo_spudec==NULL) {
1158 sh_sub_t *sh = mpctx->d_sub->sh;
1159 current_module="spudec_init_normal";
1160 vo_spudec=spudec_new_scaled(NULL, mpctx->sh_video->disp_w, mpctx->sh_video->disp_h, sh->extradata, sh->extradata_len);
1161 spudec_set_font_factor(vo_spudec,font_factor);
1164 if (vo_spudec!=NULL) {
1165 mpctx->initialized_flags|=INITIALIZED_SPUDEC;
1166 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
1171 * In Mac OS X the SDL-lib is built upon Cocoa. The easiest way to
1172 * make it all work is to use the builtin SDL-bootstrap code, which
1173 * will be done automatically by replacing our main() if we include SDL.h.
1175 #if defined(__APPLE__) && defined(CONFIG_SDL)
1176 #ifdef CONFIG_SDL_SDL_H
1177 #include <SDL/SDL.h>
1178 #else
1179 #include <SDL.h>
1180 #endif
1181 #endif
1184 * \brief append a formatted string
1185 * \param buf buffer to print into
1186 * \param pos position of terminating 0 in buf
1187 * \param len maximum number of characters in buf, not including terminating 0
1188 * \param format printf format string
1190 static void saddf(char *buf, unsigned *pos, int len, const char *format, ...)
1192 va_list va;
1193 va_start(va, format);
1194 *pos += vsnprintf(&buf[*pos], len - *pos, format, va);
1195 va_end(va);
1196 if (*pos >= len ) {
1197 buf[len] = 0;
1198 *pos = len;
1203 * \brief append time in the hh:mm:ss.f format
1204 * \param buf buffer to print into
1205 * \param pos position of terminating 0 in buf
1206 * \param len maximum number of characters in buf, not including terminating 0
1207 * \param time time value to convert/append
1209 static void sadd_hhmmssf(char *buf, unsigned *pos, int len, float time) {
1210 int64_t tenths = 10 * time;
1211 int f1 = tenths % 10;
1212 int ss = (tenths / 10) % 60;
1213 int mm = (tenths / 600) % 60;
1214 int hh = tenths / 36000;
1215 if (time <= 0) {
1216 saddf(buf, pos, len, "unknown");
1217 return;
1219 if (hh > 0)
1220 saddf(buf, pos, len, "%2d:", hh);
1221 if (hh > 0 || mm > 0)
1222 saddf(buf, pos, len, "%02d:", mm);
1223 saddf(buf, pos, len, "%02d.%1d", ss, f1);
1226 static void print_status(struct MPContext *mpctx, double a_pos, bool at_frame)
1228 struct MPOpts *opts = &mpctx->opts;
1229 sh_video_t * const sh_video = mpctx->sh_video;
1231 if (mpctx->sh_audio && a_pos == MP_NOPTS_VALUE)
1232 a_pos = playing_audio_pts(mpctx);
1233 if (mpctx->sh_audio && sh_video && at_frame) {
1234 mpctx->last_av_difference = a_pos - mpctx->video_pts - audio_delay;
1235 if (mpctx->time_frame > 0)
1236 mpctx->last_av_difference += mpctx->time_frame * opts->playback_speed;
1237 if (mpctx->last_av_difference > 0.5 && drop_frame_cnt > 50
1238 && !mpctx->drop_message_shown) {
1239 mp_tmsg(MSGT_AVSYNC,MSGL_WARN,SystemTooSlow);
1240 mpctx->drop_message_shown = true;
1243 if (opts->quiet)
1244 return;
1247 int width;
1248 char *line;
1249 unsigned pos = 0;
1250 get_screen_size();
1251 if (screen_width > 0)
1252 width = screen_width;
1253 else
1254 width = 80;
1255 #if defined(__MINGW32__) || defined(__CYGWIN__) || defined(__OS2__)
1256 /* Windows command line is broken (MinGW's rxvt works, but we
1257 * should not depend on that). */
1258 width--;
1259 #endif
1260 line = malloc(width + 1); // one additional char for the terminating null
1262 // Audio time
1263 if (mpctx->sh_audio) {
1264 saddf(line, &pos, width, "A:%6.1f ", a_pos);
1265 if (!sh_video) {
1266 float len = get_time_length(mpctx);
1267 saddf(line, &pos, width, "(");
1268 sadd_hhmmssf(line, &pos, width, a_pos);
1269 saddf(line, &pos, width, ") of %.1f (", len);
1270 sadd_hhmmssf(line, &pos, width, len);
1271 saddf(line, &pos, width, ") ");
1275 // Video time
1276 if (sh_video)
1277 saddf(line, &pos, width, "V:%6.1f ", mpctx->video_pts);
1279 // A-V sync
1280 if (mpctx->sh_audio && sh_video)
1281 saddf(line, &pos, width, "A-V:%7.3f ct:%7.3f ",
1282 mpctx->last_av_difference, mpctx->total_avsync_change);
1284 // Video stats
1285 if (sh_video)
1286 saddf(line, &pos, width, "%3d/%3d ",
1287 (int)sh_video->num_frames,
1288 (int)sh_video->num_frames_decoded);
1290 // CPU usage
1291 if (sh_video) {
1292 if (sh_video->timer > 0.5)
1293 saddf(line, &pos, width, "%2d%% %2d%% %4.1f%% ",
1294 (int)(100.0*video_time_usage*opts->playback_speed/(double)sh_video->timer),
1295 (int)(100.0*vout_time_usage*opts->playback_speed/(double)sh_video->timer),
1296 (100.0*audio_time_usage*opts->playback_speed/(double)sh_video->timer));
1297 else
1298 saddf(line, &pos, width, "??%% ??%% ??,?%% ");
1299 } else if (mpctx->sh_audio) {
1300 if (mpctx->delay > 0.5)
1301 saddf(line, &pos, width, "%4.1f%% ",
1302 100.0*audio_time_usage/(double)mpctx->delay);
1303 else
1304 saddf(line, &pos, width, "??,?%% ");
1307 // VO stats
1308 if (sh_video)
1309 saddf(line, &pos, width, "%d %d ", drop_frame_cnt, output_quality);
1311 #ifdef CONFIG_STREAM_CACHE
1312 // cache stats
1313 if (stream_cache_size > 0)
1314 saddf(line, &pos, width, "%d%% ", cache_fill_status);
1315 #endif
1317 // other
1318 if (opts->playback_speed != 1)
1319 saddf(line, &pos, width, "%4.2fx ", opts->playback_speed);
1321 // end
1322 if (erase_to_end_of_line) {
1323 line[pos] = 0;
1324 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s%s\r", line, erase_to_end_of_line);
1325 } else {
1326 memset(&line[pos], ' ', width - pos);
1327 line[width] = 0;
1328 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s\r", line);
1330 free(line);
1334 * \brief build a chain of audio filters that converts the input format
1335 * to the ao's format, taking into account the current playback_speed.
1336 * \param sh_audio describes the requested input format of the chain.
1337 * \param ao_data describes the requested output format of the chain.
1339 static int build_afilter_chain(struct MPContext *mpctx, sh_audio_t *sh_audio,
1340 ao_data_t *ao_data)
1342 struct MPOpts *opts = &mpctx->opts;
1343 int new_srate;
1344 int result;
1345 if (!sh_audio)
1347 mpctx->mixer.afilter = NULL;
1348 return 0;
1350 if(af_control_any_rev(sh_audio->afilter,
1351 AF_CONTROL_PLAYBACK_SPEED | AF_CONTROL_SET,
1352 &opts->playback_speed)) {
1353 new_srate = sh_audio->samplerate;
1354 } else {
1355 new_srate = sh_audio->samplerate * opts->playback_speed;
1356 if (new_srate != ao_data->samplerate) {
1357 // limits are taken from libaf/af_resample.c
1358 if (new_srate < 8000)
1359 new_srate = 8000;
1360 if (new_srate > 192000)
1361 new_srate = 192000;
1362 opts->playback_speed = (float)new_srate / (float)sh_audio->samplerate;
1365 result = init_audio_filters(sh_audio, new_srate,
1366 &ao_data->samplerate, &ao_data->channels, &ao_data->format);
1367 mpctx->mixer.afilter = sh_audio->afilter;
1368 return result;
1372 typedef struct mp_osd_msg mp_osd_msg_t;
1373 struct mp_osd_msg {
1374 /// Previous message on the stack.
1375 mp_osd_msg_t* prev;
1376 /// Message text.
1377 char msg[128];
1378 int id,level,started;
1379 /// Display duration in ms.
1380 unsigned time;
1383 /// OSD message stack.
1384 static mp_osd_msg_t* osd_msg_stack = NULL;
1387 * \brief Add a message on the OSD message stack
1389 * If a message with the same id is already present in the stack
1390 * it is pulled on top of the stack, otherwise a new message is created.
1393 static void set_osd_msg_va(int id, int level, int time, const char *fmt,
1394 va_list ap)
1396 mp_osd_msg_t *msg,*last=NULL;
1397 int r;
1399 // look if the id is already in the stack
1400 for(msg = osd_msg_stack ; msg && msg->id != id ;
1401 last = msg, msg = msg->prev);
1402 // not found: alloc it
1403 if(!msg) {
1404 msg = calloc(1,sizeof(mp_osd_msg_t));
1405 msg->prev = osd_msg_stack;
1406 osd_msg_stack = msg;
1407 } else if(last) { // found, but it's not on top of the stack
1408 last->prev = msg->prev;
1409 msg->prev = osd_msg_stack;
1410 osd_msg_stack = msg;
1412 // write the msg
1413 r = vsnprintf(msg->msg, 128, fmt, ap);
1414 if(r >= 128) msg->msg[127] = 0;
1415 // set id and time
1416 msg->id = id;
1417 msg->level = level;
1418 msg->time = time;
1422 void set_osd_msg(int id, int level, int time, const char *fmt, ...)
1424 va_list ap;
1425 va_start(ap, fmt);
1426 set_osd_msg_va(id, level, time, fmt, ap);
1427 va_end(ap);
1430 void set_osd_tmsg(int id, int level, int time, const char *fmt, ...)
1432 va_list ap;
1433 va_start(ap, fmt);
1434 set_osd_msg_va(id, level, time, mp_gtext(fmt), ap);
1435 va_end(ap);
1440 * \brief Remove a message from the OSD stack
1442 * This function can be used to get rid of a message right away.
1446 void rm_osd_msg(int id) {
1447 mp_osd_msg_t *msg,*last=NULL;
1449 // Search for the msg
1450 for(msg = osd_msg_stack ; msg && msg->id != id ;
1451 last = msg, msg = msg->prev);
1452 if(!msg) return;
1454 // Detach it from the stack and free it
1455 if(last)
1456 last->prev = msg->prev;
1457 else
1458 osd_msg_stack = msg->prev;
1459 free(msg);
1463 * \brief Remove all messages from the OSD stack
1467 static void clear_osd_msgs(void) {
1468 mp_osd_msg_t* msg = osd_msg_stack, *prev = NULL;
1469 while(msg) {
1470 prev = msg->prev;
1471 free(msg);
1472 msg = prev;
1474 osd_msg_stack = NULL;
1478 * \brief Get the current message from the OSD stack.
1480 * This function decrements the message timer and destroys the old ones.
1481 * The message that should be displayed is returned (if any).
1485 static mp_osd_msg_t* get_osd_msg(struct MPContext *mpctx)
1487 struct MPOpts *opts = &mpctx->opts;
1488 mp_osd_msg_t *msg,*prev,*last = NULL;
1489 static unsigned last_update = 0;
1490 unsigned now = GetTimerMS();
1491 unsigned diff;
1492 char hidden_dec_done = 0;
1494 if (mpctx->osd_visible) {
1495 // 36000000 means max timed visibility is 1 hour into the future, if
1496 // the difference is greater assume it's wrapped around from below 0
1497 if (mpctx->osd_visible - now > 36000000) {
1498 mpctx->osd_visible = 0;
1499 vo_osd_progbar_type = -1; // disable
1500 vo_osd_changed(OSDTYPE_PROGBAR);
1501 mpctx->osd_function = mpctx->paused ? OSD_PAUSE : OSD_PLAY;
1504 if (mpctx->osd_show_percentage_until - now > 36000000)
1505 mpctx->osd_show_percentage_until = 0;
1507 if(!last_update) last_update = now;
1508 diff = now >= last_update ? now - last_update : 0;
1510 last_update = now;
1512 // Look for the first message in the stack with high enough level.
1513 for(msg = osd_msg_stack ; msg ; last = msg, msg = prev) {
1514 prev = msg->prev;
1515 if (msg->level > opts->osd_level && hidden_dec_done)
1516 continue;
1517 // The message has a high enough level or it is the first hidden one
1518 // in both cases we decrement the timer or kill it.
1519 if(!msg->started || msg->time > diff) {
1520 if(msg->started) msg->time -= diff;
1521 else msg->started = 1;
1522 // display it
1523 if (msg->level <= opts->osd_level)
1524 return msg;
1525 hidden_dec_done = 1;
1526 continue;
1528 // kill the message
1529 free(msg);
1530 if(last) {
1531 last->prev = prev;
1532 msg = last;
1533 } else {
1534 osd_msg_stack = prev;
1535 msg = NULL;
1538 // Nothing found
1539 return NULL;
1543 * \brief Display the OSD bar.
1545 * Display the OSD bar or fall back on a simple message.
1549 void set_osd_bar(struct MPContext *mpctx, int type,const char* name,double min,double max,double val) {
1550 struct MPOpts *opts = &mpctx->opts;
1551 if (opts->osd_level < 1)
1552 return;
1554 if(mpctx->sh_video) {
1555 mpctx->osd_visible = (GetTimerMS() + 1000) | 1;
1556 vo_osd_progbar_type = type;
1557 vo_osd_progbar_value = 256*(val-min)/(max-min);
1558 vo_osd_changed(OSDTYPE_PROGBAR);
1559 return;
1562 set_osd_msg(OSD_MSG_BAR, 1, opts->osd_duration, "%s: %d %%",
1563 name, ROUND(100*(val-min)/(max-min)));
1567 * \brief Display text subtitles on the OSD
1569 void set_osd_subtitle(struct MPContext *mpctx, subtitle *subs)
1571 int i;
1572 vo_sub = subs;
1573 vo_osd_changed(OSDTYPE_SUBTITLE);
1574 if (!mpctx->sh_video) {
1575 // reverse order, since newest set_osd_msg is displayed first
1576 for (i = SUB_MAX_TEXT - 1; i >= 0; i--) {
1577 if (!subs || i >= subs->lines || !subs->text[i])
1578 rm_osd_msg(OSD_MSG_SUB_BASE + i);
1579 else {
1580 // HACK: currently display time for each sub line except the last is set to 2 seconds.
1581 int display_time = i == subs->lines - 1 ? 180000 : 2000;
1582 set_osd_msg(OSD_MSG_SUB_BASE + i, 1, display_time, "%s", subs->text[i]);
1589 * \brief Update the OSD message line.
1591 * This function displays the current message on the vo OSD or on the term.
1592 * If the stack is empty and the OSD level is high enough the timer
1593 * is displayed (only on the vo OSD).
1597 static void update_osd_msg(struct MPContext *mpctx)
1599 struct MPOpts *opts = &mpctx->opts;
1600 mp_osd_msg_t *msg;
1601 struct osd_state *osd = mpctx->osd;
1602 char osd_text_timer[128];
1604 if (mpctx->add_osd_seek_info) {
1605 double percentage = get_percent_pos(mpctx);
1606 set_osd_bar(mpctx, 0, "Position", 0, 100, percentage);
1607 if (mpctx->sh_video)
1608 mpctx->osd_show_percentage_until = (GetTimerMS() + 1000) | 1;
1609 mpctx->add_osd_seek_info = false;
1612 // Look if we have a msg
1613 if((msg = get_osd_msg(mpctx))) {
1614 if (strcmp(osd->osd_text, msg->msg)) {
1615 strncpy(osd->osd_text, msg->msg, 127);
1616 if(mpctx->sh_video) vo_osd_changed(OSDTYPE_OSD); else
1617 if(opts->term_osd)
1618 mp_msg(MSGT_CPLAYER,MSGL_STATUS, "%s%s\n", opts->term_osd_esc,
1619 msg->msg);
1621 return;
1624 if(mpctx->sh_video) {
1625 // fallback on the timer
1626 if (opts->osd_level >= 2) {
1627 int len = get_time_length(mpctx);
1628 int percentage = -1;
1629 char percentage_text[10];
1630 int pts = get_current_time(mpctx);
1632 if (mpctx->osd_show_percentage_until)
1633 percentage = get_percent_pos(mpctx);
1635 if (percentage >= 0)
1636 snprintf(percentage_text, 9, " (%d%%)", percentage);
1637 else
1638 percentage_text[0] = 0;
1640 if (opts->osd_level == 3)
1641 snprintf(osd_text_timer, 63,
1642 "%c %02d:%02d:%02d / %02d:%02d:%02d%s",
1643 mpctx->osd_function,pts/3600,(pts/60)%60,pts%60,
1644 len/3600,(len/60)%60,len%60,percentage_text);
1645 else
1646 snprintf(osd_text_timer, 63, "%c %02d:%02d:%02d%s",
1647 mpctx->osd_function,pts/3600,(pts/60)%60,
1648 pts%60,percentage_text);
1649 } else
1650 osd_text_timer[0]=0;
1652 if (strcmp(osd->osd_text, osd_text_timer)) {
1653 strncpy(osd->osd_text, osd_text_timer, 63);
1654 vo_osd_changed(OSDTYPE_OSD);
1656 return;
1659 // Clear the term osd line
1660 if (opts->term_osd && osd->osd_text[0]) {
1661 osd->osd_text[0] = 0;
1662 printf("%s\n", opts->term_osd_esc);
1666 ///@}
1667 // OSDMsgStack
1670 void reinit_audio_chain(struct MPContext *mpctx)
1672 struct MPOpts *opts = &mpctx->opts;
1673 if (!mpctx->sh_audio)
1674 return;
1675 if (!(mpctx->initialized_flags & INITIALIZED_ACODEC)) {
1676 current_module="init_audio_codec";
1677 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1678 if(!init_best_audio_codec(mpctx->sh_audio,audio_codec_list,audio_fm_list)){
1679 goto init_error;
1681 mpctx->initialized_flags|=INITIALIZED_ACODEC;
1682 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
1686 current_module="af_preinit";
1687 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1688 ao_data.samplerate=force_srate;
1689 ao_data.channels=0;
1690 ao_data.format = opts->audio_output_format;
1692 // first init to detect best values
1693 if(!init_audio_filters(mpctx->sh_audio, // preliminary init
1694 // input:
1695 mpctx->sh_audio->samplerate,
1696 // output:
1697 &ao_data.samplerate, &ao_data.channels, &ao_data.format)){
1698 mp_tmsg(MSGT_CPLAYER,MSGL_ERR, "Error at audio filter chain "
1699 "pre-init!\n");
1700 exit_player(mpctx, EXIT_ERROR);
1702 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1703 current_module="ao2_init";
1704 ao_data.buffersize = opts->ao_buffersize;
1705 mpctx->audio_out = init_best_audio_out(opts->audio_driver_list,
1706 0, // plugin flag
1707 ao_data.samplerate,
1708 ao_data.channels,
1709 ao_data.format, 0);
1710 if(!mpctx->audio_out){
1711 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Could not open/initialize audio device -> no sound.\n");
1712 goto init_error;
1714 mpctx->initialized_flags|=INITIALIZED_AO;
1715 mp_msg(MSGT_CPLAYER,MSGL_INFO,"AO: [%s] %dHz %dch %s (%d bytes per sample)\n",
1716 mpctx->audio_out->info->short_name,
1717 ao_data.samplerate, ao_data.channels,
1718 af_fmt2str_short(ao_data.format),
1719 af_fmt2bits(ao_data.format)/8 );
1720 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Description: %s\nAO: Author: %s\n",
1721 mpctx->audio_out->info->name, mpctx->audio_out->info->author);
1722 if(strlen(mpctx->audio_out->info->comment) > 0)
1723 mp_msg(MSGT_CPLAYER,MSGL_V,"AO: Comment: %s\n", mpctx->audio_out->info->comment);
1726 // init audio filters:
1727 current_module="af_init";
1728 if(!build_afilter_chain(mpctx, mpctx->sh_audio, &ao_data)) {
1729 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Couldn't find matching filter/ao format!\n");
1730 goto init_error;
1732 mpctx->mixer.audio_out = mpctx->audio_out;
1733 mpctx->mixer.volstep = volstep;
1734 mpctx->syncing_audio = true;
1735 return;
1737 init_error:
1738 uninit_player(mpctx, INITIALIZED_ACODEC|INITIALIZED_AO); // close codec and possibly AO
1739 mpctx->sh_audio=mpctx->d_audio->sh=NULL; // -> nosound
1740 mpctx->d_audio->id = -2;
1744 ///@}
1745 // Command2Property
1748 // Return pts value corresponding to the end point of audio written to the
1749 // ao so far.
1750 static double written_audio_pts(struct MPContext *mpctx)
1752 sh_audio_t *sh_audio = mpctx->sh_audio;
1753 demux_stream_t *d_audio = mpctx->d_audio;
1754 double buffered_output;
1755 // first calculate the end pts of audio that has been output by decoder
1756 double a_pts = sh_audio->pts;
1757 if (a_pts != MP_NOPTS_VALUE)
1758 // Good, decoder supports new way of calculating audio pts.
1759 // sh_audio->pts is the timestamp of the latest input packet with
1760 // known pts that the decoder has decoded. sh_audio->pts_bytes is
1761 // the amount of bytes the decoder has written after that timestamp.
1762 a_pts += sh_audio->pts_bytes / (double) sh_audio->o_bps;
1763 else {
1764 // Decoder doesn't support new way of calculating pts (or we're
1765 // being called before it has decoded anything with known timestamp).
1766 // Use the old method of audio pts calculation: take the timestamp
1767 // of last packet with known pts the decoder has read data from,
1768 // and add amount of bytes read after the beginning of that packet
1769 // divided by input bps. This will be inaccurate if the input/output
1770 // ratio is not constant for every audio packet or if it is constant
1771 // but not accurately known in sh_audio->i_bps.
1773 a_pts = d_audio->pts;
1774 // ds_tell_pts returns bytes read after last timestamp from
1775 // demuxing layer, decoder might use sh_audio->a_in_buffer for bytes
1776 // it has read but not decoded
1777 if (sh_audio->i_bps)
1778 a_pts += (ds_tell_pts(d_audio) - sh_audio->a_in_buffer_len) /
1779 (double)sh_audio->i_bps;
1781 // Now a_pts hopefully holds the pts for end of audio from decoder.
1782 // Substract data in buffers between decoder and audio out.
1784 // Decoded but not filtered
1785 a_pts -= sh_audio->a_buffer_len / (double)sh_audio->o_bps;
1787 // Data buffered in audio filters, measured in bytes of "missing" output
1788 buffered_output = af_calc_delay(sh_audio->afilter);
1790 // Data that was ready for ao but was buffered because ao didn't fully
1791 // accept everything to internal buffers yet
1792 buffered_output += sh_audio->a_out_buffer_len;
1794 // Filters divide audio length by playback_speed, so multiply by it
1795 // to get the length in original units without speedup or slowdown
1796 a_pts -= buffered_output * mpctx->opts.playback_speed / ao_data.bps;
1798 return a_pts + mpctx->video_offset;
1801 // Return pts value corresponding to currently playing audio.
1802 double playing_audio_pts(struct MPContext *mpctx)
1804 return written_audio_pts(mpctx) - mpctx->opts.playback_speed *
1805 mpctx->audio_out->get_delay();
1808 static bool is_text_sub(int type)
1810 return type == 't' || type == 'm' || type == 'a';
1813 static bool is_av_sub(int type)
1815 return type == 'b' || type == 'p' || type == 'x';
1818 void update_subtitles(struct MPContext *mpctx, double refpts,
1819 double sub_offset, bool reset)
1821 struct MPOpts *opts = &mpctx->opts;
1822 struct sh_video *sh_video = mpctx->sh_video;
1823 struct demux_stream *d_sub = mpctx->d_sub;
1824 double curpts = refpts + sub_delay;
1825 unsigned char *packet=NULL;
1826 int len;
1827 int type = d_sub->sh ? ((sh_sub_t *)d_sub->sh)->type : 'v';
1828 static subtitle subs;
1829 if (reset) {
1830 sub_clear_text(&subs, MP_NOPTS_VALUE);
1831 if (vo_sub)
1832 set_osd_subtitle(mpctx, NULL);
1833 if (vo_spudec) {
1834 spudec_reset(vo_spudec);
1835 vo_osd_changed(OSDTYPE_SPU);
1837 #ifdef CONFIG_FFMPEG
1838 if (is_av_sub(type))
1839 reset_avsub(d_sub->sh);
1840 #endif
1841 return;
1843 // find sub
1844 if (mpctx->subdata) {
1845 if (sub_fps==0) sub_fps = sh_video ? sh_video->fps : 25;
1846 current_module = "find_sub";
1847 find_sub(mpctx, mpctx->subdata, curpts *
1848 (mpctx->subdata->sub_uses_time ? 100. : sub_fps));
1849 if (vo_sub)
1850 mpctx->vo_sub_last = vo_sub;
1853 // DVD sub:
1854 if (vobsub_id >= 0 || type == 'v') {
1855 int timestamp;
1856 current_module = "spudec";
1857 /* Get a sub packet from the DVD or a vobsub */
1858 while(1) {
1859 // Vobsub
1860 len = 0;
1861 if (vo_vobsub) {
1862 if (curpts >= 0) {
1863 len = vobsub_get_packet(vo_vobsub, curpts,
1864 (void**)&packet, &timestamp);
1865 if (len > 0) {
1866 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);
1869 } else {
1870 // DVD sub
1871 len = ds_get_packet_sub(d_sub, (unsigned char**)&packet);
1872 if (len > 0) {
1873 // XXX This is wrong, sh_video->pts can be arbitrarily
1874 // much behind demuxing position. Unfortunately using
1875 // d_video->pts which would have been the simplest
1876 // improvement doesn't work because mpeg specific hacks
1877 // in video.c set d_video->pts to 0.
1878 float x = d_sub->pts - refpts;
1879 if (x > -20 && x < 20) // prevent missing subs on pts reset
1880 timestamp = 90000*d_sub->pts;
1881 else timestamp = 90000*curpts;
1882 mp_dbg(MSGT_CPLAYER, MSGL_V, "\rDVD sub: len=%d "
1883 "v_pts=%5.3f s_pts=%5.3f ts=%d \n", len,
1884 refpts, d_sub->pts, timestamp);
1887 if (len<=0 || !packet) break;
1888 // create it only here, since with some broken demuxers we might
1889 // type = v but no DVD sub and we currently do not change the
1890 // "original frame size" ever after init, leading to wrong-sized
1891 // PGS subtitles.
1892 if (!vo_spudec)
1893 vo_spudec = spudec_new(NULL);
1894 if (vo_vobsub || timestamp >= 0)
1895 spudec_assemble(vo_spudec, packet, len, timestamp);
1897 } else if (is_text_sub(type) || is_av_sub(type) || type == 'd') {
1898 if (type == 'd' && !d_sub->demuxer->teletext) {
1899 tt_stream_props tsp = {0};
1900 void *ptr = &tsp;
1901 if (teletext_control(NULL, TV_VBI_CONTROL_START, &ptr) == VBI_CONTROL_TRUE)
1902 d_sub->demuxer->teletext = ptr;
1904 if (d_sub->non_interleaved)
1905 ds_get_next_pts(d_sub);
1907 int orig_type = type;
1908 while (d_sub->first) {
1909 double subpts = ds_get_next_pts(d_sub) + sub_offset;
1910 type = orig_type;
1911 if (subpts > curpts) {
1912 // Libass handled subs can be fed to it in advance
1913 if (!opts->ass_enabled || !is_text_sub(type))
1914 break;
1915 // Try to avoid demuxing whole file at once
1916 if (d_sub->non_interleaved && subpts > curpts + 1)
1917 break;
1919 double endpts = d_sub->first->endpts + sub_offset;
1920 len = ds_get_packet_sub(d_sub, &packet);
1921 if (is_av_sub(type)) {
1922 #ifdef CONFIG_FFMPEG
1923 type = decode_avsub(d_sub->sh, &packet, &len, &subpts, &endpts);
1924 if (type <= 0)
1925 #endif
1926 continue;
1928 if (type == 'm') {
1929 if (len < 2) continue;
1930 len = FFMIN(len - 2, AV_RB16(packet));
1931 packet += 2;
1933 if (type == 'd') {
1934 if (d_sub->demuxer->teletext) {
1935 uint8_t *p = packet;
1936 p++;
1937 len--;
1938 while (len >= 46) {
1939 int sublen = p[1];
1940 if (p[0] == 2 || p[0] == 3)
1941 teletext_control(d_sub->demuxer->teletext,
1942 TV_VBI_CONTROL_DECODE_DVB, p + 2);
1943 p += sublen + 2;
1944 len -= sublen + 2;
1947 continue;
1949 #ifdef CONFIG_ASS
1950 if (opts->ass_enabled) {
1951 sh_sub_t* sh = d_sub->sh;
1952 ass_track = sh ? sh->ass_track : NULL;
1953 if (!ass_track) continue;
1954 if (type == 'a') { // ssa/ass subs with libass
1955 ass_process_chunk(ass_track, packet, len,
1956 (long long)(subpts*1000 + 0.5),
1957 (long long)((endpts-subpts)*1000 + 0.5));
1958 } else { // plaintext subs with libass
1959 if (subpts != MP_NOPTS_VALUE) {
1960 subtitle tmp_subs = {0};
1961 if (endpts == MP_NOPTS_VALUE) endpts = subpts + 3;
1962 sub_add_text(&tmp_subs, packet, len, endpts);
1963 tmp_subs.start = subpts * 100;
1964 tmp_subs.end = endpts * 100;
1965 ass_process_subtitle(ass_track, &tmp_subs);
1966 sub_clear_text(&tmp_subs, MP_NOPTS_VALUE);
1969 continue;
1971 #endif
1972 if (subpts != MP_NOPTS_VALUE) {
1973 if (endpts == MP_NOPTS_VALUE)
1974 sub_clear_text(&subs, MP_NOPTS_VALUE);
1975 if (type == 'a') { // ssa/ass subs without libass => convert to plaintext
1976 int i;
1977 unsigned char* p = packet;
1978 for (i=0; i < 8 && *p != '\0'; p++)
1979 if (*p == ',')
1980 i++;
1981 if (*p == '\0') /* Broken line? */
1982 continue;
1983 len -= p - packet;
1984 packet = p;
1986 sub_add_text(&subs, packet, len, endpts);
1987 set_osd_subtitle(mpctx, &subs);
1989 if (d_sub->non_interleaved)
1990 ds_get_next_pts(d_sub);
1992 if (!opts->ass_enabled)
1993 if (sub_clear_text(&subs, curpts))
1994 set_osd_subtitle(mpctx, &subs);
1996 if (vo_spudec) {
1997 spudec_heartbeat(vo_spudec, 90000*curpts);
1998 if (spudec_changed(vo_spudec))
1999 vo_osd_changed(OSDTYPE_SPU);
2002 current_module=NULL;
2005 static void update_teletext(sh_video_t *sh_video, demuxer_t *demuxer, int reset)
2007 int page_changed;
2009 if (!demuxer->teletext)
2010 return;
2012 //Also forcing page update when such ioctl is not supported or call error occured
2013 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_IS_CHANGED,&page_changed)!=VBI_CONTROL_TRUE)
2014 page_changed=1;
2016 if(!page_changed)
2017 return;
2019 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_GET_VBIPAGE,&vo_osd_teletext_page)!=VBI_CONTROL_TRUE)
2020 vo_osd_teletext_page=NULL;
2021 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_GET_HALF_PAGE,&vo_osd_teletext_half)!=VBI_CONTROL_TRUE)
2022 vo_osd_teletext_half=0;
2023 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_GET_MODE,&vo_osd_teletext_mode)!=VBI_CONTROL_TRUE)
2024 vo_osd_teletext_mode=0;
2025 if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_GET_FORMAT,&vo_osd_teletext_format)!=VBI_CONTROL_TRUE)
2026 vo_osd_teletext_format=0;
2027 vo_osd_changed(OSDTYPE_TELETEXT);
2029 teletext_control(demuxer->teletext,TV_VBI_CONTROL_MARK_UNCHANGED,NULL);
2032 static int check_framedrop(struct MPContext *mpctx, double frame_time) {
2033 struct MPOpts *opts = &mpctx->opts;
2034 // check for frame-drop:
2035 current_module = "check_framedrop";
2036 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
2037 static int dropped_frames;
2038 float delay = opts->playback_speed*mpctx->audio_out->get_delay();
2039 float d = delay-mpctx->delay;
2040 ++total_frame_cnt;
2041 // we should avoid dropping too many frames in sequence unless we
2042 // are too late. and we allow 100ms A-V delay here:
2043 if (d < -dropped_frames*frame_time-0.100 && !mpctx->paused
2044 && !mpctx->restart_playback) {
2045 ++drop_frame_cnt;
2046 ++dropped_frames;
2047 return frame_dropping;
2048 } else
2049 dropped_frames = 0;
2051 return 0;
2055 #ifdef HAVE_RTC
2056 int rtc_fd = -1;
2057 #endif
2059 static float timing_sleep(struct MPContext *mpctx, float time_frame)
2061 #ifdef HAVE_RTC
2062 if (rtc_fd >= 0){
2063 // -------- RTC -----------
2064 current_module="sleep_rtc";
2065 while (time_frame > 0.000) {
2066 unsigned long rtc_ts;
2067 if (read(rtc_fd, &rtc_ts, sizeof(rtc_ts)) <= 0)
2068 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC read error: %s\n", strerror(errno));
2069 time_frame -= get_relative_time(mpctx);
2071 } else
2072 #endif
2074 // assume kernel HZ=100 for softsleep, works with larger HZ but with
2075 // unnecessarily high CPU usage
2076 struct MPOpts *opts = &mpctx->opts;
2077 float margin = opts->softsleep ? 0.011 : 0;
2078 current_module = "sleep_timer";
2079 while (time_frame > margin) {
2080 usec_sleep(1000000 * (time_frame - margin));
2081 time_frame -= get_relative_time(mpctx);
2083 if (opts->softsleep){
2084 current_module = "sleep_soft";
2085 if (time_frame < 0)
2086 mp_tmsg(MSGT_AVSYNC, MSGL_WARN, "Warning! Softsleep underflow!\n");
2087 while (time_frame > 0)
2088 time_frame -= get_relative_time(mpctx); // burn the CPU
2091 return time_frame;
2094 static int select_subtitle(MPContext *mpctx)
2096 struct MPOpts *opts = &mpctx->opts;
2097 // find the best sub to use
2098 int id;
2099 int found = 0;
2100 mpctx->global_sub_pos = -1; // no subs by default
2101 if (vobsub_id >= 0) {
2102 // if user asks for a vobsub id, use that first.
2103 id = vobsub_id;
2104 found = mp_property_do("sub_vob", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
2107 if (!found && opts->sub_id >= 0) {
2108 // if user asks for a dvd sub id, use that next.
2109 id = opts->sub_id;
2110 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
2113 if (!found) {
2114 // if there are text subs to use, use those. (autosubs come last here)
2115 id = 0;
2116 found = mp_property_do("sub_file", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
2119 if (!found && opts->sub_id == -1) {
2120 // finally select subs by language and container hints
2121 if (opts->sub_id == -1)
2122 opts->sub_id =
2123 demuxer_sub_track_by_lang_and_default(mpctx->d_sub->demuxer,
2124 opts->sub_lang);
2125 if (opts->sub_id >= 0) {
2126 id = opts->sub_id;
2127 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) == M_PROPERTY_OK;
2130 return found;
2133 #ifdef CONFIG_DVDNAV
2134 #ifndef FF_B_TYPE
2135 #define FF_B_TYPE 3
2136 #endif
2137 /// store decoded video image
2138 static mp_image_t * mp_dvdnav_copy_mpi(mp_image_t *to_mpi,
2139 mp_image_t *from_mpi) {
2140 mp_image_t *mpi;
2142 /// Do not store B-frames
2143 if (from_mpi->pict_type == FF_B_TYPE)
2144 return to_mpi;
2146 if (to_mpi &&
2147 to_mpi->w == from_mpi->w &&
2148 to_mpi->h == from_mpi->h &&
2149 to_mpi->imgfmt == from_mpi->imgfmt)
2150 mpi = to_mpi;
2151 else {
2152 if (to_mpi)
2153 free_mp_image(to_mpi);
2154 if (from_mpi->w == 0 || from_mpi->h == 0)
2155 return NULL;
2156 mpi = alloc_mpi(from_mpi->w,from_mpi->h,from_mpi->imgfmt);
2159 copy_mpi(mpi,from_mpi);
2160 return mpi;
2163 static void mp_dvdnav_reset_stream (MPContext *ctx) {
2164 struct MPOpts *opts = &ctx->opts;
2165 if (ctx->sh_video) {
2166 /// clear video pts
2167 ctx->d_video->pts = 0.0f;
2168 ctx->sh_video->pts = 0.0f;
2169 ctx->sh_video->i_pts = 0.0f;
2170 ctx->sh_video->last_pts = 0.0f;
2171 ctx->sh_video->num_buffered_pts = 0;
2172 ctx->sh_video->num_frames = 0;
2173 ctx->sh_video->num_frames_decoded = 0;
2174 ctx->sh_video->timer = 0.0f;
2175 ctx->sh_video->stream_delay = 0.0f;
2176 ctx->sh_video->timer = 0;
2177 ctx->demuxer->stream_pts = MP_NOPTS_VALUE;
2180 if (ctx->sh_audio) {
2181 /// free audio packets and reset
2182 ds_free_packs(ctx->d_audio);
2183 audio_delay -= ctx->sh_audio->stream_delay;
2184 ctx->delay =- audio_delay;
2185 ctx->audio_out->reset();
2186 resync_audio_stream(ctx->sh_audio);
2189 audio_delay = 0.0f;
2190 ctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(ctx->stream);
2191 if (opts->sub_lang && opts->sub_id == dvdsub_lang_id) {
2192 dvdsub_lang_id = mp_dvdnav_sid_from_lang(ctx->stream, opts->sub_lang);
2193 if (dvdsub_lang_id != opts->sub_id) {
2194 opts->sub_id = dvdsub_lang_id;
2195 select_subtitle(ctx);
2199 /// clear all EOF related flags
2200 ctx->d_video->eof = ctx->d_audio->eof = ctx->stream->eof = 0;
2203 /// Restore last decoded DVDNAV (still frame)
2204 static mp_image_t *mp_dvdnav_restore_smpi(struct MPContext *mpctx,
2205 int *in_size,
2206 unsigned char **start,
2207 mp_image_t *decoded_frame)
2209 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2210 return decoded_frame;
2212 /// a change occured in dvdnav stream
2213 if (mp_dvdnav_cell_has_changed(mpctx->stream,0)) {
2214 mp_dvdnav_read_wait(mpctx->stream, 1, 1);
2215 mp_dvdnav_context_free(mpctx);
2216 mp_dvdnav_reset_stream(mpctx);
2217 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
2218 mp_dvdnav_cell_has_changed(mpctx->stream,1);
2221 if (*in_size < 0) {
2222 float len;
2224 /// Display still frame, if any
2225 if (mpctx->nav_smpi && !mpctx->nav_buffer)
2226 decoded_frame = mpctx->nav_smpi;
2228 /// increment video frame : continue playing after still frame
2229 len = get_time_length(mpctx);
2230 if (mpctx->sh_video->pts >= len &&
2231 mpctx->sh_video->pts > 0.0 && len > 0.0) {
2232 mp_dvdnav_skip_still(mpctx->stream);
2233 mp_dvdnav_skip_wait(mpctx->stream);
2235 mpctx->sh_video->pts += 1 / mpctx->sh_video->fps;
2237 if (mpctx->nav_buffer) {
2238 *start = mpctx->nav_start;
2239 *in_size = mpctx->nav_in_size;
2240 if (mpctx->nav_start)
2241 memcpy(*start,mpctx->nav_buffer,mpctx->nav_in_size);
2245 return decoded_frame;
2248 /// Save last decoded DVDNAV (still frame)
2249 static void mp_dvdnav_save_smpi(struct MPContext *mpctx, int in_size,
2250 unsigned char *start,
2251 mp_image_t *decoded_frame)
2253 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2254 return;
2256 free(mpctx->nav_buffer);
2258 mpctx->nav_buffer = malloc(in_size);
2259 mpctx->nav_start = start;
2260 mpctx->nav_in_size = mpctx->nav_buffer ? in_size : -1;
2261 if (mpctx->nav_buffer)
2262 memcpy(mpctx->nav_buffer,start,in_size);
2264 if (decoded_frame && mpctx->nav_smpi != decoded_frame)
2265 mpctx->nav_smpi = mp_dvdnav_copy_mpi(mpctx->nav_smpi,decoded_frame);
2267 #endif /* CONFIG_DVDNAV */
2269 /* Modify video timing to match the audio timeline. There are two main
2270 * reasons this is needed. First, video and audio can start from different
2271 * positions at beginning of file or after a seek (MPlayer starts both
2272 * immediately even if they have different pts). Second, the file can have
2273 * audio timestamps that are inconsistent with the duration of the audio
2274 * packets, for example two consecutive timestamp values differing by
2275 * one second but only a packet with enough samples for half a second
2276 * of playback between them.
2278 static void adjust_sync(struct MPContext *mpctx, double frame_time)
2280 current_module = "av_sync";
2282 if (!mpctx->sh_audio || mpctx->syncing_audio)
2283 return;
2285 double a_pts = written_audio_pts(mpctx) - mpctx->delay;
2286 double v_pts = mpctx->sh_video->pts;
2287 double av_delay = a_pts - v_pts;
2288 // Try to sync vo_flip() so it will *finish* at given time
2289 av_delay += mpctx->last_vo_flip_duration;
2290 av_delay -= audio_delay; // This much pts difference is desired
2292 double change = av_delay * 0.1;
2293 double max_change = default_max_pts_correction >= 0 ?
2294 default_max_pts_correction : frame_time * 0.1;
2295 if (change < -max_change)
2296 change = -max_change;
2297 else if (change > max_change)
2298 change = max_change;
2299 mpctx->delay += change;
2300 mpctx->total_avsync_change += change;
2303 #define ASYNC_PLAY_DONE -3
2304 static int audio_start_sync(struct MPContext *mpctx, int playsize)
2306 struct MPOpts *opts = &mpctx->opts;
2307 sh_audio_t * const sh_audio = mpctx->sh_audio;
2308 int res;
2310 // Timing info may not be set without
2311 res = decode_audio(sh_audio, 1);
2312 if (res < 0)
2313 return res;
2315 int bytes;
2316 bool did_retry = false;
2317 while (1) {
2318 double written_pts = written_audio_pts(mpctx);
2319 double ptsdiff = written_pts - mpctx->video_pts - mpctx->delay
2320 - audio_delay;
2321 bytes = ptsdiff * ao_data.bps / mpctx->opts.playback_speed;
2322 bytes -= bytes % (ao_data.channels * af_fmt2bits(ao_data.format) / 8);
2324 // ogg demuxers give packets without timing
2325 if (written_pts <= 1 && sh_audio->pts == MP_NOPTS_VALUE) {
2326 if (!did_retry) {
2327 // Try to read more data to see packets that have pts
2328 int res = decode_audio(sh_audio, ao_data.bps);
2329 if (res < 0)
2330 return res;
2331 did_retry = true;
2332 continue;
2334 bytes = 0;
2337 if (fabs(ptsdiff) > 300) // pts reset or just broken?
2338 bytes = 0;
2340 if (bytes > 0)
2341 break;
2343 mpctx->syncing_audio = false;
2344 int a = FFMIN(-bytes, FFMAX(playsize, 20000));
2345 int res = decode_audio(sh_audio, a);
2346 bytes += sh_audio->a_out_buffer_len;
2347 if (bytes >= 0) {
2348 memmove(sh_audio->a_out_buffer,
2349 sh_audio->a_out_buffer +
2350 sh_audio->a_out_buffer_len - bytes,
2351 bytes);
2352 sh_audio->a_out_buffer_len = bytes;
2353 if (res < 0)
2354 return res;
2355 return decode_audio(sh_audio, playsize);
2357 sh_audio->a_out_buffer_len = 0;
2358 if (res < 0)
2359 return res;
2361 int fillbyte = 0;
2362 if ((ao_data.format & AF_FORMAT_SIGN_MASK) == AF_FORMAT_US)
2363 fillbyte = 0x80;
2364 if (bytes >= playsize) {
2365 /* This case could fall back to the one below with
2366 * bytes = playsize, but then silence would keep accumulating
2367 * in a_out_buffer if the AO accepts less data than it asks for
2368 * in playsize. */
2369 char *p = malloc(playsize);
2370 memset(p, fillbyte, playsize);
2371 playsize = mpctx->audio_out->play(p, playsize, 0);
2372 free(p);
2373 mpctx->delay += opts->playback_speed*playsize/(double)ao_data.bps;
2374 return ASYNC_PLAY_DONE;
2376 mpctx->syncing_audio = false;
2377 decode_audio_prepend_bytes(sh_audio, bytes, fillbyte);
2378 return decode_audio(sh_audio, playsize);
2381 static int fill_audio_out_buffers(struct MPContext *mpctx)
2383 struct MPOpts *opts = &mpctx->opts;
2384 unsigned int t;
2385 double tt;
2386 int playsize;
2387 int playflags=0;
2388 int audio_eof=0;
2389 bool format_change = false;
2390 sh_audio_t * const sh_audio = mpctx->sh_audio;
2392 current_module="play_audio";
2394 while (1) {
2395 int sleep_time;
2396 // all the current uses of ao_data.pts seem to be in aos that handle
2397 // sync completely wrong; there should be no need to use ao_data.pts
2398 // in get_space()
2399 ao_data.pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2400 playsize = mpctx->audio_out->get_space();
2401 if (mpctx->sh_video || playsize >= ao_data.outburst)
2402 break;
2404 // handle audio-only case:
2405 // this is where mplayer sleeps during audio-only playback
2406 // to avoid 100% CPU use
2407 sleep_time = (ao_data.outburst - playsize) * 1000 / ao_data.bps;
2408 if (sleep_time < 10) sleep_time = 10; // limit to 100 wakeups per second
2409 usec_sleep(sleep_time * 1000);
2412 // Fill buffer if needed:
2413 current_module="decode_audio";
2414 t = GetTimer();
2416 if (!opts->initial_audio_sync || (ao_data.format & AF_FORMAT_SPECIAL_MASK))
2417 mpctx->syncing_audio = false;
2419 int res;
2420 if (mpctx->syncing_audio && mpctx->sh_video)
2421 res = audio_start_sync(mpctx, playsize);
2422 else
2423 res = decode_audio(sh_audio, playsize);
2424 if (res < 0) { // EOF, error or format change
2425 if (res == -2)
2426 format_change = true;
2427 else if (res == ASYNC_PLAY_DONE)
2428 return 1;
2429 else if (mpctx->d_audio->eof) {
2430 audio_eof = 1;
2431 int unitsize = ao_data.channels * af_fmt2bits(ao_data.format) / 8;
2432 if (sh_audio->a_out_buffer_len < unitsize)
2433 return 0;
2436 t = GetTimer() - t;
2437 tt = t*0.000001f; audio_time_usage+=tt;
2438 if (playsize > sh_audio->a_out_buffer_len) {
2439 playsize = sh_audio->a_out_buffer_len;
2440 if (audio_eof)
2441 playflags |= AOPLAY_FINAL_CHUNK;
2443 if (!playsize)
2444 return 1;
2446 // play audio:
2447 current_module="play_audio";
2449 // Is this pts value actually useful for the aos that access it?
2450 // They're obviously badly broken in the way they handle av sync;
2451 // would not having access to this make them more broken?
2452 ao_data.pts = ((mpctx->sh_video?mpctx->sh_video->timer:0)+mpctx->delay)*90000.0;
2453 playsize = mpctx->audio_out->play(sh_audio->a_out_buffer, playsize, playflags);
2455 if (playsize > 0) {
2456 sh_audio->a_out_buffer_len -= playsize;
2457 memmove(sh_audio->a_out_buffer, &sh_audio->a_out_buffer[playsize],
2458 sh_audio->a_out_buffer_len);
2459 mpctx->delay += opts->playback_speed*playsize/(double)ao_data.bps;
2460 } else if (audio_eof && mpctx->audio_out->get_delay() < .04) {
2461 // Sanity check to avoid hanging in case current ao doesn't output
2462 // partial chunks and doesn't check for AOPLAY_FINAL_CHUNK
2463 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Audio output truncated at end.\n");
2464 sh_audio->a_out_buffer_len = 0;
2467 /* The format change isn't handled too gracefully. A more precise
2468 * implementation would require draining buffered old-format audio
2469 * while displaying video, then doing the output format switch.
2471 if (format_change) {
2472 uninit_player(mpctx, INITIALIZED_AO);
2473 reinit_audio_chain(mpctx);
2476 return 1;
2479 static int sleep_until_near_frame(struct MPContext *mpctx, float *time_frame,
2480 float *aq_sleep_time)
2482 struct MPOpts *opts = &mpctx->opts;
2483 double audio_limit = 2;
2484 current_module="calc_sleep_time";
2486 if (mpctx->restart_playback)
2487 return 0;
2489 *time_frame -= get_relative_time(mpctx); // reset timer
2491 if (mpctx->sh_audio && !mpctx->d_audio->eof) {
2492 float delay = mpctx->audio_out->get_delay();
2493 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "delay=%f\n", delay);
2495 if (opts->autosync) {
2497 * Adjust this raw delay value by calculating the expected
2498 * delay for this frame and generating a new value which is
2499 * weighted between the two. The higher autosync is, the
2500 * closer to the delay value gets to that which "-nosound"
2501 * would have used, and the longer it will take for A/V
2502 * sync to settle at the right value (but it eventually will.)
2503 * This settling time is very short for values below 100.
2505 float predicted = mpctx->delay / opts->playback_speed + *time_frame;
2506 float difference = delay - predicted;
2507 delay = predicted + difference / (float)opts->autosync;
2510 *time_frame = delay - mpctx->delay / opts->playback_speed;
2512 // delay = amount of audio buffered in soundcard/driver
2513 delay = FFMIN(delay, 0.5);
2514 delay = FFMAX(delay, 0.1);
2515 audio_limit = delay;
2516 } else {
2517 // If we're lagging more than 200 ms behind the right playback rate,
2518 // don't try to "catch up".
2519 // If benchmark is set always output frames as fast as possible
2520 // without sleeping.
2521 if (*time_frame < -0.2 || opts->benchmark)
2522 *time_frame = 0;
2525 double t = *time_frame - mpctx->video_out->flip_queue_offset;
2527 if (t <= 0.05)
2528 return 0;
2530 t -= 0.05;
2531 if (t > audio_limit * 0.6)
2532 t = audio_limit * 0.5;
2533 *aq_sleep_time += t;
2534 mp_input_get_cmd(mpctx->input, t * 1000 + 1, 1);
2535 return 1;
2538 int reinit_video_chain(struct MPContext *mpctx)
2540 struct MPOpts *opts = &mpctx->opts;
2541 sh_video_t * const sh_video = mpctx->sh_video;
2542 double ar=-1.0;
2543 //================== Init VIDEO (codec & libvo) ==========================
2544 if (!opts->fixed_vo || !(mpctx->initialized_flags & INITIALIZED_VO)) {
2545 current_module="preinit_libvo";
2547 //shouldn't we set dvideo->id=-2 when we fail?
2548 //if((mpctx->video_out->preinit(vo_subdevice))!=0){
2549 if(!(mpctx->video_out=init_best_video_out(opts, mpctx->x11_state, mpctx->key_fifo, mpctx->input))){
2550 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Error opening/initializing the selected video_out (-vo) device.\n");
2551 goto err_out;
2553 mpctx->initialized_flags|=INITIALIZED_VO;
2556 if(stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_ASPECT_RATIO, &ar) != STREAM_UNSUPPORTED)
2557 mpctx->sh_video->stream_aspect = ar;
2558 current_module="init_video_filters";
2560 char* vf_arg[] = { "_oldargs_", (char*)mpctx->video_out , NULL };
2561 sh_video->vfilter = vf_open_filter(opts, NULL,"vo",vf_arg);
2563 #ifdef CONFIG_MENU
2564 if(use_menu) {
2565 char* vf_arg[] = { "_oldargs_", menu_root, NULL };
2566 vf_menu = vf_open_plugin(opts,libmenu_vfs,sh_video->vfilter,"menu",vf_arg);
2567 if(!vf_menu) {
2568 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Can't open libmenu video filter with root menu %s.\n",menu_root);
2569 use_menu = 0;
2572 if(vf_menu)
2573 sh_video->vfilter = vf_menu;
2574 #endif
2576 #ifdef CONFIG_ASS
2577 if(opts->ass_enabled) {
2578 int i;
2579 int insert = 1;
2580 if (opts->vf_settings)
2581 for (i = 0; opts->vf_settings[i].name; ++i)
2582 if (strcmp(opts->vf_settings[i].name, "ass") == 0) {
2583 insert = 0;
2584 break;
2586 if (insert) {
2587 extern vf_info_t vf_info_ass;
2588 const vf_info_t* libass_vfs[] = {&vf_info_ass, NULL};
2589 char* vf_arg[] = {"auto", "1", NULL};
2590 int retcode = 0;
2591 struct vf_instance *vf_ass = vf_open_plugin_noerr(opts, libass_vfs,
2592 sh_video->vfilter,
2593 "ass", vf_arg,
2594 &retcode);
2595 if (vf_ass)
2596 sh_video->vfilter = vf_ass;
2597 else if (retcode == -1) // vf_ass open() returns -1 if there's VO EOSD
2598 mp_msg(MSGT_CPLAYER, MSGL_V, "[ass] vf_ass not needed\n");
2599 else
2600 mp_msg(MSGT_CPLAYER,MSGL_ERR, "ASS: cannot add video filter\n");
2603 #endif
2605 sh_video->vfilter = append_filters(sh_video->vfilter, opts->vf_settings);
2607 #ifdef CONFIG_ASS
2608 if (opts->ass_enabled)
2609 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_INIT_EOSD, ass_library);
2610 #endif
2612 current_module="init_video_codec";
2614 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2615 init_best_video_codec(sh_video,video_codec_list,video_fm_list);
2616 mp_msg(MSGT_CPLAYER,MSGL_INFO,"==========================================================================\n");
2618 if(!sh_video->initialized){
2619 if(!opts->fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
2620 goto err_out;
2623 mpctx->initialized_flags|=INITIALIZED_VCODEC;
2625 if (sh_video->codec)
2626 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODEC=%s\n", sh_video->codec->name);
2628 sh_video->last_pts = MP_NOPTS_VALUE;
2629 sh_video->num_buffered_pts = 0;
2630 sh_video->next_frame_time = 0;
2632 if (opts->auto_quality > 0) {
2633 // Auto quality option enabled
2634 output_quality=get_video_quality_max(sh_video);
2635 if (opts->auto_quality > output_quality)
2636 opts->auto_quality = output_quality;
2637 else
2638 output_quality = opts->auto_quality;
2639 mp_msg(MSGT_CPLAYER,MSGL_V,"AutoQ: setting quality to %d.\n",output_quality);
2640 set_video_quality(sh_video,output_quality);
2643 // ========== Init display (sh_video->disp_w*sh_video->disp_h/out_fmt) ============
2645 current_module="init_vo";
2647 return 1;
2649 err_out:
2650 mpctx->sh_video = mpctx->d_video->sh = NULL;
2651 return 0;
2654 static double update_video_nocorrect_pts(struct MPContext *mpctx)
2656 struct sh_video *sh_video = mpctx->sh_video;
2657 double frame_time = 0;
2658 struct vo *video_out = mpctx->video_out;
2659 while (1) {
2660 current_module = "filter_video";
2661 // In nocorrect-pts mode there is no way to properly time these frames
2662 if (vo_get_buffered_frame(video_out, 0) >= 0)
2663 break;
2664 if (vf_output_queued_frame(sh_video->vfilter))
2665 break;
2666 unsigned char *packet = NULL;
2667 frame_time = sh_video->next_frame_time;
2668 if (mpctx->restart_playback)
2669 frame_time = 0;
2670 int in_size = video_read_frame(sh_video, &sh_video->next_frame_time,
2671 &packet, force_fps);
2672 if (in_size < 0) {
2673 #ifdef CONFIG_DVDNAV
2674 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
2675 if (mp_dvdnav_is_eof(mpctx->stream))
2676 return -1;
2677 if (mpctx->d_video)
2678 mpctx->d_video->eof = 0;
2679 if (mpctx->d_audio)
2680 mpctx->d_audio->eof = 0;
2681 mpctx->stream->eof = 0;
2682 } else
2683 #endif
2684 return -1;
2686 if (in_size > max_framesize)
2687 max_framesize = in_size;
2688 sh_video->timer += frame_time;
2689 if (mpctx->sh_audio)
2690 mpctx->delay -= frame_time;
2691 // video_read_frame can change fps (e.g. for ASF video)
2692 vo_fps = sh_video->fps;
2693 int framedrop_type = check_framedrop(mpctx, frame_time);
2694 current_module = "decode video";
2696 void *decoded_frame;
2697 #ifdef CONFIG_DVDNAV
2698 decoded_frame = mp_dvdnav_restore_smpi(mpctx, &in_size, &packet, NULL);
2699 if (in_size >= 0 && !decoded_frame)
2700 #endif
2701 decoded_frame = decode_video(sh_video, packet, in_size, framedrop_type,
2702 sh_video->pts);
2703 #ifdef CONFIG_DVDNAV
2704 // Save last still frame for future display
2705 mp_dvdnav_save_smpi(mpctx, in_size, packet, decoded_frame);
2706 #endif
2707 if (decoded_frame) {
2708 current_module = "filter video";
2709 filter_video(sh_video, decoded_frame, sh_video->pts);
2711 break;
2713 return frame_time;
2716 static void determine_frame_pts(struct MPContext *mpctx)
2718 struct sh_video *sh_video = mpctx->sh_video;
2719 struct MPOpts *opts = &mpctx->opts;
2721 if (opts->user_pts_assoc_mode) {
2722 sh_video->pts_assoc_mode = opts->user_pts_assoc_mode;
2723 } else if (sh_video->pts_assoc_mode == 0) {
2724 if (mpctx->d_video->demuxer->timestamp_type == TIMESTAMP_TYPE_PTS
2725 && sh_video->codec_reordered_pts != MP_NOPTS_VALUE)
2726 sh_video->pts_assoc_mode = 1;
2727 else
2728 sh_video->pts_assoc_mode = 2;
2729 } else {
2730 int probcount1 = sh_video->num_reordered_pts_problems;
2731 int probcount2 = sh_video->num_sorted_pts_problems;
2732 if (sh_video->pts_assoc_mode == 2) {
2733 int tmp = probcount1;
2734 probcount1 = probcount2;
2735 probcount2 = tmp;
2737 if (probcount1 >= probcount2 * 1.5 + 2) {
2738 sh_video->pts_assoc_mode = 3 - sh_video->pts_assoc_mode;
2739 mp_msg(MSGT_CPLAYER, MSGL_V, "Switching to pts association mode "
2740 "%d.\n", sh_video->pts_assoc_mode);
2743 sh_video->pts = sh_video->pts_assoc_mode == 1 ?
2744 sh_video->codec_reordered_pts : sh_video->sorted_pts;
2747 static double update_video(struct MPContext *mpctx)
2749 struct sh_video *sh_video = mpctx->sh_video;
2750 struct vo *video_out = mpctx->video_out;
2751 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_SET_OSD_OBJ,
2752 mpctx->osd); // hack for vf_expand
2753 if (!mpctx->opts.correct_pts)
2754 return update_video_nocorrect_pts(mpctx);
2756 double pts;
2758 while (1) {
2759 current_module = "filter_video";
2760 if (!mpctx->hrseek_active
2761 && vo_get_buffered_frame(video_out, false) >= 0)
2762 break;
2763 // XXX Time used in this call is not counted in any performance
2764 // timer now
2765 if (vf_output_queued_frame(sh_video->vfilter))
2766 break;
2767 unsigned char *packet = NULL;
2768 int in_size = ds_get_packet_pts(mpctx->d_video, &packet, &pts);
2769 if (pts != MP_NOPTS_VALUE)
2770 pts += mpctx->video_offset;
2771 bool hit_eof = false;
2772 if (in_size < 0) {
2773 // try to extract last frames in case of decoder lag
2774 in_size = 0;
2775 pts = MP_NOPTS_VALUE;
2776 hit_eof = true;
2778 if (in_size > max_framesize)
2779 max_framesize = in_size;
2780 current_module = "decode video";
2781 if (pts >= mpctx->hrseek_pts - .005)
2782 mpctx->hrseek_framedrop = false;
2783 int framedrop_type = mpctx->hrseek_framedrop ? 1 :
2784 check_framedrop(mpctx, sh_video->frametime);
2785 void *decoded_frame = decode_video(sh_video, packet, in_size,
2786 framedrop_type, pts);
2787 if (decoded_frame) {
2788 determine_frame_pts(mpctx);
2789 current_module = "filter video";
2790 filter_video(sh_video, decoded_frame, sh_video->pts);
2791 } else if (hit_eof) {
2792 if (vo_get_buffered_frame(video_out, true) < 0)
2793 return -1;
2795 break;
2798 if (!video_out->frame_loaded)
2799 return 0;
2801 pts = video_out->next_pts;
2802 if (pts == MP_NOPTS_VALUE) {
2803 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Video pts after filters MISSING\n");
2804 // Try to use decoder pts from before filters
2805 pts = sh_video->pts;
2806 if (pts == MP_NOPTS_VALUE)
2807 pts = sh_video->last_pts;
2809 if (mpctx->hrseek_active && pts < mpctx->hrseek_pts - .005)
2810 return 0;
2811 mpctx->hrseek_active = false;
2812 sh_video->pts = pts;
2813 if (sh_video->last_pts == MP_NOPTS_VALUE)
2814 sh_video->last_pts = sh_video->pts;
2815 else if (sh_video->last_pts > sh_video->pts) {
2816 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Decreasing video pts: %f < %f\n",
2817 sh_video->pts, sh_video->last_pts);
2818 /* If the difference in pts is small treat it as jitter around the
2819 * right value (possibly caused by incorrect timestamp ordering) and
2820 * just show this frame immediately after the last one.
2821 * Treat bigger differences as timestamp resets and start counting
2822 * timing of later frames from the position of this one. */
2823 if (sh_video->last_pts - sh_video->pts > 0.5)
2824 sh_video->last_pts = sh_video->pts;
2825 else
2826 sh_video->pts = sh_video->last_pts;
2828 double frame_time = sh_video->pts - sh_video->last_pts;
2829 sh_video->last_pts = sh_video->pts;
2830 sh_video->timer += frame_time;
2831 if (mpctx->sh_audio)
2832 mpctx->delay -= frame_time;
2833 return frame_time;
2836 void pause_player(struct MPContext *mpctx)
2838 if (mpctx->paused)
2839 return;
2840 mpctx->paused = 1;
2841 mpctx->step_frames = 0;
2842 mpctx->time_frame -= get_relative_time(mpctx);
2844 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2845 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2847 if (mpctx->audio_out && mpctx->sh_audio)
2848 mpctx->audio_out->pause(); // pause audio, keep data if possible
2851 void unpause_player(struct MPContext *mpctx)
2853 if (!mpctx->paused)
2854 return;
2855 mpctx->paused = 0;
2857 if (mpctx->audio_out && mpctx->sh_audio)
2858 mpctx->audio_out->resume(); // resume audio
2859 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok
2860 && !mpctx->step_frames)
2861 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL); // resume video
2862 (void)get_relative_time(mpctx); // ignore time that passed during pause
2865 void add_step_frame(struct MPContext *mpctx)
2867 mpctx->step_frames++;
2868 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2869 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2870 unpause_player(mpctx);
2873 static void pause_loop(struct MPContext *mpctx)
2875 struct MPOpts *opts = &mpctx->opts;
2876 mp_cmd_t* cmd;
2877 if (!opts->quiet) {
2878 // Small hack to display the pause message on the OSD line.
2879 // The pause string is: "\n == PAUSE == \r" so we need to
2880 // take the first and the last char out
2881 if (opts->term_osd && !mpctx->sh_video) {
2882 char msg[128] = _("\n ===== PAUSE =====\r");
2883 int mlen = strlen(msg);
2884 msg[mlen-1] = '\0';
2885 set_osd_msg(OSD_MSG_PAUSE, 1, 0, "%s", msg+1);
2886 update_osd_msg(mpctx);
2887 } else
2888 mp_tmsg(MSGT_CPLAYER,MSGL_STATUS,"\n ===== PAUSE =====\r");
2889 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_PAUSED\n");
2892 while ( (cmd = mp_input_get_cmd(mpctx->input, 20, 1)) == NULL
2893 || cmd->id == MP_CMD_SET_MOUSE_POS || cmd->pausing == 4) {
2894 if (cmd) {
2895 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
2896 run_command(mpctx, cmd);
2897 mp_cmd_free(cmd);
2898 continue;
2900 if (mpctx->sh_video && mpctx->video_out)
2901 vo_check_events(mpctx->video_out);
2902 #ifdef CONFIG_MENU
2903 if (vf_menu)
2904 vf_menu_pause_update(vf_menu);
2905 #endif
2906 usec_sleep(20000);
2907 update_osd_msg(mpctx);
2908 int hack = vo_osd_changed(0);
2909 vo_osd_changed(hack);
2910 if (hack)
2911 break;
2916 // Find the right mute status and record position for new file position
2917 static void edl_seek_reset(MPContext *mpctx)
2919 mpctx->edl_muted = 0;
2920 next_edl_record = edl_records;
2922 while (next_edl_record) {
2923 if (next_edl_record->start_sec >= get_current_time(mpctx))
2924 break;
2926 if (next_edl_record->action == EDL_MUTE)
2927 mpctx->edl_muted = !mpctx->edl_muted;
2928 next_edl_record = next_edl_record->next;
2930 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2931 mixer_mute(&mpctx->mixer);
2935 // Execute EDL command for the current position if one exists
2936 static void edl_update(MPContext *mpctx)
2938 if (!next_edl_record)
2939 return;
2941 if (!mpctx->sh_video) {
2942 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot use EDL without video, disabling.\n");
2943 free_edl(edl_records);
2944 next_edl_record = NULL;
2945 edl_records = NULL;
2946 return;
2949 if (get_current_time(mpctx) >= next_edl_record->start_sec) {
2950 if (next_edl_record->action == EDL_SKIP) {
2951 mpctx->osd_function = OSD_FFW;
2952 queue_seek(mpctx, MPSEEK_RELATIVE, next_edl_record->length_sec, 0);
2953 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_SKIP: start [%f], stop "
2954 "[%f], length [%f]\n", next_edl_record->start_sec,
2955 next_edl_record->stop_sec, next_edl_record->length_sec);
2957 else if (next_edl_record->action == EDL_MUTE) {
2958 mpctx->edl_muted = !mpctx->edl_muted;
2959 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
2960 mixer_mute(&mpctx->mixer);
2961 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_MUTE: [%f]\n",
2962 next_edl_record->start_sec );
2964 next_edl_record = next_edl_record->next;
2968 static void reinit_decoders(struct MPContext *mpctx)
2970 reinit_video_chain(mpctx);
2971 reinit_audio_chain(mpctx);
2972 mp_property_do("sub", M_PROPERTY_SET, &mpctx->global_sub_pos, mpctx);
2975 static void seek_reset(struct MPContext *mpctx)
2977 if (mpctx->sh_video) {
2978 current_module = "seek_video_reset";
2979 resync_video_stream(mpctx->sh_video);
2980 mpctx->sh_video->timer = 0;
2981 vo_seek_reset(mpctx->video_out);
2982 mpctx->sh_video->timer = 0;
2983 mpctx->sh_video->num_buffered_pts = 0;
2984 mpctx->sh_video->last_pts = MP_NOPTS_VALUE;
2985 mpctx->delay = 0;
2986 mpctx->time_frame = 0;
2987 mpctx->restart_playback = true;
2988 // Not all demuxers set d_video->pts during seek, so this value
2989 // (which is used by at least vobsub and edl code below) may
2990 // be completely wrong (probably 0).
2991 mpctx->sh_video->pts = mpctx->d_video->pts + mpctx->video_offset;
2992 mpctx->video_pts = mpctx->sh_video->pts;
2993 update_subtitles(mpctx, mpctx->sh_video->pts, mpctx->video_offset,
2994 true);
2995 update_teletext(mpctx->sh_video, mpctx->demuxer, 1);
2998 if (mpctx->sh_audio) {
2999 current_module = "seek_audio_reset";
3000 resync_audio_stream(mpctx->sh_audio);
3001 mpctx->audio_out->reset(); // stop audio, throwing away buffered data
3002 mpctx->sh_audio->a_buffer_len = 0;
3003 mpctx->sh_audio->a_out_buffer_len = 0;
3004 if (!mpctx->sh_video)
3005 update_subtitles(mpctx, mpctx->sh_audio->pts,
3006 mpctx->video_offset, true);
3009 if (vo_vobsub && mpctx->sh_video) {
3010 current_module = "seek_vobsub_reset";
3011 vobsub_seek(vo_vobsub, mpctx->sh_video->pts);
3014 edl_seek_reset(mpctx);
3016 mpctx->hrseek_active = false;
3017 mpctx->hrseek_framedrop = false;
3018 mpctx->total_avsync_change = 0;
3019 audio_time_usage = 0; video_time_usage = 0; vout_time_usage = 0;
3020 drop_frame_cnt = 0;
3022 current_module = NULL;
3025 static bool timeline_set_part(struct MPContext *mpctx, int i)
3027 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
3028 struct timeline_part *n = mpctx->timeline + i;
3029 mpctx->timeline_part = i;
3030 mpctx->video_offset = n->start - n->source_start;
3031 if (n->source == p->source)
3032 return false;
3033 uninit_player(mpctx, INITIALIZED_VCODEC | (mpctx->opts.fixed_vo && mpctx->opts.video_id != -2 ? 0 : INITIALIZED_VO) | INITIALIZED_AO | INITIALIZED_ACODEC);
3034 mpctx->demuxer = n->source->demuxer;
3035 mpctx->d_video = mpctx->demuxer->video;
3036 mpctx->d_audio = mpctx->demuxer->audio;
3037 mpctx->d_sub = mpctx->demuxer->sub;
3038 mpctx->sh_video = mpctx->d_video->sh;
3039 mpctx->sh_audio = mpctx->d_audio->sh;
3040 return true;
3043 // Given pts, switch playback to the corresponding part.
3044 // Return offset within that part.
3045 static double timeline_set_from_time(struct MPContext *mpctx, double pts,
3046 bool *need_reset)
3048 if (pts < 0)
3049 pts = 0;
3050 for (int i = 0; i < mpctx->num_timeline_parts; i++) {
3051 struct timeline_part *p = mpctx->timeline + i;
3052 if (pts < (p+1)->start) {
3053 *need_reset = timeline_set_part(mpctx, i);
3054 return pts - p->start + p->source_start;
3057 return -1;
3061 // return -1 if seek failed (non-seekable stream?), 0 otherwise
3062 static int seek(MPContext *mpctx, struct seek_params seek)
3064 struct MPOpts *opts = &mpctx->opts;
3066 current_module = "seek";
3067 if (mpctx->stop_play == AT_END_OF_FILE)
3068 mpctx->stop_play = KEEP_PLAYING;
3069 bool hr_seek = mpctx->demuxer->accurate_seek && opts->correct_pts;
3070 hr_seek &= seek.exact >= 0 && seek.type != MPSEEK_FACTOR;
3071 hr_seek &= opts->hr_seek == 0 && seek.type == MPSEEK_ABSOLUTE
3072 || opts->hr_seek > 0 || seek.exact > 0;
3073 if (seek.type == MPSEEK_FACTOR
3074 || seek.type == MPSEEK_ABSOLUTE
3075 && seek.amount < mpctx->last_chapter_pts
3076 || seek.amount < 0)
3077 mpctx->last_chapter_seek = -1;
3078 if (mpctx->timeline && seek.type == MPSEEK_FACTOR) {
3079 seek.amount *= mpctx->timeline[mpctx->num_timeline_parts].start;
3080 seek.type = MPSEEK_ABSOLUTE;
3082 if ((mpctx->demuxer->accurate_seek || mpctx->timeline)
3083 && seek.type == MPSEEK_RELATIVE) {
3084 seek.type = MPSEEK_ABSOLUTE;
3085 seek.direction = seek.amount > 0 ? 1 : -1;
3086 seek.amount += get_current_time(mpctx);
3089 /* At least the liba52 decoder wants to read from the input stream
3090 * during initialization, so reinit must be done after the demux_seek()
3091 * call that clears possible stream EOF. */
3092 bool need_reset = false;
3093 double demuxer_amount = seek.amount;
3094 if (mpctx->timeline) {
3095 demuxer_amount = timeline_set_from_time(mpctx, seek.amount,
3096 &need_reset);
3097 if (demuxer_amount == -1) {
3098 mpctx->stop_play = AT_END_OF_FILE;
3099 // Clear audio from current position
3100 if (mpctx->sh_audio) {
3101 mpctx->audio_out->reset();
3102 mpctx->sh_audio->a_buffer_len = 0;
3103 mpctx->sh_audio->a_out_buffer_len = 0;
3105 return -1;
3108 int demuxer_style = 0;
3109 switch (seek.type) {
3110 case MPSEEK_FACTOR:
3111 demuxer_style |= SEEK_FACTOR; // fallthrough
3112 case MPSEEK_ABSOLUTE:
3113 demuxer_style |= SEEK_ABSOLUTE;
3115 if (hr_seek || seek.direction < 0)
3116 demuxer_style |= SEEK_BACKWARD;
3117 else if (seek.direction > 0)
3118 demuxer_style |= SEEK_FORWARD;
3120 int seekresult = demux_seek(mpctx->demuxer, demuxer_amount, audio_delay,
3121 demuxer_style);
3122 if (need_reset)
3123 reinit_decoders(mpctx);
3124 if (seekresult == 0)
3125 return -1;
3127 seek_reset(mpctx);
3129 /* Use the target time as "current position" for further relative
3130 * seeks etc until a new video frame has been decoded */
3131 if (seek.type == MPSEEK_ABSOLUTE)
3132 mpctx->video_pts = seek.amount;
3134 if (hr_seek) {
3135 mpctx->hrseek_active = true;
3136 mpctx->hrseek_framedrop = true;
3137 mpctx->hrseek_pts = seek.amount;
3140 mpctx->start_timestamp = GetTimerMS();
3142 return 0;
3145 void queue_seek(struct MPContext *mpctx, enum seek_type type, double amount,
3146 int exact)
3148 struct seek_params *seek = &mpctx->seek;
3149 switch (type) {
3150 case MPSEEK_RELATIVE:
3151 if (seek->type == MPSEEK_FACTOR)
3152 return; // Well... not common enough to bother doing better
3153 seek->amount += amount;
3154 seek->exact = FFMAX(seek->exact, exact);
3155 if (seek->type == MPSEEK_NONE)
3156 seek->exact = exact;
3157 if (seek->type == MPSEEK_ABSOLUTE)
3158 return;
3159 if (seek->amount == 0) {
3160 *seek = (struct seek_params){0};
3161 return;
3163 seek->type = MPSEEK_RELATIVE;
3164 return;
3165 case MPSEEK_ABSOLUTE:
3166 case MPSEEK_FACTOR:
3167 *seek = (struct seek_params) {
3168 .type = type,
3169 .amount = amount,
3170 .exact = exact,
3172 return;
3173 case MPSEEK_NONE:
3174 *seek = (struct seek_params){0};
3175 return;
3177 abort();
3181 double get_time_length(struct MPContext *mpctx)
3183 if (mpctx->timeline)
3184 return mpctx->timeline[mpctx->num_timeline_parts].start;
3186 struct demuxer *demuxer = mpctx->demuxer;
3187 double get_time_ans;
3188 // <= 0 means DEMUXER_CTRL_NOTIMPL or DEMUXER_CTRL_DONTKNOW
3189 if (demux_control(demuxer, DEMUXER_CTRL_GET_TIME_LENGTH,
3190 (void *) &get_time_ans) > 0)
3191 return get_time_ans;
3193 struct sh_video *sh_video = mpctx->d_video->sh;
3194 struct sh_audio *sh_audio = mpctx->d_audio->sh;
3195 if (sh_video && sh_video->i_bps && sh_audio && sh_audio->i_bps)
3196 return (double) (demuxer->movi_end - demuxer->movi_start) /
3197 (sh_video->i_bps + sh_audio->i_bps);
3198 if (sh_video && sh_video->i_bps)
3199 return (double) (demuxer->movi_end - demuxer->movi_start) /
3200 sh_video->i_bps;
3201 if (sh_audio && sh_audio->i_bps)
3202 return (double) (demuxer->movi_end - demuxer->movi_start) /
3203 sh_audio->i_bps;
3204 return 0;
3207 /* If there are timestamps from stream level then use those (for example
3208 * DVDs can have consistent times there while the MPEG-level timestamps
3209 * reset). */
3210 double get_current_time(struct MPContext *mpctx)
3212 struct demuxer *demuxer = mpctx->demuxer;
3213 if (demuxer->stream_pts != MP_NOPTS_VALUE)
3214 return demuxer->stream_pts;
3215 struct sh_video *sh_video = demuxer->video->sh;
3216 if (sh_video)
3217 return mpctx->video_pts;
3218 return playing_audio_pts(mpctx);
3221 int get_percent_pos(struct MPContext *mpctx)
3223 struct demuxer *demuxer = mpctx->demuxer;
3224 int ans = 0;
3225 if (mpctx->timeline)
3226 ans = get_current_time(mpctx) * 100 /
3227 mpctx->timeline[mpctx->num_timeline_parts].start;
3228 else if (demux_control(demuxer, DEMUXER_CTRL_GET_PERCENT_POS, &ans) > 0)
3230 else {
3231 int len = (demuxer->movi_end - demuxer->movi_start) / 100;
3232 off_t pos = demuxer->filepos > 0 ?
3233 demuxer->filepos : stream_tell(demuxer->stream);
3234 if (len > 0)
3235 ans = (pos - demuxer->movi_start) / len;
3236 else
3237 ans = 0;
3239 if (ans < 0)
3240 ans = 0;
3241 if (ans > 100)
3242 ans = 100;
3243 return ans;
3246 // -2 is no chapters, -1 is before first chapter
3247 int get_current_chapter(struct MPContext *mpctx)
3249 double current_pts = get_current_time(mpctx);
3250 if (!mpctx->chapters)
3251 return FFMAX(mpctx->last_chapter_seek,
3252 demuxer_get_current_chapter(mpctx->demuxer, current_pts));
3254 int i;
3255 for (i = 1; i < mpctx->num_chapters; i++)
3256 if (current_pts < mpctx->chapters[i].start)
3257 break;
3258 return FFMAX(mpctx->last_chapter_seek, i - 1);
3261 // currently returns a string allocated with malloc, not talloc
3262 char *chapter_display_name(struct MPContext *mpctx, int chapter)
3264 if (!mpctx->chapters || !mpctx->sh_video)
3265 return demuxer_chapter_display_name(mpctx->demuxer, chapter);
3266 return strdup(mpctx->chapters[chapter].name);
3269 int seek_chapter(struct MPContext *mpctx, int chapter, double *seek_pts,
3270 char **chapter_name)
3272 mpctx->last_chapter_seek = -1;
3273 if (!mpctx->chapters || !mpctx->sh_video) {
3274 int res = demuxer_seek_chapter(mpctx->demuxer, chapter, seek_pts,
3275 chapter_name);
3276 if (res >= 0) {
3277 if (*seek_pts == -1)
3278 seek_reset(mpctx);
3279 else {
3280 mpctx->last_chapter_seek = res;
3281 mpctx->last_chapter_pts = *seek_pts;
3284 return res;
3287 if (chapter >= mpctx->num_chapters)
3288 return -1;
3289 if (chapter < 0)
3290 chapter = 0;
3291 *seek_pts = mpctx->chapters[chapter].start;
3292 mpctx->last_chapter_seek = chapter;
3293 mpctx->last_chapter_pts = *seek_pts;
3294 if (chapter_name)
3295 *chapter_name = talloc_strdup(NULL, mpctx->chapters[chapter].name);
3296 return chapter;
3300 static void run_playloop(struct MPContext *mpctx)
3302 struct MPOpts *opts = &mpctx->opts;
3303 float aq_sleep_time = 0;
3305 if (opts->chapterrange[1] > 0) {
3306 int cur_chapter = get_current_chapter(mpctx);
3307 if (cur_chapter!=-1 && cur_chapter + 1 > opts->chapterrange[1])
3308 mpctx->stop_play = PT_NEXT_ENTRY;
3311 if (!mpctx->sh_audio && mpctx->d_audio->sh) {
3312 mpctx->sh_audio = mpctx->d_audio->sh;
3313 mpctx->sh_audio->ds = mpctx->d_audio;
3314 reinit_audio_chain(mpctx);
3317 /*========================== PLAY AUDIO ============================*/
3319 if (mpctx->sh_audio && !mpctx->paused
3320 && (!mpctx->restart_playback || !mpctx->sh_video))
3321 if (!fill_audio_out_buffers(mpctx))
3322 // at eof, all audio at least written to ao
3323 if (!mpctx->sh_video)
3324 mpctx->stop_play = AT_END_OF_FILE;
3327 if (!mpctx->sh_video) {
3328 mpctx->restart_playback = false;
3329 if (mpctx->step_frames) {
3330 mpctx->step_frames = 0;
3331 pause_player(mpctx);
3333 // handle audio-only case:
3334 double a_pos = 0;
3335 // sh_audio can be NULL due to video stream switching
3336 // TODO: handle this better
3337 if (mpctx->sh_audio)
3338 a_pos = playing_audio_pts(mpctx);
3340 print_status(mpctx, a_pos, false);
3342 if (end_at.type == END_AT_TIME && end_at.pos < a_pos)
3343 mpctx->stop_play = PT_NEXT_ENTRY;
3344 update_subtitles(mpctx, a_pos, mpctx->video_offset, false);
3345 update_osd_msg(mpctx);
3346 } else {
3348 /*========================== PLAY VIDEO ============================*/
3350 vo_pts = mpctx->sh_video->timer * 90000.0;
3351 vo_fps = mpctx->sh_video->fps;
3353 bool blit_frame = mpctx->video_out->frame_loaded;
3354 if (!blit_frame || mpctx->hrseek_active) {
3355 double frame_time = update_video(mpctx);
3356 blit_frame = mpctx->video_out->frame_loaded;
3357 blit_frame &= !mpctx->hrseek_active;
3358 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "*** ftime=%5.3f ***\n", frame_time);
3359 if (mpctx->sh_video->vf_initialized < 0) {
3360 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
3361 "\nFATAL: Could not initialize video filters (-vf) "
3362 "or video output (-vo).\n");
3363 mpctx->stop_play = PT_NEXT_ENTRY;
3364 return;
3366 if (frame_time < 0)
3367 mpctx->stop_play = AT_END_OF_FILE;
3368 else if (!mpctx->restart_playback) {
3369 mpctx->time_frame += frame_time / opts->playback_speed;
3370 adjust_sync(mpctx, frame_time);
3373 if (mpctx->timeline) {
3374 struct timeline_part *next =
3375 mpctx->timeline + mpctx->timeline_part + 1;
3376 if (mpctx->sh_video->pts >= next->start
3377 || mpctx->stop_play == AT_END_OF_FILE
3378 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts) {
3379 seek(mpctx, (struct seek_params){ .type = MPSEEK_ABSOLUTE,
3380 .amount = next->start });
3381 return;
3385 // ==========================================================================
3387 current_module = "vo_check_events";
3388 vo_check_events(mpctx->video_out);
3390 #ifdef CONFIG_X11
3391 if (stop_xscreensaver) {
3392 current_module = "stop_xscreensaver";
3393 xscreensaver_heartbeat(mpctx->x11_state);
3395 #endif
3396 if (heartbeat_cmd) {
3397 static unsigned last_heartbeat;
3398 unsigned now = GetTimerMS();
3399 if (now - last_heartbeat > 30000) {
3400 last_heartbeat = now;
3401 system(heartbeat_cmd);
3405 bool frame_time_remaining = sleep_until_near_frame(mpctx,
3406 &mpctx->time_frame,
3407 &aq_sleep_time);
3409 //====================== FLIP PAGE (VIDEO BLT): =========================
3411 current_module = "flip_page";
3412 if (!frame_time_remaining && blit_frame) {
3413 struct sh_video *sh_video = mpctx->sh_video;
3414 mpctx->video_pts = sh_video->pts;
3415 update_subtitles(mpctx, sh_video->pts, mpctx->video_offset, false);
3416 update_teletext(sh_video, mpctx->demuxer, 0);
3417 update_osd_msg(mpctx);
3418 struct vf_instance *vf = sh_video->vfilter;
3419 vf->control(vf, VFCTRL_DRAW_EOSD, NULL);
3420 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
3421 vo_osd_changed(0);
3423 mpctx->time_frame -= mpctx->video_out->flip_queue_offset;
3424 aq_sleep_time += mpctx->time_frame;
3425 // flag 256 means: libvo driver does its timing (dvb card)
3426 if (mpctx->time_frame > 0.001
3427 && !(mpctx->sh_video->output_flags&256))
3428 mpctx->time_frame = timing_sleep(mpctx, mpctx->time_frame);
3429 mpctx->time_frame += mpctx->video_out->flip_queue_offset;
3431 unsigned int t2 = GetTimer();
3432 unsigned int pts_us = mpctx->last_time + mpctx->time_frame * 1e6;
3433 int duration = -1;
3434 double pts2 = mpctx->video_out->next_pts2;
3435 if (pts2 != MP_NOPTS_VALUE && opts->correct_pts
3436 && !mpctx->restart_playback) {
3437 // expected A/V sync correction is ignored
3438 double diff = (pts2 - mpctx->video_pts);
3439 diff /= opts->playback_speed;
3440 if (mpctx->time_frame < 0)
3441 diff += mpctx->time_frame;
3442 if (diff < 0)
3443 diff = 0;
3444 if (diff > 10)
3445 diff = 10;
3446 duration = diff * 1e6;
3448 vo_flip_page(mpctx->video_out, pts_us | 1, duration);
3450 mpctx->last_vo_flip_duration = (GetTimer() - t2) * 0.000001;
3451 vout_time_usage += mpctx->last_vo_flip_duration;
3452 if (mpctx->video_out->driver->flip_page_timed) {
3453 // No need to adjust sync based on flip speed
3454 mpctx->last_vo_flip_duration = 0;
3455 // For print_status - VO call finishing early is OK for sync
3456 mpctx->time_frame -= get_relative_time(mpctx);
3458 if (mpctx->restart_playback) {
3459 mpctx->syncing_audio = true;
3460 if (mpctx->sh_audio && !mpctx->paused)
3461 fill_audio_out_buffers(mpctx);
3462 mpctx->restart_playback = false;
3463 mpctx->time_frame = 0;
3464 get_relative_time(mpctx);
3466 print_status(mpctx, MP_NOPTS_VALUE, true);
3467 } else
3468 print_status(mpctx, MP_NOPTS_VALUE, false);
3470 //============================ Auto QUALITY ============================
3472 /*Output quality adjustments:*/
3473 if (opts->auto_quality > 0) {
3474 current_module = "autoq";
3475 if (output_quality < opts->auto_quality && aq_sleep_time > 0)
3476 ++output_quality;
3477 else
3478 if (output_quality>1 && aq_sleep_time<0)
3479 --output_quality;
3480 else if (output_quality>0 && aq_sleep_time<-0.050f) // 50ms
3481 output_quality = 0;
3482 set_video_quality(mpctx->sh_video, output_quality);
3485 if (!frame_time_remaining && blit_frame) {
3486 if (play_n_frames >= 0) {
3487 --play_n_frames;
3488 if (play_n_frames <= 0)
3489 mpctx->stop_play = PT_NEXT_ENTRY;
3491 if (mpctx->step_frames > 0) {
3492 mpctx->step_frames--;
3493 if (mpctx->step_frames == 0)
3494 pause_player(mpctx);
3498 // FIXME: add size based support for -endpos
3499 if (end_at.type == END_AT_TIME &&
3500 !frame_time_remaining && end_at.pos <= mpctx->sh_video->pts)
3501 mpctx->stop_play = PT_NEXT_ENTRY;
3503 } // end if(mpctx->sh_video)
3505 #ifdef CONFIG_DVDNAV
3506 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
3507 nav_highlight_t hl;
3508 mp_dvdnav_get_highlight(mpctx->stream, &hl);
3509 if (!vo_spudec || !spudec_apply_palette_crop(vo_spudec, hl.palette, hl.sx, hl.sy, hl.ex, hl.ey)) {
3510 osd_set_nav_box(hl.sx, hl.sy, hl.ex, hl.ey);
3511 vo_osd_changed(OSDTYPE_DVDNAV);
3512 } else {
3513 osd_set_nav_box(0, 0, 0, 0);
3514 vo_osd_changed(OSDTYPE_DVDNAV);
3515 vo_osd_changed(OSDTYPE_SPU);
3518 if (mp_dvdnav_stream_has_changed(mpctx->stream)) {
3519 double ar = -1.0;
3520 if (mpctx->sh_video &&
3521 stream_control(mpctx->demuxer->stream,
3522 STREAM_CTRL_GET_ASPECT_RATIO, &ar)
3523 != STREAM_UNSUPPORTED)
3524 mpctx->sh_video->stream_aspect = ar;
3527 #endif
3529 //================= Keyboard events, SEEKing ====================
3531 current_module = "key_events";
3533 while (1) {
3534 mp_cmd_t *cmd;
3535 while ((cmd = mp_input_get_cmd(mpctx->input, 0, 1)) != NULL) {
3536 /* Allow running consecutive seek commands to combine them,
3537 * but execute the seek before running other commands.
3538 * If the user seeks continuously (keeps arrow key down)
3539 * try to finish showing a frame from one location before doing
3540 * another seek (which could lead to unchanging display). */
3541 if (mpctx->seek.type && cmd->id != MP_CMD_SEEK
3542 || mpctx->restart_playback && cmd->id == MP_CMD_SEEK
3543 && GetTimerMS() - mpctx->start_timestamp < 300)
3544 break;
3545 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
3546 run_command(mpctx, cmd);
3547 mp_cmd_free(cmd);
3548 if (mpctx->stop_play)
3549 break;
3551 if (!mpctx->paused || mpctx->stop_play || mpctx->seek.type
3552 || mpctx->restart_playback)
3553 break;
3554 if (mpctx->sh_video) {
3555 update_osd_msg(mpctx);
3556 int hack = vo_osd_changed(0);
3557 vo_osd_changed(hack);
3558 if (hack) {
3559 if (redraw_osd(mpctx->sh_video, mpctx->osd) < 0) {
3560 add_step_frame(mpctx);
3561 break;
3562 } else
3563 vo_osd_changed(0);
3566 pause_loop(mpctx);
3569 // handle -sstep
3570 if (step_sec > 0 && !mpctx->paused) {
3571 mpctx->osd_function = OSD_FFW;
3572 queue_seek(mpctx, MPSEEK_RELATIVE, step_sec, 0);
3575 edl_update(mpctx);
3577 /* Looping. */
3578 if (mpctx->stop_play==AT_END_OF_FILE && opts->loop_times>=0) {
3579 mp_msg(MSGT_CPLAYER, MSGL_V, "loop_times = %d\n", opts->loop_times);
3581 if (opts->loop_times>1)
3582 opts->loop_times--;
3583 else if (opts->loop_times==1)
3584 opts->loop_times = -1;
3585 play_n_frames = play_n_frames_mf;
3586 mpctx->stop_play = 0;
3587 queue_seek(mpctx, MPSEEK_ABSOLUTE, 0, 0);
3590 if (mpctx->seek.type) {
3591 seek(mpctx, mpctx->seek);
3592 mpctx->seek = (struct seek_params){0};
3597 static int find_ordered_chapter_sources(struct MPContext *mpctx,
3598 struct content_source *sources,
3599 int num_sources,
3600 unsigned char uid_map[][16])
3602 int num_filenames = 0;
3603 char **filenames = NULL;
3604 if (num_sources > 1) {
3605 mp_msg(MSGT_CPLAYER, MSGL_INFO, "This file references data from "
3606 "other sources.\n");
3607 if (mpctx->stream->type != STREAMTYPE_FILE) {
3608 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Playback source is not a "
3609 "normal disk file. Will not search for related files.\n");
3610 } else {
3611 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Will scan other files in the "
3612 "same directory to find referenced sources.\n");
3613 filenames = find_files(mpctx->demuxer->filename, ".mkv",
3614 &num_filenames);
3618 int num_left = num_sources - 1;
3619 for (int i = 0; i < num_filenames && num_left > 0; i++) {
3620 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Checking file %s\n",
3621 filename_recode(filenames[i]));
3622 int format;
3623 struct stream *s = open_stream(filenames[i], &mpctx->opts, &format);
3624 if (!s)
3625 continue;
3626 struct demuxer *d = demux_open(&mpctx->opts, s, DEMUXER_TYPE_MATROSKA,
3627 mpctx->opts.audio_id,
3628 mpctx->opts.video_id,
3629 mpctx->opts.sub_id, filenames[i]);
3630 if (!d) {
3631 free_stream(s);
3632 continue;
3634 if (d->file_format == DEMUXER_TYPE_MATROSKA) {
3635 for (int i = 1; i < num_sources; i++) {
3636 if (sources[i].demuxer)
3637 continue;
3638 if (!memcmp(uid_map[i], d->matroska_data.segment_uid, 16)) {
3639 mp_msg(MSGT_CPLAYER, MSGL_INFO,"Match for source %d: %s\n",
3640 i, filename_recode(d->filename));
3641 sources[i].stream = s;
3642 sources[i].demuxer = d;
3643 num_left--;
3644 goto match;
3648 free_demuxer(d);
3649 free_stream(s);
3650 continue;
3651 match:
3654 talloc_free(filenames);
3655 if (num_left) {
3656 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Failed to find ordered chapter part!\n"
3657 "There will be parts MISSING from the video!\n");
3658 for (int i = 1, j = 1; i < num_sources; i++)
3659 if (sources[i].demuxer) {
3660 sources[j] = sources[i];
3661 memcpy(uid_map[j], uid_map[i], 16);
3662 j++;
3665 return num_sources - num_left;
3668 static void build_ordered_chapter_timeline(struct MPContext *mpctx)
3670 struct MPOpts *opts = &mpctx->opts;
3672 if (!opts->ordered_chapters) {
3673 mp_msg(MSGT_CPLAYER, MSGL_INFO, "File uses ordered chapters, but "
3674 "you have disabled support for them. Ignoring.\n");
3675 return;
3678 mp_msg(MSGT_CPLAYER, MSGL_INFO, "File uses ordered chapters, will build "
3679 "edit timeline.\n");
3681 struct demuxer *demuxer = mpctx->demuxer;
3682 struct matroska_data *m = &demuxer->matroska_data;
3684 // +1 because sources/uid_map[0] is original file even if all chapters
3685 // actually use other sources and need separate entries
3686 struct content_source *sources = talloc_array_ptrtype(NULL, sources,
3687 m->num_ordered_chapters+1);
3688 sources[0].stream = mpctx->stream;
3689 sources[0].demuxer = mpctx->demuxer;
3690 unsigned char uid_map[m->num_ordered_chapters+1][16];
3691 int num_sources = 1;
3692 memcpy(uid_map[0], m->segment_uid, 16);
3694 for (int i = 0; i < m->num_ordered_chapters; i++) {
3695 struct matroska_chapter *c = m->ordered_chapters + i;
3696 if (!c->has_segment_uid)
3697 memcpy(c->segment_uid, m->segment_uid, 16);
3699 for (int j = 0; j < num_sources; j++)
3700 if (!memcmp(c->segment_uid, uid_map[j], 16))
3701 goto found1;
3702 memcpy(uid_map[num_sources], c->segment_uid, 16);
3703 sources[num_sources] = (struct content_source){};
3704 num_sources++;
3705 found1:
3709 num_sources = find_ordered_chapter_sources(mpctx, sources, num_sources,
3710 uid_map);
3713 // +1 for terminating chapter with start time marking end of last real one
3714 struct timeline_part *timeline = talloc_array_ptrtype(NULL, timeline,
3715 m->num_ordered_chapters + 1);
3716 struct chapter *chapters = talloc_array_ptrtype(NULL, chapters,
3717 m->num_ordered_chapters);
3718 uint64_t starttime = 0;
3719 uint64_t missing_time = 0;
3720 int part_count = 0;
3721 int num_chapters = 0;
3722 uint64_t prev_part_offset = 0;
3723 for (int i = 0; i < m->num_ordered_chapters; i++) {
3724 struct matroska_chapter *c = m->ordered_chapters + i;
3726 int j;
3727 for (j = 0; j < num_sources; j++) {
3728 if (!memcmp(c->segment_uid, uid_map[j], 16))
3729 goto found2;
3731 missing_time += c->end - c->start;
3732 continue;
3733 found2:;
3734 /* Only add a separate part if the time or file actually changes.
3735 * Matroska files have chapter divisions that are redundant from
3736 * timeline point of view because the same chapter structure is used
3737 * both to specify the timeline and for normal chapter information.
3738 * Removing a missing inserted external chapter can also cause this.
3739 * We allow for a configurable fudge factor because of files which
3740 * specify chapter end times that are one frame too early;
3741 * we don't want to try seeking over a one frame gap. */
3742 int64_t join_diff = c->start - starttime - prev_part_offset;
3743 if (part_count == 0 || FFABS(join_diff) > opts->chapter_merge_threshold
3744 || sources + j != timeline[part_count - 1].source) {
3745 timeline[part_count].source = sources + j;
3746 timeline[part_count].start = starttime / 1000.;
3747 timeline[part_count].source_start = c->start / 1000.;
3748 prev_part_offset = c->start - starttime;
3749 part_count++;
3750 } else if (part_count > 0 && join_diff) {
3751 /* Chapter was merged at an inexact boundary;
3752 * adjust timestamps to match. */
3753 mp_msg(MSGT_CPLAYER, MSGL_V, "Merging timeline part %d with "
3754 "offset %d ms.\n", i, (int) join_diff);
3755 starttime += join_diff;
3757 chapters[num_chapters].start = starttime / 1000.;
3758 chapters[num_chapters].name = talloc_strdup(chapters, c->name);
3759 starttime += c->end - c->start;
3760 num_chapters++;
3762 timeline[part_count].start = starttime / 1000.;
3764 if (!part_count) {
3765 // None of the parts come from the file itself???
3766 talloc_free(sources);
3767 talloc_free(timeline);
3768 talloc_free(chapters);
3769 return;
3772 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline contains %d parts from %d "
3773 "sources. Total length %.3f seconds.\n", part_count, num_sources,
3774 timeline[part_count].start);
3775 if (missing_time)
3776 mp_msg(MSGT_CPLAYER, MSGL_ERR, "There are %.3f seconds missing "
3777 "from the timeline!\n", missing_time / 1000.);
3778 mp_msg(MSGT_CPLAYER, MSGL_V, "Source files:\n");
3779 for (int i = 0; i < num_sources; i++)
3780 mp_msg(MSGT_CPLAYER, MSGL_V, "%d: %s\n", i,
3781 filename_recode(sources[i].demuxer->filename));
3782 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline parts: (number, start, "
3783 "source_start, source):\n");
3784 for (int i = 0; i < part_count; i++) {
3785 struct timeline_part *p = timeline + i;
3786 mp_msg(MSGT_CPLAYER, MSGL_V, "%3d %9.3f %9.3f %3td\n", i, p->start,
3787 p->source_start, p->source - sources);
3789 mp_msg(MSGT_CPLAYER, MSGL_V, "END %9.3f\n", timeline[part_count].start);
3790 mpctx->sources = sources;
3791 mpctx->num_sources = num_sources;
3792 mpctx->timeline = timeline;
3793 mpctx->num_timeline_parts = part_count;
3794 mpctx->num_chapters = num_chapters;
3795 mpctx->chapters = chapters;
3797 mpctx->timeline_part = 0;
3798 mpctx->demuxer = timeline[0].source->demuxer;
3802 static int read_keys(void *ctx, int fd)
3804 getch2(ctx);
3805 return mplayer_get_key(ctx, 0);
3808 static bool attachment_is_font(struct demux_attachment *att)
3810 if (!att->name || !att->type || !att->data || !att->data_size)
3811 return false;
3812 // match against MIME types
3813 if (strcmp(att->type, "application/x-truetype-font") == 0
3814 || strcmp(att->type, "application/x-font") == 0)
3815 return true;
3816 // fallback: match against file extension
3817 if (strlen(att->name) > 4) {
3818 char *ext = att->name + strlen(att->name) - 4;
3819 if (strcasecmp(ext, ".ttf") == 0 || strcasecmp(ext, ".ttc") == 0
3820 || strcasecmp(ext, ".otf") == 0)
3821 return true;
3823 return false;
3826 static int select_audio(demuxer_t *demuxer, int audio_id, char *audio_lang)
3828 if (audio_id == -1)
3829 audio_id = demuxer_audio_track_by_lang_and_default(demuxer, audio_lang);
3830 if (audio_id != -1) // -1 (automatic) is the default behaviour of demuxers
3831 demuxer_switch_audio(demuxer, audio_id);
3832 if (audio_id == -2) { // some demuxers don't yet know how to switch to no sound
3833 demuxer->audio->id = -2;
3834 demuxer->audio->sh = NULL;
3836 return demuxer->audio->id;
3839 static void print_version(const char* name)
3841 mp_msg(MSGT_CPLAYER, MSGL_INFO, MP_TITLE, name);
3843 /* Test for CPU capabilities (and corresponding OS support) for optimizing */
3844 GetCpuCaps(&gCpuCaps);
3845 #if ARCH_X86
3846 mp_msg(MSGT_CPLAYER, MSGL_V,
3847 "CPUflags: MMX: %d MMX2: %d 3DNow: %d 3DNowExt: %d SSE: %d SSE2: %d SSSE3: %d\n",
3848 gCpuCaps.hasMMX, gCpuCaps.hasMMX2,
3849 gCpuCaps.has3DNow, gCpuCaps.has3DNowExt,
3850 gCpuCaps.hasSSE, gCpuCaps.hasSSE2, gCpuCaps.hasSSSE3);
3851 #if CONFIG_RUNTIME_CPUDETECT
3852 mp_tmsg(MSGT_CPLAYER,MSGL_V, "Compiled with runtime CPU detection.\n");
3853 #else
3854 mp_tmsg(MSGT_CPLAYER,MSGL_V, "Compiled for x86 CPU with extensions:");
3855 if (HAVE_MMX)
3856 mp_msg(MSGT_CPLAYER,MSGL_V," MMX");
3857 if (HAVE_MMX2)
3858 mp_msg(MSGT_CPLAYER,MSGL_V," MMX2");
3859 if (HAVE_AMD3DNOW)
3860 mp_msg(MSGT_CPLAYER,MSGL_V," 3DNow");
3861 if (HAVE_AMD3DNOWEXT)
3862 mp_msg(MSGT_CPLAYER,MSGL_V," 3DNowExt");
3863 if (HAVE_SSE)
3864 mp_msg(MSGT_CPLAYER,MSGL_V," SSE");
3865 if (HAVE_SSE2)
3866 mp_msg(MSGT_CPLAYER,MSGL_V," SSE2");
3867 if (HAVE_SSSE3)
3868 mp_msg(MSGT_CPLAYER,MSGL_V," SSSE3");
3869 if (HAVE_CMOV)
3870 mp_msg(MSGT_CPLAYER,MSGL_V," CMOV");
3871 mp_msg(MSGT_CPLAYER,MSGL_V,"\n");
3872 #endif /* CONFIG_RUNTIME_CPUDETECT */
3873 #endif /* ARCH_X86 */
3876 /* This preprocessor directive is a hack to generate a mplayer-nomain.o object
3877 * file for some tools to link against. */
3878 #ifndef DISABLE_MAIN
3879 int main(int argc,char* argv[]){
3882 char * mem_ptr;
3884 // movie info:
3886 /* Flag indicating whether MPlayer should exit without playing anything. */
3887 int opt_exit = 0;
3888 int i;
3890 struct MPContext *mpctx = &(struct MPContext){
3891 .osd_function = OSD_PLAY,
3892 .begin_skip = MP_NOPTS_VALUE,
3893 .play_tree_step = 1,
3894 .global_sub_pos = -1,
3895 .set_of_sub_pos = -1,
3896 .file_format = DEMUXER_TYPE_UNKNOWN,
3897 .last_dvb_step = 1,
3900 InitTimer();
3901 srand(GetTimerMS());
3903 mp_msg_init();
3904 set_av_log_callback();
3906 #ifdef CONFIG_X11
3907 mpctx->x11_state = vo_x11_init_state();
3908 #endif
3909 struct MPOpts *opts = &mpctx->opts;
3910 set_default_mplayer_options(opts);
3911 // Create the config context and register the options
3912 mpctx->mconfig = m_config_new(opts, cfg_include);
3913 m_config_register_options(mpctx->mconfig,mplayer_opts);
3914 m_config_register_options(mpctx->mconfig, common_opts);
3915 mp_input_register_options(mpctx->mconfig);
3917 // Preparse the command line
3918 m_config_preparse_command_line(mpctx->mconfig,argc,argv);
3920 #if (defined(__MINGW32__) || defined(__CYGWIN__)) && defined(CONFIG_WIN32DLL)
3921 set_path_env();
3922 #endif
3924 #ifdef CONFIG_TV
3925 stream_tv_defaults.immediate = 1;
3926 #endif
3928 parse_cfgfiles(mpctx, mpctx->mconfig);
3930 mpctx->playtree = m_config_parse_mp_command_line(mpctx->mconfig, argc, argv);
3931 if(mpctx->playtree == NULL)
3932 opt_exit = 1;
3933 else {
3934 mpctx->playtree = play_tree_cleanup(mpctx->playtree);
3935 if(mpctx->playtree) {
3936 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,mpctx->mconfig);
3937 if(mpctx->playtree_iter) {
3938 if(play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
3939 play_tree_iter_free(mpctx->playtree_iter);
3940 mpctx->playtree_iter = NULL;
3942 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,1);
3946 mpctx->key_fifo = mp_fifo_create(opts);
3948 print_version("MPlayer");
3950 #if defined(__MINGW32__) || defined(__CYGWIN__)
3952 HMODULE kernel32 = GetModuleHandle("Kernel32.dll");
3953 BOOL WINAPI (*setDEP)(DWORD) = NULL;
3954 BOOL WINAPI (*setDllDir)(LPCTSTR) = NULL;
3955 if (kernel32) {
3956 setDEP = GetProcAddress(kernel32, "SetProcessDEPPolicy");
3957 setDllDir = GetProcAddress(kernel32, "SetDllDirectoryA");
3959 if (setDEP) setDEP(3);
3960 if (setDllDir) setDllDir("");
3962 // stop Windows from showing all kinds of annoying error dialogs
3963 SetErrorMode(0x8003);
3964 // request 1ms timer resolution
3965 timeBeginPeriod(1);
3966 #endif
3968 #ifdef CONFIG_PRIORITY
3969 set_priority();
3970 #endif
3972 if (codec_path)
3973 set_codec_path(codec_path);
3975 if(opts->video_driver_list && strcmp(opts->video_driver_list[0],"help")==0){
3976 list_video_out();
3977 opt_exit = 1;
3980 if(opts->audio_driver_list && strcmp(opts->audio_driver_list[0],"help")==0){
3981 list_audio_out();
3982 opt_exit = 1;
3985 /* Check codecs.conf. */
3986 if(!codecs_file || !parse_codec_cfg(codecs_file)){
3987 if(!parse_codec_cfg(mem_ptr=get_path("codecs.conf"))){
3988 if(!parse_codec_cfg(MPLAYER_CONFDIR "/codecs.conf")){
3989 if(!parse_codec_cfg(NULL)){
3990 exit_player_with_rc(mpctx, EXIT_NONE, 0);
3992 mp_tmsg(MSGT_CPLAYER,MSGL_V,"Using built-in default codecs.conf.\n");
3995 free( mem_ptr ); // release the buffer created by get_path()
3998 if(audio_codec_list && strcmp(audio_codec_list[0],"help")==0){
3999 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available audio codecs:\n");
4000 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AUDIO_CODECS\n");
4001 list_codecs(1);
4002 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4003 opt_exit = 1;
4005 if(video_codec_list && strcmp(video_codec_list[0],"help")==0){
4006 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available video codecs:\n");
4007 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODECS\n");
4008 list_codecs(0);
4009 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4010 opt_exit = 1;
4012 if(video_fm_list && strcmp(video_fm_list[0],"help")==0){
4013 vfm_help();
4014 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4015 opt_exit = 1;
4017 if(audio_fm_list && strcmp(audio_fm_list[0],"help")==0){
4018 afm_help();
4019 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4020 opt_exit = 1;
4022 if(af_cfg.list && strcmp(af_cfg.list[0],"help")==0){
4023 af_help();
4024 printf("\n");
4025 opt_exit = 1;
4027 #ifdef CONFIG_X11
4028 if(vo_fstype_list && strcmp(vo_fstype_list[0],"help")==0){
4029 fstype_help();
4030 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4031 opt_exit = 1;
4033 #endif
4034 if((opts->demuxer_name && strcmp(opts->demuxer_name,"help")==0) ||
4035 (opts->audio_demuxer_name && strcmp(opts->audio_demuxer_name,"help")==0) ||
4036 (opts->sub_demuxer_name && strcmp(opts->sub_demuxer_name,"help")==0)){
4037 demuxer_help();
4038 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
4039 opt_exit = 1;
4041 if (opts->list_properties) {
4042 property_print_help();
4043 opt_exit = 1;
4046 if(opt_exit)
4047 exit_player(mpctx, EXIT_NONE);
4049 if (!mpctx->filename && !opts->player_idle_mode) {
4050 // no file/vcd/dvd -> show HELP:
4051 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", mp_gtext(help_text));
4052 exit_player_with_rc(mpctx, EXIT_NONE, 0);
4055 /* Display what configure line was used */
4056 mp_msg(MSGT_CPLAYER, MSGL_V, "Configuration: " CONFIGURATION "\n");
4058 // Many users forget to include command line in bugreports...
4059 if( mp_msg_test(MSGT_CPLAYER,MSGL_V) ){
4060 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "CommandLine:");
4061 for(i=1;i<argc;i++)mp_msg(MSGT_CPLAYER, MSGL_INFO," '%s'",argv[i]);
4062 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
4065 //------ load global data first ------
4067 mpctx->osd = osd_create();
4069 // check font
4070 #ifdef CONFIG_FREETYPE
4071 init_freetype();
4072 #endif
4073 #ifdef CONFIG_FONTCONFIG
4074 if(font_fontconfig <= 0)
4076 #endif
4077 #ifdef CONFIG_BITMAP_FONT
4078 if(font_name){
4079 vo_font=read_font_desc(font_name,font_factor,verbose>1);
4080 if(!vo_font) mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load bitmap font: %s\n",
4081 filename_recode(font_name));
4082 } else {
4083 // try default:
4084 vo_font=read_font_desc( mem_ptr=get_path("font/font.desc"),font_factor,verbose>1);
4085 free(mem_ptr); // release the buffer created by get_path()
4086 if(!vo_font)
4087 vo_font=read_font_desc(MPLAYER_DATADIR "/font/font.desc",font_factor,verbose>1);
4089 if (sub_font_name)
4090 mpctx->osd->sub_font = read_font_desc(sub_font_name, font_factor, verbose>1);
4091 else
4092 mpctx->osd->sub_font = vo_font;
4093 #endif
4094 #ifdef CONFIG_FONTCONFIG
4096 #endif
4098 #ifdef CONFIG_ASS
4099 ass_library = ass_init();
4100 #endif
4102 #ifdef HAVE_RTC
4103 if(opts->rtc)
4105 char *rtc_device = opts->rtc_device;
4106 // seteuid(0); /* Can't hurt to try to get root here */
4107 if ((rtc_fd = open(rtc_device ? rtc_device : "/dev/rtc", O_RDONLY)) < 0)
4108 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Failed to open %s: %s (it should be readable by the user.)\n",
4109 rtc_device ? rtc_device : "/dev/rtc", strerror(errno));
4110 else {
4111 unsigned long irqp = 1024; /* 512 seemed OK. 128 is jerky. */
4113 if (ioctl(rtc_fd, RTC_IRQP_SET, irqp) < 0) {
4114 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Linux RTC init error in ioctl (rtc_irqp_set %lu): %s\n", irqp, strerror(errno));
4115 mp_tmsg(MSGT_CPLAYER, MSGL_HINT, "Try adding \"echo %lu > /proc/sys/dev/rtc/max-user-freq\" to your system startup scripts.\n", irqp);
4116 close (rtc_fd);
4117 rtc_fd = -1;
4118 } else if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
4119 /* variable only by the root */
4120 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC init error in ioctl (rtc_pie_on): %s\n", strerror(errno));
4121 close (rtc_fd);
4122 rtc_fd = -1;
4123 } else
4124 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Using Linux hardware RTC timing (%ldHz).\n", irqp);
4127 if(rtc_fd<0)
4128 #endif /* HAVE_RTC */
4129 mp_msg(MSGT_CPLAYER, MSGL_V, "Using %s timing\n",
4130 opts->softsleep ? "software" : timer_name);
4132 #ifdef HAVE_TERMCAP
4133 load_termcap(NULL); // load key-codes
4134 #endif
4136 // ========== Init keyboard FIFO (connection to libvo) ============
4138 // Init input system
4139 current_module = "init_input";
4140 mpctx->input = mp_input_init(&opts->input);
4141 mp_input_add_key_fd(mpctx->input, -1,0,mplayer_get_key,NULL, mpctx->key_fifo);
4142 if(slave_mode)
4143 mp_input_add_cmd_fd(mpctx->input, 0,USE_SELECT,MP_INPUT_SLAVE_CMD_FUNC,NULL);
4144 else if (opts->consolecontrols)
4145 mp_input_add_key_fd(mpctx->input, 0, 1, read_keys, NULL, mpctx->key_fifo);
4146 // Set the libstream interrupt callback
4147 stream_set_interrupt_callback(mp_input_check_interrupt, mpctx->input);
4149 #ifdef CONFIG_MENU
4150 if(use_menu) {
4151 if(menu_cfg && menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
4152 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
4153 else {
4154 menu_cfg = get_path("menu.conf");
4155 if(menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
4156 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
4157 else {
4158 if(menu_init(mpctx, mpctx->mconfig, mpctx->input,
4159 MPLAYER_CONFDIR "/menu.conf"))
4160 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", MPLAYER_CONFDIR"/menu.conf");
4161 else {
4162 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Menu init failed.\n");
4163 use_menu = 0;
4168 #endif
4170 current_module = NULL;
4172 /// Catch signals
4173 #ifndef __MINGW32__
4174 signal(SIGCHLD,child_sighandler);
4175 #endif
4177 #ifdef CONFIG_CRASH_DEBUG
4178 prog_path = argv[0];
4179 #endif
4180 //========= Catch terminate signals: ================
4181 // terminate requests:
4182 signal(SIGTERM,exit_sighandler); // kill
4183 signal(SIGHUP,exit_sighandler); // kill -HUP / xterm closed
4185 signal(SIGINT,exit_sighandler); // Interrupt from keyboard
4187 signal(SIGQUIT,exit_sighandler); // Quit from keyboard
4188 signal(SIGPIPE,exit_sighandler); // Some window managers cause this
4189 #ifdef CONFIG_SIGHANDLER
4190 // fatal errors:
4191 signal(SIGBUS,exit_sighandler); // bus error
4192 signal(SIGSEGV,exit_sighandler); // segfault
4193 signal(SIGILL,exit_sighandler); // illegal instruction
4194 signal(SIGFPE,exit_sighandler); // floating point exc.
4195 signal(SIGABRT,exit_sighandler); // abort()
4196 #ifdef CONFIG_CRASH_DEBUG
4197 if (crash_debug)
4198 signal(SIGTRAP,exit_sighandler);
4199 #endif
4200 #endif
4202 // ******************* Now, let's see the per-file stuff ********************
4204 play_next_file:
4206 // init global sub numbers
4207 mpctx->global_sub_size = 0;
4208 memset(mpctx->sub_counts, 0, sizeof(mpctx->sub_counts));
4210 if (mpctx->filename) {
4211 load_per_protocol_config (mpctx->mconfig, mpctx->filename);
4212 load_per_extension_config (mpctx->mconfig, mpctx->filename);
4213 load_per_file_config (mpctx->mconfig, mpctx->filename);
4216 if (opts->video_driver_list)
4217 load_per_output_config (mpctx->mconfig, PROFILE_CFG_VO, opts->video_driver_list[0]);
4218 if (opts->audio_driver_list)
4219 load_per_output_config (mpctx->mconfig, PROFILE_CFG_AO, opts->audio_driver_list[0]);
4221 // We must enable getch2 here to be able to interrupt network connection
4222 // or cache filling
4223 if (opts->consolecontrols && !slave_mode) {
4224 if(mpctx->initialized_flags&INITIALIZED_GETCH2)
4225 mp_tmsg(MSGT_CPLAYER,MSGL_WARN,"WARNING: getch2_init called twice!\n");
4226 else
4227 getch2_enable(); // prepare stdin for hotkeys...
4228 mpctx->initialized_flags|=INITIALIZED_GETCH2;
4229 mp_msg(MSGT_CPLAYER,MSGL_DBG2,"\n[[[init getch2]]]\n");
4232 // =================== GUI idle loop (STOP state) ===========================
4233 while (opts->player_idle_mode && !mpctx->filename) {
4234 play_tree_t * entry = NULL;
4235 mp_cmd_t * cmd;
4236 if (mpctx->video_out && mpctx->video_out->config_ok)
4237 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
4238 while (!(cmd = mp_input_get_cmd(mpctx->input, 0, 0))) { // wait for command
4239 if (mpctx->video_out)
4240 vo_check_events(mpctx->video_out);
4241 usec_sleep(20000);
4243 switch (cmd->id) {
4244 case MP_CMD_LOADFILE:
4245 // prepare a tree entry with the new filename
4246 entry = play_tree_new();
4247 play_tree_add_file(entry, cmd->args[0].v.s);
4248 // The entry is added to the main playtree after the switch().
4249 break;
4250 case MP_CMD_LOADLIST:
4251 entry = parse_playlist_file(mpctx->mconfig, cmd->args[0].v.s);
4252 break;
4253 case MP_CMD_QUIT:
4254 exit_player_with_rc(mpctx, EXIT_QUIT, (cmd->nargs > 0)? cmd->args[0].v.i : 0);
4255 break;
4256 case MP_CMD_VO_FULLSCREEN:
4257 case MP_CMD_GET_PROPERTY:
4258 case MP_CMD_SET_PROPERTY:
4259 case MP_CMD_STEP_PROPERTY:
4260 run_command(mpctx, cmd);
4261 break;
4264 mp_cmd_free(cmd);
4266 if (entry) { // user entered a command that gave a valid entry
4267 if (mpctx->playtree) // the playtree is always a node with one child. let's clear it
4268 play_tree_free_list(mpctx->playtree->child, 1);
4269 else mpctx->playtree=play_tree_new(); // .. or make a brand new playtree
4271 if (!mpctx->playtree) continue; // couldn't make playtree! wait for next command
4273 play_tree_set_child(mpctx->playtree, entry);
4275 /* Make iterator start at the top the of tree. */
4276 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree, mpctx->mconfig);
4277 if (!mpctx->playtree_iter) continue;
4279 // find the first real item in the tree
4280 if (play_tree_iter_step(mpctx->playtree_iter,0,0) != PLAY_TREE_ITER_ENTRY) {
4281 // no items!
4282 play_tree_iter_free(mpctx->playtree_iter);
4283 mpctx->playtree_iter = NULL;
4284 continue; // wait for next command
4286 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, 1);
4289 //---------------------------------------------------------------------------
4291 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
4292 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL);
4294 if (mpctx->filename) {
4295 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"\nPlaying %s.\n",
4296 filename_recode(mpctx->filename));
4297 if(use_filename_title && opts->vo_wintitle == NULL)
4298 opts->vo_wintitle = strdup(mp_basename(mpctx->filename));
4301 if (edl_filename) {
4302 if (edl_records) free_edl(edl_records);
4303 next_edl_record = edl_records = edl_parse_file();
4305 if (edl_output_filename) {
4306 if (edl_fd) fclose(edl_fd);
4307 if ((edl_fd = fopen(edl_output_filename, "w")) == NULL)
4309 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Can't open EDL file [%s] for writing.\n",
4310 filename_recode(edl_output_filename));
4314 //==================== Open VOB-Sub ============================
4316 current_module="vobsub";
4317 if (vobsub_name){
4318 vo_vobsub=vobsub_open(vobsub_name,spudec_ifo,1,&vo_spudec);
4319 if(vo_vobsub==NULL)
4320 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Cannot load subtitles: %s\n",
4321 filename_recode(vobsub_name));
4322 } else if (sub_auto && mpctx->filename){
4323 /* try to autodetect vobsub from movie filename ::atmos */
4324 char *buf = strdup(mpctx->filename), *psub;
4325 char *pdot = strrchr(buf, '.');
4326 char *pslash = strrchr(buf, '/');
4327 #if defined(__MINGW32__) || defined(__CYGWIN__)
4328 if (!pslash) pslash = strrchr(buf, '\\');
4329 #endif
4330 if (pdot && (!pslash || pdot > pslash))
4331 *pdot = '\0';
4332 vo_vobsub=vobsub_open(buf,spudec_ifo,0,&vo_spudec);
4333 /* try from ~/.mplayer/sub */
4334 if(!vo_vobsub && (psub = get_path( "sub/" ))) {
4335 const char *bname = mp_basename(buf);
4336 int l;
4337 l = strlen(psub) + strlen(bname) + 1;
4338 psub = realloc(psub,l);
4339 strcat(psub,bname);
4340 vo_vobsub=vobsub_open(psub,spudec_ifo,0,&vo_spudec);
4341 free(psub);
4343 free(buf);
4345 if(vo_vobsub){
4346 mpctx->initialized_flags|=INITIALIZED_VOBSUB;
4347 vobsub_set_from_lang(vo_vobsub, opts->sub_lang);
4348 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only, mpctx);
4350 // setup global sub numbering
4351 mpctx->sub_counts[SUB_SOURCE_VOBSUB] = vobsub_get_indexes_count(vo_vobsub);
4354 //============ Open & Sync STREAM --- fork cache2 ====================
4356 mpctx->stream=NULL;
4357 mpctx->demuxer=NULL;
4358 if (mpctx->d_audio) {
4359 //free_demuxer_stream(mpctx->d_audio);
4360 mpctx->d_audio=NULL;
4362 if (mpctx->d_video) {
4363 //free_demuxer_stream(d_video);
4364 mpctx->d_video=NULL;
4366 mpctx->sh_audio=NULL;
4367 mpctx->sh_video=NULL;
4369 current_module="open_stream";
4370 mpctx->stream = open_stream(mpctx->filename, opts, &mpctx->file_format);
4371 if(!mpctx->stream) { // error...
4372 mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY);
4373 goto goto_next_file;
4375 mpctx->initialized_flags|=INITIALIZED_STREAM;
4377 if(mpctx->file_format == DEMUXER_TYPE_PLAYLIST) {
4378 mp_msg(MSGT_CPLAYER, MSGL_ERR, "\nThis looks like a playlist, but "
4379 "playlist support will not be used automatically.\n"
4380 "MPlayer's playlist code is unsafe and should only be used with "
4381 "trusted sources.\nPlayback will probably fail.\n\n");
4382 #if 0
4383 play_tree_t* entry;
4384 // Handle playlist
4385 current_module="handle_playlist";
4386 mp_msg(MSGT_CPLAYER,MSGL_V,"Parsing playlist %s...\n",
4387 filename_recode(mpctx->filename));
4388 entry = parse_playtree(mpctx->stream, mpctx->mconfig, 0);
4389 mpctx->eof=playtree_add_playlist(mpctx, entry);
4390 goto goto_next_file;
4391 #endif
4393 mpctx->stream->start_pos+=seek_to_byte;
4395 if(stream_dump_type==5){
4396 unsigned char buf[4096];
4397 int len;
4398 FILE *f;
4399 current_module="dumpstream";
4400 stream_reset(mpctx->stream);
4401 stream_seek(mpctx->stream,mpctx->stream->start_pos);
4402 f=fopen(opts->stream_dump_name,"wb");
4403 if(!f){
4404 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
4405 exit_player(mpctx, EXIT_ERROR);
4407 if (opts->chapterrange[0] > 1) {
4408 int chapter = opts->chapterrange[0] - 1;
4409 stream_control(mpctx->stream, STREAM_CTRL_SEEK_TO_CHAPTER, &chapter);
4411 while(!mpctx->stream->eof && !async_quit_request){
4412 len=stream_read(mpctx->stream,buf,4096);
4413 if(len>0) {
4414 if(fwrite(buf,len,1,f) != 1) {
4415 mp_tmsg(MSGT_MENCODER,MSGL_FATAL,"%s: Error writing file.\n",opts->stream_dump_name);
4416 exit_player(mpctx, EXIT_ERROR);
4419 if (opts->chapterrange[1] > 0) {
4420 int chapter = -1;
4421 if (stream_control(mpctx->stream, STREAM_CTRL_GET_CURRENT_CHAPTER,
4422 &chapter) == STREAM_OK
4423 && chapter + 1 > opts->chapterrange[1])
4424 break;
4427 if(fclose(f)) {
4428 mp_tmsg(MSGT_MENCODER,MSGL_FATAL,"%s: Error writing file.\n",opts->stream_dump_name);
4429 exit_player(mpctx, EXIT_ERROR);
4431 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Core dumped ;)\n");
4432 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4435 #ifdef CONFIG_DVDREAD
4436 if(mpctx->stream->type==STREAMTYPE_DVD){
4437 current_module="dvd lang->id";
4438 if(opts->audio_lang && opts->audio_id==-1) opts->audio_id=dvd_aid_from_lang(mpctx->stream,opts->audio_lang);
4439 if(opts->sub_lang && opts->sub_id==-1) opts->sub_id=dvd_sid_from_lang(mpctx->stream,opts->sub_lang);
4440 // setup global sub numbering
4441 mpctx->sub_counts[SUB_SOURCE_DEMUX] = dvd_number_of_subs(mpctx->stream);
4442 current_module=NULL;
4444 #endif
4446 #ifdef CONFIG_DVDNAV
4447 if(mpctx->stream->type==STREAMTYPE_DVDNAV){
4448 current_module="dvdnav lang->id";
4449 if(opts->audio_lang && opts->audio_id==-1) opts->audio_id=mp_dvdnav_aid_from_lang(mpctx->stream,opts->audio_lang);
4450 dvdsub_lang_id = -3;
4451 if(opts->sub_lang && opts->sub_id==-1)
4452 dvdsub_lang_id = opts->sub_id = mp_dvdnav_sid_from_lang(mpctx->stream,opts->sub_lang);
4453 // setup global sub numbering
4454 mpctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(mpctx->stream);
4455 current_module=NULL;
4457 #endif
4459 // CACHE2: initial prefill: 20% later: 5% (should be set by -cacheopts)
4460 goto_enable_cache:
4461 if(stream_cache_size>0){
4462 int res;
4463 float stream_cache_min_percent = opts->stream_cache_min_percent;
4464 float stream_cache_seek_min_percent = opts->stream_cache_seek_min_percent;
4465 current_module="enable_cache";
4466 res = stream_enable_cache(mpctx->stream,stream_cache_size*1024,
4467 stream_cache_size*1024*(stream_cache_min_percent / 100.0),
4468 stream_cache_size*1024*(stream_cache_seek_min_percent / 100.0));
4469 if(res == 0)
4470 if((mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY))) goto goto_next_file;
4473 //============ Open DEMUXERS --- DETECT file type =======================
4474 current_module="demux_open";
4476 mpctx->demuxer=demux_open(opts, mpctx->stream,mpctx->file_format,opts->audio_id,opts->video_id,opts->sub_id,mpctx->filename);
4478 // HACK to get MOV Reference Files working
4480 if (mpctx->demuxer && mpctx->demuxer->type==DEMUXER_TYPE_PLAYLIST)
4482 unsigned char* playlist_entry;
4483 play_tree_t *list = NULL, *entry = NULL;
4485 current_module="handle_demux_playlist";
4486 while (ds_get_packet(mpctx->demuxer->video,&playlist_entry)>0)
4488 char *temp;
4489 const char *bname;
4491 mp_msg(MSGT_CPLAYER,MSGL_V,"Adding file %s to element entry.\n",
4492 filename_recode(playlist_entry));
4494 bname=mp_basename(playlist_entry);
4495 if ((strlen(bname)>10) && !strncmp(bname,"qt",2) && !strncmp(bname+3,"gateQT",6))
4496 continue;
4498 if (!strcmp(playlist_entry, mpctx->filename)) // ignoring self-reference
4499 continue;
4501 entry = play_tree_new();
4503 if (mpctx->filename && !strcmp(mp_basename(playlist_entry),playlist_entry)) // add reference path of current file
4505 temp=malloc((strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))+strlen(playlist_entry)+1));
4506 if (temp)
4508 strncpy(temp, mpctx->filename, strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename)));
4509 temp[strlen(mpctx->filename)-strlen(mp_basename(mpctx->filename))]='\0';
4510 strcat(temp, playlist_entry);
4511 if (!strcmp(temp, mpctx->filename)) {
4512 free(temp);
4513 continue;
4515 play_tree_add_file(entry,temp);
4516 mp_msg(MSGT_CPLAYER,MSGL_V,"Resolving reference to %s.\n",temp);
4517 free(temp);
4520 else
4521 play_tree_add_file(entry,playlist_entry);
4523 if(!list)
4524 list = entry;
4525 else
4526 play_tree_append_entry(list,entry);
4528 free_demuxer(mpctx->demuxer);
4529 mpctx->demuxer = NULL;
4531 if (list)
4533 entry = play_tree_new();
4534 play_tree_set_child(entry,list);
4535 mpctx->stop_play = playtree_add_playlist(mpctx, entry);
4536 goto goto_next_file;
4540 if(!mpctx->demuxer) {
4541 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Failed to recognize file format.\n");
4542 goto goto_next_file;
4545 if (mpctx->demuxer->matroska_data.ordered_chapters)
4546 build_ordered_chapter_timeline(mpctx);
4548 if (!mpctx->sources) {
4549 mpctx->sources = talloc_ptrtype(NULL, mpctx->sources);
4550 *mpctx->sources = (struct content_source){.stream = mpctx->stream,
4551 .demuxer = mpctx->demuxer};
4552 mpctx->num_sources = 1;
4555 mpctx->initialized_flags|=INITIALIZED_DEMUXER;
4557 #ifdef CONFIG_ASS
4558 if (opts->ass_enabled && ass_library) {
4559 for (int j = 0; j < mpctx->num_sources; j++) {
4560 struct demuxer *d = mpctx->sources[j].demuxer;
4561 for (int i = 0; i < d->num_attachments; i++) {
4562 struct demux_attachment *att = d->attachments + i;
4563 if (use_embedded_fonts && attachment_is_font(att))
4564 ass_add_font(ass_library, att->name, att->data, att->data_size);
4568 #endif
4570 current_module="demux_open2";
4572 mpctx->d_audio=mpctx->demuxer->audio;
4573 mpctx->d_video=mpctx->demuxer->video;
4574 mpctx->d_sub=mpctx->demuxer->sub;
4576 if (ts_prog) {
4577 int tmp = ts_prog;
4578 mp_property_do("switch_program", M_PROPERTY_SET, &tmp, mpctx);
4580 // select audio stream
4581 if (mpctx->num_sources)
4582 for (int i = 0; i < mpctx->num_sources; i++)
4583 select_audio(mpctx->sources[i].demuxer, opts->audio_id,
4584 opts->audio_lang);
4585 else
4586 select_audio(mpctx->d_audio->demuxer, opts->audio_id, opts->audio_lang);
4588 // DUMP STREAMS:
4589 if((stream_dump_type)&&(stream_dump_type<4)){
4590 FILE *f;
4591 demux_stream_t *ds=NULL;
4592 current_module="dump";
4593 // select stream to dump
4594 switch(stream_dump_type){
4595 case 1: ds=mpctx->d_audio;break;
4596 case 2: ds=mpctx->d_video;break;
4597 case 3: ds=mpctx->d_sub;break;
4599 if(!ds){
4600 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"dump: FATAL: Selected stream missing!\n");
4601 exit_player(mpctx, EXIT_ERROR);
4603 // disable other streams:
4604 if(mpctx->d_audio && mpctx->d_audio!=ds) {ds_free_packs(mpctx->d_audio); mpctx->d_audio->id=-2; }
4605 if(mpctx->d_video && mpctx->d_video!=ds) {ds_free_packs(mpctx->d_video); mpctx->d_video->id=-2; }
4606 if(mpctx->d_sub && mpctx->d_sub!=ds) {ds_free_packs(mpctx->d_sub); mpctx->d_sub->id=-2; }
4607 // let's dump it!
4608 f=fopen(opts->stream_dump_name,"wb");
4609 if(!f){
4610 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL,"Cannot open dump file.\n");
4611 exit_player(mpctx, EXIT_ERROR);
4613 while(!ds->eof){
4614 unsigned char* start;
4615 int in_size=ds_get_packet(ds,&start);
4616 if( (mpctx->demuxer->file_format==DEMUXER_TYPE_AVI || mpctx->demuxer->file_format==DEMUXER_TYPE_ASF || mpctx->demuxer->file_format==DEMUXER_TYPE_MOV)
4617 && stream_dump_type==2) fwrite(&in_size,1,4,f);
4618 if(in_size>0) fwrite(start,in_size,1,f);
4619 if (opts->chapterrange[1] > 0) {
4620 int cur_chapter = demuxer_get_current_chapter(mpctx->demuxer, 0);
4621 if(cur_chapter!=-1 && cur_chapter+1 > opts->chapterrange[1])
4622 break;
4625 fclose(f);
4626 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Core dumped ;)\n");
4627 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4630 mpctx->sh_audio=mpctx->d_audio->sh;
4631 mpctx->sh_video=mpctx->d_video->sh;
4633 if(mpctx->sh_video){
4635 current_module="video_read_properties";
4636 if(!video_read_properties(mpctx->sh_video)) {
4637 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"Video: Cannot read properties.\n");
4638 mpctx->sh_video=mpctx->d_video->sh=NULL;
4639 } else {
4640 mp_tmsg(MSGT_CPLAYER,MSGL_V,"[V] filefmt:%d fourcc:0x%X size:%dx%d fps:%5.3f ftime:=%6.4f\n",
4641 mpctx->demuxer->file_format,mpctx->sh_video->format, mpctx->sh_video->disp_w,mpctx->sh_video->disp_h,
4642 mpctx->sh_video->fps,mpctx->sh_video->frametime
4645 /* need to set fps here for output encoders to pick it up in their init */
4646 if(force_fps){
4647 mpctx->sh_video->fps=force_fps;
4648 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
4650 vo_fps = mpctx->sh_video->fps;
4652 if(!mpctx->sh_video->fps && !force_fps){
4653 mp_tmsg(MSGT_CPLAYER,MSGL_ERR,"FPS not specified in the header or invalid, use the -fps option.\n");
4654 mpctx->opts.correct_pts = 1;
4660 if(!mpctx->sh_video && !mpctx->sh_audio){
4661 mp_tmsg(MSGT_CPLAYER,MSGL_FATAL, "No stream found.\n");
4662 #ifdef CONFIG_DVBIN
4663 if(mpctx->stream->type == STREAMTYPE_DVB)
4665 int dir;
4666 int v = mpctx->last_dvb_step;
4667 if(v > 0)
4668 dir = DVB_CHANNEL_HIGHER;
4669 else
4670 dir = DVB_CHANNEL_LOWER;
4672 if(dvb_step_channel(mpctx->stream, dir)) {
4673 mpctx->stop_play = PT_NEXT_ENTRY;
4674 mpctx->dvbin_reopen = 1;
4677 #endif
4678 goto goto_next_file; // exit_player(_("Fatal error"));
4681 /* display clip info */
4682 demux_info_print(mpctx->demuxer);
4684 //================== Read SUBTITLES (DVD & TEXT) ==========================
4685 if(vo_spudec==NULL &&
4686 (mpctx->stream->type==STREAMTYPE_DVD || mpctx->stream->type == STREAMTYPE_DVDNAV)){
4687 init_vo_spudec(mpctx);
4690 // after reading video params we should load subtitles because
4691 // we know fps so now we can adjust subtitle time to ~6 seconds AST
4692 // check .sub
4693 current_module="read_subtitles_file";
4694 double sub_fps = mpctx->sh_video ? mpctx->sh_video->fps : 25;
4695 if(sub_name){
4696 for (i = 0; sub_name[i] != NULL; ++i)
4697 add_subtitles(mpctx, sub_name[i], sub_fps, 0);
4699 if(sub_auto) { // auto load sub file ...
4700 char *psub = get_path( "sub/" );
4701 char **tmp = sub_filenames((psub ? psub : ""), mpctx->filename);
4702 int i = 0;
4703 free(psub); // release the buffer created by get_path() above
4704 while (tmp[i]) {
4705 add_subtitles(mpctx, tmp[i], sub_fps, 1);
4706 free(tmp[i++]);
4708 free(tmp);
4710 if (mpctx->set_of_sub_size > 0)
4711 mpctx->sub_counts[SUB_SOURCE_SUBS] = mpctx->set_of_sub_size;
4713 if (select_subtitle(mpctx)) {
4714 if(mpctx->subdata)
4715 switch (stream_dump_type) {
4716 case 3: list_sub_file(mpctx->subdata); break;
4717 case 4: dump_mpsub(mpctx->subdata, mpctx->sh_video->fps); break;
4718 case 6: dump_srt(mpctx->subdata, mpctx->sh_video->fps); break;
4719 case 7: dump_microdvd(mpctx->subdata, mpctx->sh_video->fps); break;
4720 case 8: dump_jacosub(mpctx->subdata, mpctx->sh_video->fps); break;
4721 case 9: dump_sami(mpctx->subdata, mpctx->sh_video->fps); break;
4725 print_file_properties(mpctx, mpctx->filename);
4727 if(!mpctx->sh_video) goto main; // audio-only
4729 if(!reinit_video_chain(mpctx)) {
4730 if(!mpctx->sh_video){
4731 if(!mpctx->sh_audio) goto goto_next_file;
4732 goto main; // exit_player(_("Fatal error"));
4736 if(mpctx->sh_video->output_flags & 0x08 && vo_spudec)
4737 spudec_set_hw_spu(vo_spudec,mpctx->video_out);
4739 #ifdef CONFIG_FREETYPE
4740 force_load_font = 1;
4741 #endif
4743 //================== MAIN: ==========================
4744 main:
4745 current_module="main";
4747 if (opts->playing_msg) {
4748 char* msg = property_expand_string(mpctx, opts->playing_msg);
4749 mp_msg(MSGT_CPLAYER,MSGL_INFO,"%s",msg);
4750 free(msg);
4754 // Disable the term OSD in verbose mode
4755 if (verbose)
4756 opts->term_osd = 0;
4760 // Make sure old OSD does not stay around,
4761 // e.g. with -fixed-vo and same-resolution files
4762 clear_osd_msgs();
4763 update_osd_msg(mpctx);
4765 //================ SETUP AUDIO ==========================
4767 if(mpctx->sh_audio){
4768 reinit_audio_chain(mpctx);
4769 if (mpctx->sh_audio && mpctx->sh_audio->codec)
4770 mp_msg(MSGT_IDENTIFY,MSGL_INFO, "ID_AUDIO_CODEC=%s\n", mpctx->sh_audio->codec->name);
4773 current_module="av_init";
4775 if(mpctx->sh_video){
4776 mpctx->sh_video->timer=0;
4777 if (! ignore_start)
4778 audio_delay += mpctx->sh_video->stream_delay;
4780 if(mpctx->sh_audio){
4781 if (start_volume >= 0)
4782 mixer_setvolume(&mpctx->mixer, start_volume, start_volume);
4783 if (! ignore_start)
4784 audio_delay -= mpctx->sh_audio->stream_delay;
4785 mpctx->delay=-audio_delay;
4788 if(!mpctx->sh_audio){
4789 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Audio: no sound\n");
4790 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused audio chunks.\n",mpctx->d_audio->packs);
4791 ds_free_packs(mpctx->d_audio); // free buffered chunks
4792 //mpctx->d_audio->id=-2; // do not read audio chunks
4793 //uninit_player(mpctx, INITIALIZED_AO); // close device
4795 if(!mpctx->sh_video){
4796 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Video: no video\n");
4797 mp_msg(MSGT_CPLAYER,MSGL_V,"Freeing %d unused video chunks.\n",mpctx->d_video->packs);
4798 ds_free_packs(mpctx->d_video);
4799 mpctx->d_video->id=-2;
4800 //if(!fixed_vo) uninit_player(mpctx, INITIALIZED_VO);
4803 if (!mpctx->sh_video && !mpctx->sh_audio)
4804 goto goto_next_file;
4806 //if(demuxer->file_format!=DEMUXER_TYPE_AVI) pts_from_bps=0; // it must be 0 for mpeg/asf!
4807 if(force_fps && mpctx->sh_video){
4808 vo_fps = mpctx->sh_video->fps=force_fps;
4809 mpctx->sh_video->frametime=1.0f/mpctx->sh_video->fps;
4810 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"FPS forced to be %5.3f (ftime: %5.3f).\n",mpctx->sh_video->fps,mpctx->sh_video->frametime);
4813 mp_input_set_section(mpctx->input, NULL);
4814 //TODO: add desired (stream-based) sections here
4815 if (mpctx->stream->type==STREAMTYPE_TV) mp_input_set_section(mpctx->input, "tv");
4816 if (mpctx->stream->type==STREAMTYPE_DVDNAV) mp_input_set_section(mpctx->input, "dvdnav");
4818 //==================== START PLAYING =======================
4820 if(opts->loop_times>1) opts->loop_times--; else
4821 if(opts->loop_times==1) opts->loop_times = -1;
4823 mp_tmsg(MSGT_CPLAYER,MSGL_INFO,"Starting playback...\n");
4825 total_time_usage_start=GetTimer();
4826 audio_time_usage=0; video_time_usage=0; vout_time_usage=0;
4827 total_frame_cnt=0; drop_frame_cnt=0; // fix for multifile fps benchmark
4828 play_n_frames=play_n_frames_mf;
4830 if(play_n_frames==0){
4831 mpctx->stop_play=PT_NEXT_ENTRY; goto goto_next_file;
4834 mpctx->time_frame = 0;
4835 mpctx->drop_message_shown = 0;
4836 mpctx->restart_playback = true;
4837 mpctx->video_pts = 0;
4838 mpctx->hrseek_active = false;
4839 mpctx->hrseek_framedrop = false;
4840 mpctx->step_frames = 0;
4841 mpctx->total_avsync_change = 0;
4842 mpctx->last_chapter_seek = -1;
4844 // If there's a timeline force an absolute seek to initialize state
4845 if (seek_to_sec || mpctx->timeline) {
4846 queue_seek(mpctx, MPSEEK_ABSOLUTE, seek_to_sec, 0);
4847 seek(mpctx, mpctx->seek);
4848 end_at.pos += seek_to_sec;
4850 if (opts->chapterrange[0] > 0) {
4851 double pts;
4852 if (seek_chapter(mpctx, opts->chapterrange[0]-1, &pts, NULL) >= 0
4853 && pts > -1.0) {
4854 queue_seek(mpctx, MPSEEK_ABSOLUTE, pts, 0);
4855 seek(mpctx, mpctx->seek);
4859 if (end_at.type == END_AT_SIZE) {
4860 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Option -endpos in MPlayer does not yet support size units.\n");
4861 end_at.type = END_AT_NONE;
4864 #ifdef CONFIG_DVDNAV
4865 mp_dvdnav_context_free(mpctx);
4866 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4867 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
4868 mp_dvdnav_cell_has_changed(mpctx->stream,1);
4870 #endif
4872 mpctx->seek = (struct seek_params){0};
4873 get_relative_time(mpctx); // reset current delta
4874 // Make sure VO knows current pause state
4875 if (mpctx->sh_video)
4876 vo_control(mpctx->video_out, mpctx->paused ? VOCTRL_PAUSE : VOCTRL_RESUME,
4877 NULL);
4879 while (!mpctx->stop_play)
4880 run_playloop(mpctx);
4882 mp_msg(MSGT_GLOBAL,MSGL_V,"EOF code: %d \n",mpctx->stop_play);
4884 #ifdef CONFIG_DVBIN
4885 if(mpctx->dvbin_reopen)
4887 mpctx->stop_play = 0;
4888 uninit_player(mpctx, INITIALIZED_ALL-(INITIALIZED_STREAM|INITIALIZED_GETCH2|(opts->fixed_vo?INITIALIZED_VO:0)));
4889 cache_uninit(mpctx->stream);
4890 mpctx->dvbin_reopen = 0;
4891 goto goto_enable_cache;
4893 #endif
4896 goto_next_file: // don't jump here after ao/vo/getch initialization!
4898 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\n");
4900 if (opts->benchmark) {
4901 double tot=video_time_usage+vout_time_usage+audio_time_usage;
4902 double total_time_usage;
4903 total_time_usage_start=GetTimer()-total_time_usage_start;
4904 total_time_usage = (float)total_time_usage_start*0.000001;
4905 mp_msg(MSGT_CPLAYER,MSGL_INFO,"\nBENCHMARKs: VC:%8.3fs VO:%8.3fs A:%8.3fs Sys:%8.3fs = %8.3fs\n",
4906 video_time_usage,vout_time_usage,audio_time_usage,
4907 total_time_usage-tot,total_time_usage);
4908 if(total_time_usage>0.0)
4909 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARK%%: VC:%8.4f%% VO:%8.4f%% A:%8.4f%% Sys:%8.4f%% = %8.4f%%\n",
4910 100.0*video_time_usage/total_time_usage,
4911 100.0*vout_time_usage/total_time_usage,
4912 100.0*audio_time_usage/total_time_usage,
4913 100.0*(total_time_usage-tot)/total_time_usage,
4914 100.0);
4915 if(total_frame_cnt && frame_dropping)
4916 mp_msg(MSGT_CPLAYER,MSGL_INFO,"BENCHMARKn: disp: %d (%3.2f fps) drop: %d (%d%%) total: %d (%3.2f fps)\n",
4917 total_frame_cnt-drop_frame_cnt,
4918 (total_time_usage>0.5)?((total_frame_cnt-drop_frame_cnt)/total_time_usage):0,
4919 drop_frame_cnt,
4920 100*drop_frame_cnt/total_frame_cnt,
4921 total_frame_cnt,
4922 (total_time_usage>0.5)?(total_frame_cnt/total_time_usage):0);
4925 // time to uninit all, except global stuff:
4926 int uninitialize_parts = INITIALIZED_ALL;
4927 if (opts->fixed_vo)
4928 uninitialize_parts -= INITIALIZED_VO;
4929 if (opts->gapless_audio && mpctx->stop_play == AT_END_OF_FILE)
4930 uninitialize_parts -= INITIALIZED_AO;
4931 uninit_player(mpctx, uninitialize_parts);
4933 if(mpctx->set_of_sub_size > 0) {
4934 current_module="sub_free";
4935 for(i = 0; i < mpctx->set_of_sub_size; ++i) {
4936 sub_free(mpctx->set_of_subtitles[i]);
4937 #ifdef CONFIG_ASS
4938 if(mpctx->set_of_ass_tracks[i])
4939 ass_free_track( mpctx->set_of_ass_tracks[i] );
4940 #endif
4942 mpctx->set_of_sub_size = 0;
4944 mpctx->vo_sub_last = vo_sub=NULL;
4945 mpctx->subdata=NULL;
4946 #ifdef CONFIG_ASS
4947 ass_track = NULL;
4948 if(ass_library)
4949 ass_clear_fonts(ass_library);
4950 #endif
4952 if (!mpctx->stop_play) // In case some goto jumped here...
4953 mpctx->stop_play = PT_NEXT_ENTRY;
4955 int playtree_direction = 1;
4957 if(mpctx->stop_play == PT_NEXT_ENTRY || mpctx->stop_play == PT_PREV_ENTRY) {
4958 if(play_tree_iter_step(mpctx->playtree_iter,mpctx->play_tree_step,0) != PLAY_TREE_ITER_ENTRY) {
4959 play_tree_iter_free(mpctx->playtree_iter);
4960 mpctx->playtree_iter = NULL;
4962 mpctx->play_tree_step = 1;
4963 } else if(mpctx->stop_play == PT_UP_NEXT || mpctx->stop_play == PT_UP_PREV) {
4964 int direction = mpctx->stop_play == PT_UP_NEXT ? 1 : -1;
4965 if(mpctx->playtree_iter) {
4966 if(play_tree_iter_up_step(mpctx->playtree_iter,direction,0) != PLAY_TREE_ITER_ENTRY) {
4967 play_tree_iter_free(mpctx->playtree_iter);
4968 mpctx->playtree_iter = NULL;
4971 } else if (mpctx->stop_play == PT_STOP) {
4972 play_tree_iter_free(mpctx->playtree_iter);
4973 mpctx->playtree_iter = NULL;
4974 } else { // NEXT PREV SRC
4975 playtree_direction = mpctx->stop_play == PT_PREV_SRC ? -1 : 1;
4978 while(mpctx->playtree_iter != NULL) {
4979 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, playtree_direction);
4980 if(mpctx->filename == NULL) {
4981 if(play_tree_iter_step(mpctx->playtree_iter, playtree_direction, 0) != PLAY_TREE_ITER_ENTRY) {
4982 play_tree_iter_free(mpctx->playtree_iter);
4983 mpctx->playtree_iter = NULL;
4985 } else
4986 break;
4989 if (mpctx->playtree_iter != NULL || opts->player_idle_mode) {
4990 if(!mpctx->playtree_iter) mpctx->filename = NULL;
4991 mpctx->stop_play = 0;
4992 goto play_next_file;
4996 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4998 return 1;
5000 #endif /* DISABLE_MAIN */