vo_gl: add new vo name "gl_sdl" to make SDL+GL mode available
[mplayer.git] / mplayer.c
blobceb9f794a89865146f9fad9e2cbc8e48f5ceebd7
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 #include <stdio.h>
20 #include <stdlib.h>
21 #include <stdbool.h>
22 #include <math.h>
23 #include <assert.h>
25 #include "config.h"
26 #include "talloc.h"
28 #if defined(__MINGW32__) || defined(__CYGWIN__)
29 #define _UWIN 1 /*disable Non-underscored versions of non-ANSI functions as otherwise int eof would conflict with eof()*/
30 #include <windows.h>
31 #endif
32 #include <string.h>
33 #include <unistd.h>
35 // #include <sys/mman.h>
36 #include <sys/types.h>
37 #ifndef __MINGW32__
38 #include <sys/ioctl.h>
39 #include <sys/wait.h>
40 #else
41 #define SIGHUP 1 /* hangup */
42 #define SIGQUIT 3 /* quit */
43 #define SIGKILL 9 /* kill (cannot be caught or ignored) */
44 #define SIGBUS 10 /* bus error */
45 #define SIGPIPE 13 /* broken pipe */
46 #endif
48 #include <sys/time.h>
49 #include <sys/stat.h>
51 #include <signal.h>
52 #include <time.h>
53 #include <fcntl.h>
54 #include <limits.h>
56 #include <errno.h>
58 #include "mp_msg.h"
59 #include "av_log.h"
62 #include "m_option.h"
63 #include "m_config.h"
64 #include "mplayer.h"
65 #include "access_mpcontext.h"
66 #include "m_property.h"
68 #include "libavutil/avstring.h"
70 #include "sub/subreader.h"
71 #include "sub/find_subfiles.h"
72 #include "sub/dec_sub.h"
74 #include "mp_osd.h"
75 #include "libvo/video_out.h"
77 #include "sub/font_load.h"
78 #include "sub/sub.h"
79 #include "ffmpeg_files/intreadwrite.h"
80 #include "sub/av_sub.h"
81 #include "libmpcodecs/dec_teletext.h"
82 #include "cpudetect.h"
83 #include "version.h"
85 #ifdef CONFIG_X11
86 #include "libvo/x11_common.h"
87 #endif
89 #include "libao2/audio_out.h"
91 #include "codec-cfg.h"
93 #include "edl.h"
95 #include "sub/spudec.h"
96 #include "sub/vobsub.h"
98 #include "osdep/getch2.h"
99 #include "osdep/timer.h"
101 #include "input/input.h"
103 int slave_mode = 0;
104 int enable_mouse_movements = 0;
105 float start_volume = -1;
107 #include "osdep/priority.h"
109 char *heartbeat_cmd;
111 #ifdef HAVE_RTC
112 #ifdef __linux__
113 #include <linux/rtc.h>
114 #else
115 #include <rtc.h>
116 #define RTC_IRQP_SET RTCIO_IRQP_SET
117 #define RTC_PIE_ON RTCIO_PIE_ON
118 #endif /* __linux__ */
119 #endif /* HAVE_RTC */
121 #include "stream/tv.h"
122 #include "stream/stream_radio.h"
123 #ifdef CONFIG_DVBIN
124 #include "stream/dvbin.h"
125 #endif
126 #include "stream/cache2.h"
128 //**************************************************************************//
129 // Playtree
130 //**************************************************************************//
131 #include "playtree.h"
132 #include "playtreeparser.h"
134 //**************************************************************************//
135 // Config
136 //**************************************************************************//
137 #include "parser-cfg.h"
138 #include "parser-mpcmd.h"
140 //**************************************************************************//
141 // Config file
142 //**************************************************************************//
144 static int cfg_inc_verbose(m_option_t *conf)
146 ++verbose;
147 return 0;
150 #include "path.h"
152 //**************************************************************************//
153 //**************************************************************************//
154 // Input media streaming & demultiplexer:
155 //**************************************************************************//
157 static int max_framesize = 0;
159 #include "stream/stream.h"
160 #include "libmpdemux/demuxer.h"
161 #include "libmpdemux/stheader.h"
163 #ifdef CONFIG_DVDREAD
164 #include "stream/stream_dvd.h"
165 #endif
166 #include "stream/stream_dvdnav.h"
168 #include "libmpcodecs/dec_audio.h"
169 #include "libmpcodecs/dec_video.h"
170 #include "libmpcodecs/mp_image.h"
171 #include "libmpcodecs/vf.h"
172 #include "libmpcodecs/vd.h"
174 #include "mixer.h"
176 #include "mp_core.h"
177 #include "options.h"
178 #include "defaultopts.h"
180 static const char help_text[] = _(
181 "Usage: mplayer [options] [url|path/]filename\n"
182 "\n"
183 "Basic options: (complete list in the man page)\n"
184 " -vo <drv> select video output driver ('-vo help' for a list)\n"
185 " -ao <drv> select audio output driver ('-ao help' for a list)\n"
186 #ifdef CONFIG_VCD
187 " vcd://<trackno> play (S)VCD (Super Video CD) track (raw device, no mount)\n"
188 #endif
189 #ifdef CONFIG_DVDREAD
190 " dvd://<titleno> play DVD title from device instead of plain file\n"
191 #endif
192 " -alang/-slang select DVD audio/subtitle language (by 2-char country code)\n"
193 " -ss <position> seek to given (seconds or hh:mm:ss) position\n"
194 " -nosound do not play sound\n"
195 " -fs fullscreen playback (or -vm, -zoom, details in the man page)\n"
196 " -x <x> -y <y> set display resolution (for use with -vm or -zoom)\n"
197 " -sub <file> specify subtitle file to use (also see -subfps, -subdelay)\n"
198 " -playlist <file> specify playlist file\n"
199 " -vid x -aid y select video (x) and audio (y) stream to play\n"
200 " -fps x -srate y change video (x fps) and audio (y Hz) rate\n"
201 " -pp <quality> enable postprocessing filter (details in the man page)\n"
202 " -framedrop enable frame dropping (for slow machines)\n"
203 "\n"
204 "Basic keys: (complete list in the man page, also check input.conf)\n"
205 " <- or -> seek backward/forward 10 seconds\n"
206 " down or up seek backward/forward 1 minute\n"
207 " pgdown or pgup seek backward/forward 10 minutes\n"
208 " < or > step backward/forward in playlist\n"
209 " p or SPACE pause movie (press any key to continue)\n"
210 " q or ESC stop playing and quit program\n"
211 " + or - adjust audio delay by +/- 0.1 second\n"
212 " o cycle OSD mode: none / seekbar / seekbar + timer\n"
213 " * or / increase or decrease PCM volume\n"
214 " x or z adjust subtitle delay by +/- 0.1 second\n"
215 " r or t adjust subtitle position up/down, also see -vf expand\n"
216 " double click toggle fullscreen\n"
217 " right click pause (press again to continue)\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;
276 double vout_time_usage;
277 static double audio_time_usage;
278 static int total_time_usage_start;
279 static int total_frame_cnt;
280 static int drop_frame_cnt; // total number of dropped frames
282 // options:
283 static int output_quality;
285 // seek:
286 static off_t seek_to_byte;
287 static off_t step_sec;
289 static m_time_size_t end_at = { .type = END_AT_NONE, .pos = 0 };
291 // codecs:
292 char **audio_codec_list; // override audio codec
293 char **video_codec_list; // override video codec
294 char **audio_fm_list; // override audio codec family
295 char **video_fm_list; // override video codec family
297 // this dvdsub_id was selected via slang
298 // use this to allow dvdnav to follow -slang across stream resets,
299 // in particular the subtitle ID for a language changes
300 int dvdsub_lang_id;
301 int vobsub_id = -1;
302 static char *spudec_ifo = NULL;
303 int forced_subs_only = 0;
304 int file_filter = 1;
306 // cache2:
307 int stream_cache_size = -1;
309 // dump:
310 int stream_dump_type = 0;
312 // A-V sync:
313 static float default_max_pts_correction = -1;
314 float audio_delay = 0;
315 static int ignore_start = 0;
317 double force_fps = 0;
318 static int force_srate = 0;
319 int frame_dropping = 0; // option 0=no drop 1= drop vo 2= drop decode
320 static int play_n_frames = -1;
321 static int play_n_frames_mf = -1;
323 // sub:
324 char *font_name = NULL;
325 char *sub_font_name = NULL;
326 extern int font_fontconfig;
327 float font_factor = 0.75;
328 float sub_delay = 0;
329 float sub_fps = 0;
330 int subcc_enabled = 0;
331 int suboverlap_enabled = 1;
333 #include "sub/ass_mp.h"
335 char *current_module; // for debugging
338 // ---
340 #ifdef CONFIG_MENU
341 #include "m_struct.h"
342 #include "libmenu/menu.h"
343 static const vf_info_t * const libmenu_vfs[] = {
344 &vf_info_menu,
345 NULL
347 static vf_instance_t *vf_menu;
348 int use_menu;
349 static char *menu_cfg;
350 static char *menu_root = "main";
351 #endif
354 edl_record_ptr edl_records = NULL; ///< EDL entries memory area
355 edl_record_ptr next_edl_record = NULL; ///< only for traversing edl_records
356 FILE *edl_fd; // file to write to when in -edlout mode.
357 int use_filedir_conf;
358 int use_filename_title;
360 #include "mpcommon.h"
361 #include "command.h"
363 #include "metadata.h"
365 void *mpctx_get_video_out(MPContext *mpctx)
367 return mpctx->video_out;
370 void *mpctx_get_demuxer(MPContext *mpctx)
372 return mpctx->demuxer;
375 void *mpctx_get_playtree_iter(MPContext *mpctx)
377 return mpctx->playtree_iter;
380 void *mpctx_get_mixer(MPContext *mpctx)
382 return &mpctx->mixer;
385 int mpctx_get_global_sub_size(MPContext *mpctx)
387 return mpctx->global_sub_size;
390 int mpctx_get_osd_function(MPContext *mpctx)
392 return mpctx->osd_function;
395 static float get_relative_time(struct MPContext *mpctx)
397 unsigned int new_time = GetTimer();
398 unsigned int delta = new_time - mpctx->last_time;
399 mpctx->last_time = new_time;
400 return delta * 0.000001;
403 static int is_valid_metadata_type(struct MPContext *mpctx, metadata_t type)
405 switch (type) {
406 /* check for valid video stream */
407 case META_VIDEO_CODEC:
408 case META_VIDEO_BITRATE:
409 case META_VIDEO_RESOLUTION:
410 if (!mpctx->sh_video)
411 return 0;
412 break;
414 /* check for valid audio stream */
415 case META_AUDIO_CODEC:
416 case META_AUDIO_BITRATE:
417 case META_AUDIO_SAMPLES:
418 if (!mpctx->sh_audio)
419 return 0;
420 break;
422 /* check for valid demuxer */
423 case META_INFO_TITLE:
424 case META_INFO_ARTIST:
425 case META_INFO_ALBUM:
426 case META_INFO_YEAR:
427 case META_INFO_COMMENT:
428 case META_INFO_TRACK:
429 case META_INFO_GENRE:
430 if (!mpctx->demuxer)
431 return 0;
432 break;
434 default:
435 break;
438 return 1;
441 static char *get_demuxer_info(struct MPContext *mpctx, char *tag)
443 char **info = mpctx->demuxer->info;
444 int n;
446 if (!info || !tag)
447 return talloc_strdup(NULL, "");
449 for (n = 0; info[2 * n] != NULL; n++)
450 if (!strcasecmp(info[2 * n], tag))
451 break;
453 return talloc_strdup(NULL, info[2 * n + 1] ? info[2 * n + 1] : "");
456 char *get_metadata(struct MPContext *mpctx, metadata_t type)
458 sh_audio_t * const sh_audio = mpctx->sh_audio;
459 sh_video_t * const sh_video = mpctx->sh_video;
461 if (!is_valid_metadata_type(mpctx, type))
462 return NULL;
464 switch (type) {
465 case META_NAME:
466 return talloc_strdup(NULL, mp_basename(mpctx->filename));
467 case META_VIDEO_CODEC:
468 if (sh_video->format == 0x10000001)
469 return talloc_strdup(NULL, "mpeg1");
470 else if (sh_video->format == 0x10000002)
471 return talloc_strdup(NULL, "mpeg2");
472 else if (sh_video->format == 0x10000004)
473 return talloc_strdup(NULL, "mpeg4");
474 else if (sh_video->format == 0x10000005)
475 return talloc_strdup(NULL, "h264");
476 else if (sh_video->format >= 0x20202020)
477 return talloc_asprintf(NULL, "%.4s", (char *) &sh_video->format);
478 else
479 return talloc_asprintf(NULL, "0x%08X", sh_video->format);
480 case META_VIDEO_BITRATE:
481 return talloc_asprintf(NULL, "%d kbps",
482 (int) (sh_video->i_bps * 8 / 1024));
483 case META_VIDEO_RESOLUTION:
484 return talloc_asprintf(NULL, "%d x %d", sh_video->disp_w,
485 sh_video->disp_h);
486 case META_AUDIO_CODEC:
487 if (sh_audio->codec && sh_audio->codec->name)
488 return talloc_strdup(NULL, sh_audio->codec->name);
489 return talloc_strdup(NULL, "");
490 case META_AUDIO_BITRATE:
491 return talloc_asprintf(NULL, "%d kbps",
492 (int) (sh_audio->i_bps * 8 / 1000));
493 case META_AUDIO_SAMPLES:
494 return talloc_asprintf(NULL, "%d Hz, %d ch.", sh_audio->samplerate,
495 sh_audio->channels);
497 /* check for valid demuxer */
498 case META_INFO_TITLE:
499 return get_demuxer_info(mpctx, "Title");
501 case META_INFO_ARTIST:
502 return get_demuxer_info(mpctx, "Artist");
504 case META_INFO_ALBUM:
505 return get_demuxer_info(mpctx, "Album");
507 case META_INFO_YEAR:
508 return get_demuxer_info(mpctx, "Year");
510 case META_INFO_COMMENT:
511 return get_demuxer_info(mpctx, "Comment");
513 case META_INFO_TRACK:
514 return get_demuxer_info(mpctx, "Track");
516 case META_INFO_GENRE:
517 return get_demuxer_info(mpctx, "Genre");
519 default:
520 break;
523 return talloc_strdup(NULL, "");
526 static void print_file_properties(struct MPContext *mpctx, const char *filename)
528 double start_pts = MP_NOPTS_VALUE;
529 double video_start_pts = MP_NOPTS_VALUE;
530 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILENAME=%s\n",
531 filename_recode(filename));
532 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_DEMUXER=%s\n",
533 mpctx->demuxer->desc->name);
534 if (mpctx->sh_video) {
535 /* Assume FOURCC if all bytes >= 0x20 (' ') */
536 if (mpctx->sh_video->format >= 0x20202020)
537 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
538 "ID_VIDEO_FORMAT=%.4s\n", (char *)&mpctx->sh_video->format);
539 else
540 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
541 "ID_VIDEO_FORMAT=0x%08X\n", mpctx->sh_video->format);
542 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
543 "ID_VIDEO_BITRATE=%d\n", mpctx->sh_video->i_bps * 8);
544 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
545 "ID_VIDEO_WIDTH=%d\n", mpctx->sh_video->disp_w);
546 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
547 "ID_VIDEO_HEIGHT=%d\n", mpctx->sh_video->disp_h);
548 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
549 "ID_VIDEO_FPS=%5.3f\n", mpctx->sh_video->fps);
550 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
551 "ID_VIDEO_ASPECT=%1.4f\n", mpctx->sh_video->aspect);
552 video_start_pts = ds_get_next_pts(mpctx->d_video);
554 if (mpctx->sh_audio) {
555 /* Assume FOURCC if all bytes >= 0x20 (' ') */
556 if (mpctx->sh_audio->format >= 0x20202020)
557 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
558 "ID_AUDIO_FORMAT=%.4s\n", (char *)&mpctx->sh_audio->format);
559 else
560 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
561 "ID_AUDIO_FORMAT=%d\n", mpctx->sh_audio->format);
562 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
563 "ID_AUDIO_BITRATE=%d\n", mpctx->sh_audio->i_bps * 8);
564 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
565 "ID_AUDIO_RATE=%d\n", mpctx->sh_audio->samplerate);
566 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
567 "ID_AUDIO_NCH=%d\n", mpctx->sh_audio->channels);
568 start_pts = ds_get_next_pts(mpctx->d_audio);
570 if (video_start_pts != MP_NOPTS_VALUE) {
571 if (start_pts == MP_NOPTS_VALUE || !mpctx->sh_audio ||
572 (mpctx->sh_video && video_start_pts < start_pts))
573 start_pts = video_start_pts;
575 if (start_pts != MP_NOPTS_VALUE)
576 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_START_TIME=%.2f\n", start_pts);
577 else
578 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_START_TIME=unknown\n");
579 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
580 "ID_LENGTH=%.2f\n", get_time_length(mpctx));
581 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SEEKABLE=%d\n",
582 mpctx->stream->seek
583 && (!mpctx->demuxer || mpctx->demuxer->seekable));
584 if (mpctx->demuxer) {
585 if (mpctx->demuxer->num_chapters == 0)
586 stream_control(mpctx->demuxer->stream,
587 STREAM_CTRL_GET_NUM_CHAPTERS,
588 &mpctx->demuxer->num_chapters);
589 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
590 "ID_CHAPTERS=%d\n", mpctx->demuxer->num_chapters);
594 /// step size of mixer changes
595 int volstep = 3;
597 #ifdef CONFIG_DVDNAV
598 static void mp_dvdnav_context_free(MPContext *ctx)
600 if (ctx->nav_smpi)
601 free_mp_image(ctx->nav_smpi);
602 ctx->nav_smpi = NULL;
603 free(ctx->nav_buffer);
604 ctx->nav_buffer = NULL;
605 ctx->nav_start = NULL;
606 ctx->nav_in_size = 0;
608 #endif
610 static void uninit_subs(struct demuxer *demuxer)
612 for (int i = 0; i < MAX_S_STREAMS; i++) {
613 struct sh_sub *sh = demuxer->s_streams[i];
614 if (sh && sh->initialized)
615 sub_uninit(sh);
619 void uninit_player(struct MPContext *mpctx, unsigned int mask)
621 mask &= mpctx->initialized_flags;
623 mp_msg(MSGT_CPLAYER, MSGL_DBG2, "\n*** uninit(0x%X)\n", mask);
625 if (mask & INITIALIZED_ACODEC) {
626 mpctx->initialized_flags &= ~INITIALIZED_ACODEC;
627 current_module = "uninit_acodec";
628 if (mpctx->sh_audio)
629 uninit_audio(mpctx->sh_audio);
630 mpctx->sh_audio = NULL;
631 mpctx->mixer.afilter = NULL;
634 if (mask & INITIALIZED_SUB) {
635 mpctx->initialized_flags &= ~INITIALIZED_SUB;
636 if (mpctx->d_sub->sh)
637 sub_switchoff(mpctx->d_sub->sh, mpctx->osd);
640 if (mask & INITIALIZED_VCODEC) {
641 mpctx->initialized_flags &= ~INITIALIZED_VCODEC;
642 current_module = "uninit_vcodec";
643 if (mpctx->sh_video)
644 uninit_video(mpctx->sh_video);
645 mpctx->sh_video = NULL;
646 #ifdef CONFIG_MENU
647 vf_menu = NULL;
648 #endif
651 if (mask & INITIALIZED_DEMUXER) {
652 mpctx->initialized_flags &= ~INITIALIZED_DEMUXER;
653 current_module = "free_demuxer";
654 if (mpctx->num_sources) {
655 mpctx->demuxer = mpctx->sources[0].demuxer;
656 for (int i = 1; i < mpctx->num_sources; i++) {
657 uninit_subs(mpctx->sources[i].demuxer);
658 free_stream(mpctx->sources[i].stream);
659 free_demuxer(mpctx->sources[i].demuxer);
662 talloc_free(mpctx->sources);
663 mpctx->sources = NULL;
664 mpctx->num_sources = 0;
665 talloc_free(mpctx->timeline);
666 mpctx->timeline = NULL;
667 mpctx->num_timeline_parts = 0;
668 talloc_free(mpctx->chapters);
669 mpctx->chapters = NULL;
670 mpctx->num_chapters = 0;
671 mpctx->video_offset = 0;
672 if (mpctx->demuxer) {
673 mpctx->stream = mpctx->demuxer->stream;
674 uninit_subs(mpctx->demuxer);
675 free_demuxer(mpctx->demuxer);
677 mpctx->demuxer = NULL;
680 // kill the cache process:
681 if (mask & INITIALIZED_STREAM) {
682 mpctx->initialized_flags &= ~INITIALIZED_STREAM;
683 current_module = "uninit_stream";
684 if (mpctx->stream)
685 free_stream(mpctx->stream);
686 mpctx->stream = NULL;
689 if (mask & INITIALIZED_VO) {
690 mpctx->initialized_flags &= ~INITIALIZED_VO;
691 current_module = "uninit_vo";
692 vo_destroy(mpctx->video_out);
693 mpctx->video_out = NULL;
694 #ifdef CONFIG_DVDNAV
695 mp_dvdnav_context_free(mpctx);
696 #endif
699 // Must be after libvo uninit, as few vo drivers (svgalib) have tty code.
700 if (mask & INITIALIZED_GETCH2) {
701 mpctx->initialized_flags &= ~INITIALIZED_GETCH2;
702 current_module = "uninit_getch2";
703 mp_msg(MSGT_CPLAYER, MSGL_DBG2, "\n[[[uninit getch2]]]\n");
704 // restore terminal:
705 getch2_disable();
708 if (mask & INITIALIZED_VOBSUB) {
709 mpctx->initialized_flags &= ~INITIALIZED_VOBSUB;
710 current_module = "uninit_vobsub";
711 if (vo_vobsub)
712 vobsub_close(vo_vobsub);
713 vo_vobsub = NULL;
716 if (mask & INITIALIZED_SPUDEC) {
717 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
718 current_module = "uninit_spudec";
719 spudec_free(vo_spudec);
720 vo_spudec = NULL;
723 if (mask & INITIALIZED_AO) {
724 mpctx->initialized_flags &= ~INITIALIZED_AO;
725 current_module = "uninit_ao";
726 if (mpctx->edl_muted)
727 mixer_mute(&mpctx->mixer);
728 if (mpctx->ao)
729 ao_uninit(mpctx->ao, mpctx->stop_play != AT_END_OF_FILE);
730 mpctx->ao = NULL;
733 current_module = NULL;
736 void exit_player_with_rc(struct MPContext *mpctx, enum exit_reason how, int rc)
738 if (mpctx->user_muted && !mpctx->edl_muted)
739 mixer_mute(&mpctx->mixer);
740 uninit_player(mpctx, INITIALIZED_ALL);
741 #if defined(__MINGW32__) || defined(__CYGWIN__)
742 timeEndPeriod(1);
743 #endif
744 #ifdef CONFIG_X11
745 vo_uninit(mpctx->x11_state); // Close the X11 connection (if any is open).
746 #endif
748 current_module = "uninit_input";
749 mp_input_uninit(mpctx->input);
750 #ifdef CONFIG_MENU
751 if (use_menu)
752 menu_uninit();
753 #endif
755 #ifdef CONFIG_FREETYPE
756 current_module = "uninit_font";
757 if (mpctx->osd && mpctx->osd->sub_font != vo_font)
758 free_font_desc(mpctx->osd->sub_font);
759 free_font_desc(vo_font);
760 vo_font = NULL;
761 done_freetype();
762 #endif
763 osd_free(mpctx->osd);
765 #ifdef CONFIG_ASS
766 ass_library_done(mpctx->ass_library);
767 mpctx->ass_library = NULL;
768 #endif
770 current_module = "exit_player";
772 if (mpctx->playtree_iter)
773 play_tree_iter_free(mpctx->playtree_iter);
774 mpctx->playtree_iter = NULL;
775 if (mpctx->playtree)
776 play_tree_free(mpctx->playtree, 1);
777 mpctx->playtree = NULL;
779 talloc_free(mpctx->key_fifo);
781 free(edl_records); // free mem allocated for EDL
782 edl_records = NULL;
783 switch (how) {
784 case EXIT_QUIT:
785 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nExiting... (%s)\n", "Quit");
786 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=QUIT\n");
787 break;
788 case EXIT_EOF:
789 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nExiting... (%s)\n", "End of file");
790 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=EOF\n");
791 break;
792 case EXIT_ERROR:
793 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nExiting... (%s)\n", "Fatal error");
794 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=ERROR\n");
795 break;
796 default:
797 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=NONE\n");
799 mp_msg(MSGT_CPLAYER, MSGL_DBG2,
800 "max framesize was %d bytes\n", max_framesize);
802 // must be last since e.g. mp_msg uses option values
803 // that will be freed by this.
804 if (mpctx->mconfig)
805 m_config_free(mpctx->mconfig);
806 mpctx->mconfig = NULL;
808 exit(rc);
811 static void exit_player(struct MPContext *mpctx, enum exit_reason how)
813 exit_player_with_rc(mpctx, how, 1);
816 #ifndef __MINGW32__
817 static void child_sighandler(int x)
819 pid_t pid;
820 while ((pid = waitpid(-1, NULL, WNOHANG)) > 0) ;
822 #endif
824 #ifdef CONFIG_CRASH_DEBUG
825 static char *prog_path;
826 static int crash_debug = 0;
827 #endif
829 static void exit_sighandler(int x)
831 static int sig_count = 0;
832 #ifdef CONFIG_CRASH_DEBUG
833 if (!crash_debug || x != SIGTRAP)
834 #endif
835 ++sig_count;
836 if (sig_count == 5) {
837 /* We're crashing bad and can't uninit cleanly :(
838 * by popular request, we make one last (dirty)
839 * effort to restore the user's
840 * terminal. */
841 getch2_disable();
842 exit(1);
844 if (sig_count == 6)
845 exit(1);
846 if (sig_count > 6) {
847 // can't stop :(
848 #ifndef __MINGW32__
849 kill(getpid(), SIGKILL);
850 #endif
852 mp_msg(MSGT_CPLAYER, MSGL_FATAL, "\n");
853 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
854 "\nMPlayer interrupted by signal %d in module: %s\n", x,
855 current_module ? current_module : "unknown");
856 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SIGNAL=%d\n", x);
857 if (sig_count <= 1)
858 switch (x) {
859 case SIGINT:
860 case SIGPIPE:
861 case SIGQUIT:
862 case SIGTERM:
863 case SIGKILL:
864 async_quit_request = 1;
865 return; // killed from keyboard (^C) or killed [-9]
866 case SIGILL:
867 #if CONFIG_RUNTIME_CPUDETECT
868 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGILL_RTCpuSel);
869 #else
870 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGILL);
871 #endif
872 case SIGFPE:
873 case SIGSEGV:
874 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGSEGV_SIGFPE);
875 default:
876 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGCRASH);
877 #ifdef CONFIG_CRASH_DEBUG
878 if (crash_debug) {
879 int gdb_pid;
880 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forking...\n");
881 gdb_pid = fork();
882 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forked...\n");
883 if (gdb_pid == 0) { // We are the child
884 char spid[20];
885 snprintf(spid, sizeof(spid), "%i", getppid());
886 getch2_disable(); // allow terminal to work properly with gdb
887 if (execlp("gdb", "gdb", prog_path, spid, "-ex", "bt", NULL) == -1)
888 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't start gdb\n");
889 } else if (gdb_pid < 0)
890 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't fork\n");
891 else
892 waitpid(gdb_pid, NULL, 0);
893 if (x == SIGTRAP)
894 return;
896 #endif
898 getch2_disable();
899 exit(1);
902 #include "cfg-mplayer.h"
904 static int cfg_include(m_option_t *conf, char *filename)
906 return m_config_parse_config_file(conf->priv, filename);
909 #define DEF_CONFIG "# Write your default config options here!\n\n\n"
911 static void parse_cfgfiles(struct MPContext *mpctx, m_config_t *conf)
913 struct MPOpts *opts = &mpctx->opts;
914 char *conffile;
915 int conffile_fd;
916 if (!(opts->noconfig & 2) &&
917 m_config_parse_config_file(conf, MPLAYER_CONFDIR "/mplayer.conf") < 0)
918 exit_player(mpctx, EXIT_NONE);
919 if ((conffile = get_path("")) == NULL)
920 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Cannot find HOME directory.\n");
921 else {
922 #ifdef __MINGW32__
923 mkdir(conffile);
924 #else
925 mkdir(conffile, 0777);
926 #endif
927 free(conffile);
928 if ((conffile = get_path("config")) == NULL)
929 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "get_path(\"config\") problem\n");
930 else {
931 if ((conffile_fd = open(conffile, O_CREAT | O_EXCL | O_WRONLY,
932 0666)) != -1) {
933 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
934 "Creating config file: %s\n", conffile);
935 write(conffile_fd, DEF_CONFIG, sizeof(DEF_CONFIG) - 1);
936 close(conffile_fd);
938 if (!(opts->noconfig & 1) &&
939 m_config_parse_config_file(conf, conffile) < 0)
940 exit_player(mpctx, EXIT_NONE);
941 free(conffile);
946 #define PROFILE_CFG_PROTOCOL "protocol."
948 static void load_per_protocol_config(m_config_t *conf, const char * const file)
950 char *str;
951 char protocol[strlen(PROFILE_CFG_PROTOCOL) + strlen(file) + 1];
952 m_profile_t *p;
954 /* does filename actually uses a protocol ? */
955 str = strstr(file, "://");
956 if (!str)
957 return;
959 sprintf(protocol, "%s%s", PROFILE_CFG_PROTOCOL, file);
960 protocol[strlen(PROFILE_CFG_PROTOCOL) + strlen(file) - strlen(str)] = '\0';
961 p = m_config_get_profile(conf, protocol);
962 if (p) {
963 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
964 "Loading protocol-related profile '%s'\n", protocol);
965 m_config_set_profile(conf, p);
969 #define PROFILE_CFG_EXTENSION "extension."
971 static void load_per_extension_config(m_config_t *conf, const char * const file)
973 char *str;
974 char extension[strlen(PROFILE_CFG_EXTENSION) + 8];
975 m_profile_t *p;
977 /* does filename actually have an extension ? */
978 str = strrchr(file, '.');
979 if (!str)
980 return;
982 sprintf(extension, PROFILE_CFG_EXTENSION);
983 strncat(extension, ++str, 7);
984 p = m_config_get_profile(conf, extension);
985 if (p) {
986 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
987 "Loading extension-related profile '%s'\n", extension);
988 m_config_set_profile(conf, p);
992 #define PROFILE_CFG_VO "vo."
993 #define PROFILE_CFG_AO "ao."
995 static void load_per_output_config(m_config_t *conf, char *cfg, char *out)
997 char profile[strlen(cfg) + strlen(out) + 1];
998 m_profile_t *p;
1000 sprintf(profile, "%s%s", cfg, out);
1001 p = m_config_get_profile(conf, profile);
1002 if (p) {
1003 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
1004 "Loading extension-related profile '%s'\n", profile);
1005 m_config_set_profile(conf, p);
1010 * Tries to load a config file
1011 * @return 0 if file was not found, 1 otherwise
1013 static int try_load_config(m_config_t *conf, const char *file)
1015 struct stat st;
1016 if (stat(file, &st))
1017 return 0;
1018 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Loading config '%s'\n", file);
1019 m_config_parse_config_file(conf, file);
1020 return 1;
1023 static void load_per_file_config(m_config_t *conf, const char * const file)
1025 char *confpath;
1026 char cfg[PATH_MAX];
1027 const char *name;
1029 if (strlen(file) > PATH_MAX - 14) {
1030 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Filename is too long, "
1031 "can not load file or directory specific config files\n");
1032 return;
1034 sprintf(cfg, "%s.conf", file);
1036 name = mp_basename(cfg);
1037 if (use_filedir_conf) {
1038 char dircfg[PATH_MAX];
1039 strcpy(dircfg, cfg);
1040 strcpy(dircfg + (name - cfg), "mplayer.conf");
1041 try_load_config(conf, dircfg);
1043 if (try_load_config(conf, cfg))
1044 return;
1047 if ((confpath = get_path(name)) != NULL) {
1048 try_load_config(conf, confpath);
1050 free(confpath);
1054 /* When libmpdemux performs a blocking operation (network connection or
1055 * cache filling) if the operation fails we use this function to check
1056 * if it was interrupted by the user.
1057 * The function returns a new value for eof. */
1058 static int libmpdemux_was_interrupted(struct MPContext *mpctx, int stop_play)
1060 mp_cmd_t *cmd;
1061 if ((cmd = mp_input_get_cmd(mpctx->input, 0, 0)) != NULL) {
1062 switch (cmd->id) {
1063 case MP_CMD_QUIT:
1064 exit_player_with_rc(mpctx, EXIT_QUIT,
1065 (cmd->nargs > 0) ? cmd->args[0].v.i : 0);
1066 case MP_CMD_PLAY_TREE_STEP: {
1067 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_ENTRY : PT_PREV_ENTRY;
1068 mpctx->play_tree_step =
1069 (cmd->args[0].v.i == 0) ? 1 : cmd->args[0].v.i;
1070 } break;
1071 case MP_CMD_PLAY_TREE_UP_STEP: {
1072 stop_play = (cmd->args[0].v.i > 0) ? PT_UP_NEXT : PT_UP_PREV;
1073 } break;
1074 case MP_CMD_PLAY_ALT_SRC_STEP: {
1075 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_SRC : PT_PREV_SRC;
1076 } break;
1078 mp_cmd_free(cmd);
1080 return stop_play;
1083 static int playtree_add_playlist(struct MPContext *mpctx, play_tree_t *entry)
1085 play_tree_add_bpf(entry, bstr(mpctx->filename));
1088 if (!entry) {
1089 entry = mpctx->playtree_iter->tree;
1090 if (play_tree_iter_step(mpctx->playtree_iter, 1, 0)
1091 != PLAY_TREE_ITER_ENTRY)
1092 return PT_NEXT_ENTRY;
1093 if (mpctx->playtree_iter->tree == entry) { // Single file loop
1094 if (play_tree_iter_up_step(mpctx->playtree_iter, 1, 0)
1095 != PLAY_TREE_ITER_ENTRY)
1096 return PT_NEXT_ENTRY;
1098 play_tree_remove(entry, 1, 1);
1099 return PT_NEXT_SRC;
1101 play_tree_insert_entry(mpctx->playtree_iter->tree, entry);
1102 play_tree_set_params_from(entry, mpctx->playtree_iter->tree);
1103 entry = mpctx->playtree_iter->tree;
1104 if (play_tree_iter_step(mpctx->playtree_iter, 1, 0)
1105 != PLAY_TREE_ITER_ENTRY)
1106 return PT_NEXT_ENTRY;
1107 play_tree_remove(entry, 1, 1);
1109 return PT_NEXT_SRC;
1112 void add_subtitles(struct MPContext *mpctx, char *filename, float fps,
1113 int noerr)
1115 struct MPOpts *opts = &mpctx->opts;
1116 sub_data *subd = NULL;
1117 struct ass_track *asst = NULL;
1118 bool is_native_ass = false;
1120 if (filename == NULL || mpctx->set_of_sub_size >= MAX_SUBTITLE_FILES)
1121 return;
1123 #ifdef CONFIG_ASS
1124 if (opts->ass_enabled) {
1125 #ifdef CONFIG_ICONV
1126 asst = mp_ass_read_stream(mpctx->ass_library, filename, sub_cp);
1127 #else
1128 asst = mp_ass_read_stream(mpctx->ass_library, filename, 0);
1129 #endif
1130 is_native_ass = asst;
1131 if (!asst) {
1132 subd = sub_read_file(filename, fps, &mpctx->opts);
1133 if (subd) {
1134 asst = mp_ass_read_subdata(mpctx->ass_library, opts, subd, fps);
1135 sub_free(subd);
1136 subd = NULL;
1139 } else
1140 #endif
1141 subd = sub_read_file(filename, fps, &mpctx->opts);
1144 if (!asst && !subd) {
1145 mp_tmsg(MSGT_CPLAYER, noerr ? MSGL_WARN : MSGL_ERR,
1146 "Cannot load subtitles: %s\n", filename_recode(filename));
1147 return;
1150 mpctx->set_of_ass_tracks[mpctx->set_of_sub_size] = asst;
1151 mpctx->set_of_subtitles[mpctx->set_of_sub_size] = subd;
1152 mpctx->track_was_native_ass[mpctx->set_of_sub_size] = is_native_ass;
1153 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
1154 "ID_FILE_SUB_ID=%d\n", mpctx->set_of_sub_size);
1155 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_FILENAME=%s\n",
1156 filename_recode(filename));
1157 ++mpctx->set_of_sub_size;
1158 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "SUB: Added subtitle file (%d): %s\n",
1159 mpctx->set_of_sub_size, filename_recode(filename));
1162 void init_vo_spudec(struct MPContext *mpctx)
1164 unsigned width, height;
1165 spudec_free(vo_spudec);
1166 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
1167 vo_spudec = NULL;
1169 // we currently can't work without video stream
1170 if (!mpctx->sh_video)
1171 return;
1173 if (spudec_ifo) {
1174 unsigned int palette[16];
1175 current_module = "spudec_init_vobsub";
1176 if (vobsub_parse_ifo(NULL, spudec_ifo, palette, &width, &height,
1177 1, -1, NULL) >= 0)
1178 vo_spudec = spudec_new_scaled(palette, width, height, NULL, 0);
1181 width = mpctx->sh_video->disp_w;
1182 height = mpctx->sh_video->disp_h;
1184 #ifdef CONFIG_DVDREAD
1185 if (vo_spudec == NULL && mpctx->stream->type == STREAMTYPE_DVD) {
1186 current_module = "spudec_init_dvdread";
1187 vo_spudec = spudec_new_scaled(((dvd_priv_t *)(mpctx->stream->priv))->
1188 cur_pgc->palette, width, height, NULL, 0);
1190 #endif
1192 #ifdef CONFIG_DVDNAV
1193 if (vo_spudec == NULL && mpctx->stream->type == STREAMTYPE_DVDNAV) {
1194 unsigned int *palette = mp_dvdnav_get_spu_clut(mpctx->stream);
1195 current_module = "spudec_init_dvdnav";
1196 vo_spudec = spudec_new_scaled(palette, width, height, NULL, 0);
1198 #endif
1200 if (vo_spudec == NULL) {
1201 sh_sub_t *sh = mpctx->d_sub->sh;
1202 current_module = "spudec_init_normal";
1203 vo_spudec = spudec_new_scaled(NULL, width, height, sh->extradata,
1204 sh->extradata_len);
1205 spudec_set_font_factor(vo_spudec, font_factor);
1208 if (vo_spudec != NULL) {
1209 mpctx->initialized_flags |= INITIALIZED_SPUDEC;
1210 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only,
1211 mpctx);
1216 * In Mac OS X the SDL-lib is built upon Cocoa. The easiest way to
1217 * make it all work is to use the builtin SDL-bootstrap code, which
1218 * will be done automatically by replacing our main() if we include SDL.h.
1220 #if defined(__APPLE__) && defined(CONFIG_SDL)
1221 #ifdef CONFIG_SDL_SDL_H
1222 #include <SDL/SDL.h>
1223 #else
1224 #include <SDL.h>
1225 #endif
1226 #endif
1229 * \brief append a formatted string
1230 * \param buf buffer to print into
1231 * \param pos position of terminating 0 in buf
1232 * \param len maximum number of characters in buf, not including terminating 0
1233 * \param format printf format string
1235 static void saddf(char *buf, unsigned *pos, int len, const char *format, ...)
1237 va_list va;
1238 va_start(va, format);
1239 *pos += vsnprintf(&buf[*pos], len - *pos, format, va);
1240 va_end(va);
1241 if (*pos >= len) {
1242 buf[len] = 0;
1243 *pos = len;
1248 * \brief append time in the hh:mm:ss.f format
1249 * \param buf buffer to print into
1250 * \param pos position of terminating 0 in buf
1251 * \param len maximum number of characters in buf, not including terminating 0
1252 * \param time time value to convert/append
1254 static void sadd_hhmmssf(char *buf, unsigned *pos, int len, float time)
1256 int64_t tenths = 10 * time;
1257 int f1 = tenths % 10;
1258 int ss = (tenths / 10) % 60;
1259 int mm = (tenths / 600) % 60;
1260 int hh = tenths / 36000;
1261 if (time < 0) {
1262 saddf(buf, pos, len, "unknown");
1263 return;
1265 if (hh > 0)
1266 saddf(buf, pos, len, "%2d:", hh);
1267 if (hh > 0 || mm > 0)
1268 saddf(buf, pos, len, "%02d:", mm);
1269 saddf(buf, pos, len, "%02d.%1d", ss, f1);
1272 static void print_status(struct MPContext *mpctx, double a_pos, bool at_frame)
1274 struct MPOpts *opts = &mpctx->opts;
1275 sh_video_t * const sh_video = mpctx->sh_video;
1277 if (mpctx->sh_audio && a_pos == MP_NOPTS_VALUE)
1278 a_pos = playing_audio_pts(mpctx);
1279 if (mpctx->sh_audio && sh_video && at_frame) {
1280 mpctx->last_av_difference = a_pos - mpctx->video_pts - audio_delay;
1281 if (mpctx->time_frame > 0)
1282 mpctx->last_av_difference +=
1283 mpctx->time_frame * opts->playback_speed;
1284 if (mpctx->last_av_difference > 0.5 && drop_frame_cnt > 50
1285 && !mpctx->drop_message_shown) {
1286 mp_tmsg(MSGT_AVSYNC, MSGL_WARN, SystemTooSlow);
1287 mpctx->drop_message_shown = true;
1290 if (opts->quiet)
1291 return;
1293 if (a_pos == MP_NOPTS_VALUE)
1294 a_pos = -9; // don't print a huge negative number
1296 int width;
1297 char *line;
1298 unsigned pos = 0;
1299 get_screen_size();
1300 if (screen_width > 0)
1301 width = screen_width;
1302 else
1303 width = 80;
1304 #if defined(__MINGW32__) || defined(__CYGWIN__) || defined(__OS2__)
1305 /* Windows command line is broken (MinGW's rxvt works, but we
1306 * should not depend on that). */
1307 width--;
1308 #endif
1309 line = malloc(width + 1); // one additional char for the terminating null
1311 // Audio time
1312 if (mpctx->sh_audio) {
1313 saddf(line, &pos, width, "A:%6.1f ", a_pos);
1314 if (!sh_video) {
1315 float len = get_time_length(mpctx);
1316 saddf(line, &pos, width, "(");
1317 sadd_hhmmssf(line, &pos, width, a_pos);
1318 saddf(line, &pos, width, ") of %.1f (", len);
1319 sadd_hhmmssf(line, &pos, width, len);
1320 saddf(line, &pos, width, ") ");
1324 // Video time
1325 if (sh_video)
1326 saddf(line, &pos, width, "V:%6.1f ", mpctx->video_pts);
1328 // A-V sync
1329 if (mpctx->sh_audio && sh_video)
1330 saddf(line, &pos, width, "A-V:%7.3f ct:%7.3f ",
1331 mpctx->last_av_difference, mpctx->total_avsync_change);
1333 // Video stats
1334 if (sh_video)
1335 saddf(line, &pos, width, "%3d/%3d ",
1336 (int)sh_video->num_frames,
1337 (int)sh_video->num_frames_decoded);
1339 // CPU usage
1340 if (sh_video) {
1341 if (sh_video->timer > 0.5)
1342 saddf(line, &pos, width, "%2d%% %2d%% %4.1f%% ",
1343 (int)(100.0 * video_time_usage * opts->playback_speed / (double)sh_video->timer),
1344 (int)(100.0 * vout_time_usage * opts->playback_speed / (double)sh_video->timer),
1345 (100.0 * audio_time_usage * opts->playback_speed / (double)sh_video->timer));
1346 else
1347 saddf(line, &pos, width, "??%% ??%% ??,?%% ");
1348 } else if (mpctx->sh_audio) {
1349 if (mpctx->delay > 0.5)
1350 saddf(line, &pos, width, "%4.1f%% ",
1351 100.0 * audio_time_usage / (double)mpctx->delay);
1352 else
1353 saddf(line, &pos, width, "??,?%% ");
1356 // VO stats
1357 if (sh_video)
1358 saddf(line, &pos, width, "%d %d ", drop_frame_cnt, output_quality);
1360 #ifdef CONFIG_STREAM_CACHE
1361 // cache stats
1362 if (stream_cache_size > 0)
1363 saddf(line, &pos, width, "%d%% ", cache_fill_status(mpctx->stream));
1364 #endif
1366 // other
1367 if (opts->playback_speed != 1)
1368 saddf(line, &pos, width, "%4.2fx ", opts->playback_speed);
1370 // end
1371 if (erase_to_end_of_line) {
1372 line[pos] = 0;
1373 mp_msg(MSGT_STATUSLINE, MSGL_STATUS,
1374 "%s%s\r", line, erase_to_end_of_line);
1375 } else {
1376 memset(&line[pos], ' ', width - pos);
1377 line[width] = 0;
1378 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s\r", line);
1380 free(line);
1383 struct stream_dump_progress {
1384 uint64_t count;
1385 unsigned start_time;
1386 unsigned last_print_time;
1389 static void stream_dump_progress_start(struct stream_dump_progress *p)
1391 p->start_time = p->last_print_time = GetTimerMS();
1392 p->count = 0;
1395 static void stream_dump_progress(struct stream_dump_progress *p,
1396 uint64_t len, stream_t *stream)
1398 p->count += len;
1399 unsigned t = GetTimerMS();
1400 if (t - p->last_print_time < 1000)
1401 return;
1403 uint64_t start = stream->start_pos;
1404 uint64_t end = stream->end_pos;
1405 uint64_t pos = stream->pos;
1407 p->last_print_time = t;
1408 /* TODO: pretty print sizes; ETA */
1409 if (end > start && pos >= start && pos <= end) {
1410 mp_tmsg(MSGT_STATUSLINE, MSGL_STATUS,
1411 "dump: %"PRIu64 " bytes written (~%.1f%%)",
1412 p->count, 100.0 * (pos - start) / (end - start));
1413 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "\r");
1414 } else {
1415 mp_tmsg(MSGT_STATUSLINE, MSGL_STATUS,
1416 "dump: %"PRIu64 " bytes written", p->count);
1417 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "\r");
1421 static void stream_dump_progress_end(struct stream_dump_progress *p, char *name)
1423 mp_msg(MSGT_CPLAYER, MSGL_INFO, "dump: %"PRIu64 " bytes written to '%s'.\n",
1424 p->count, name);
1428 * \brief build a chain of audio filters that converts the input format
1429 * to the ao's format, taking into account the current playback_speed.
1430 * sh_audio describes the requested input format of the chain.
1431 * ao describes the requested output format of the chain.
1433 static int build_afilter_chain(struct MPContext *mpctx)
1435 struct sh_audio *sh_audio = mpctx->sh_audio;
1436 struct ao *ao = mpctx->ao;
1437 struct MPOpts *opts = &mpctx->opts;
1438 int new_srate;
1439 int result;
1440 if (!sh_audio) {
1441 mpctx->mixer.afilter = NULL;
1442 return 0;
1444 if (af_control_any_rev(sh_audio->afilter,
1445 AF_CONTROL_PLAYBACK_SPEED | AF_CONTROL_SET,
1446 &opts->playback_speed))
1447 new_srate = sh_audio->samplerate;
1448 else {
1449 new_srate = sh_audio->samplerate * opts->playback_speed;
1450 if (new_srate != ao->samplerate) {
1451 // limits are taken from libaf/af_resample.c
1452 if (new_srate < 8000)
1453 new_srate = 8000;
1454 if (new_srate > 192000)
1455 new_srate = 192000;
1456 opts->playback_speed = (float)new_srate / sh_audio->samplerate;
1459 result = init_audio_filters(sh_audio, new_srate,
1460 &ao->samplerate, &ao->channels, &ao->format);
1461 mpctx->mixer.afilter = sh_audio->afilter;
1462 return result;
1466 typedef struct mp_osd_msg mp_osd_msg_t;
1467 struct mp_osd_msg {
1468 /// Previous message on the stack.
1469 mp_osd_msg_t *prev;
1470 /// Message text.
1471 char *msg;
1472 int id, level, started;
1473 /// Display duration in ms.
1474 unsigned time;
1477 /// OSD message stack.
1478 static mp_osd_msg_t *osd_msg_stack = NULL;
1481 * \brief Add a message on the OSD message stack
1483 * If a message with the same id is already present in the stack
1484 * it is pulled on top of the stack, otherwise a new message is created.
1487 static void set_osd_msg_va(int id, int level, int time, const char *fmt,
1488 va_list ap)
1490 mp_osd_msg_t *msg, *last = NULL;
1492 // look if the id is already in the stack
1493 for (msg = osd_msg_stack; msg && msg->id != id;
1494 last = msg, msg = msg->prev) ;
1495 // not found: alloc it
1496 if (!msg) {
1497 msg = talloc_zero(NULL, mp_osd_msg_t);
1498 msg->prev = osd_msg_stack;
1499 osd_msg_stack = msg;
1500 } else if (last) { // found, but it's not on top of the stack
1501 last->prev = msg->prev;
1502 msg->prev = osd_msg_stack;
1503 osd_msg_stack = msg;
1505 talloc_free(msg->msg);
1506 // write the msg
1507 msg->msg = talloc_vasprintf(msg, fmt, ap);
1508 // set id and time
1509 msg->id = id;
1510 msg->level = level;
1511 msg->time = time;
1515 void set_osd_msg(int id, int level, int time, const char *fmt, ...)
1517 va_list ap;
1518 va_start(ap, fmt);
1519 set_osd_msg_va(id, level, time, fmt, ap);
1520 va_end(ap);
1523 void set_osd_tmsg(int id, int level, int time, const char *fmt, ...)
1525 va_list ap;
1526 va_start(ap, fmt);
1527 set_osd_msg_va(id, level, time, mp_gtext(fmt), ap);
1528 va_end(ap);
1532 * \brief Remove a message from the OSD stack
1534 * This function can be used to get rid of a message right away.
1538 void rm_osd_msg(int id)
1540 mp_osd_msg_t *msg, *last = NULL;
1542 // Search for the msg
1543 for (msg = osd_msg_stack; msg && msg->id != id;
1544 last = msg, msg = msg->prev) ;
1545 if (!msg)
1546 return;
1548 // Detach it from the stack and free it
1549 if (last)
1550 last->prev = msg->prev;
1551 else
1552 osd_msg_stack = msg->prev;
1553 talloc_free(msg);
1557 * \brief Remove all messages from the OSD stack
1561 static void clear_osd_msgs(void)
1563 mp_osd_msg_t *msg = osd_msg_stack, *prev = NULL;
1564 while (msg) {
1565 prev = msg->prev;
1566 talloc_free(msg);
1567 msg = prev;
1569 osd_msg_stack = NULL;
1573 * \brief Get the current message from the OSD stack.
1575 * This function decrements the message timer and destroys the old ones.
1576 * The message that should be displayed is returned (if any).
1580 static mp_osd_msg_t *get_osd_msg(struct MPContext *mpctx)
1582 struct MPOpts *opts = &mpctx->opts;
1583 mp_osd_msg_t *msg, *prev, *last = NULL;
1584 static unsigned last_update = 0;
1585 unsigned now = GetTimerMS();
1586 unsigned diff;
1587 char hidden_dec_done = 0;
1589 if (mpctx->osd_visible) {
1590 // 36000000 means max timed visibility is 1 hour into the future, if
1591 // the difference is greater assume it's wrapped around from below 0
1592 if (mpctx->osd_visible - now > 36000000) {
1593 mpctx->osd_visible = 0;
1594 vo_osd_progbar_type = -1; // disable
1595 vo_osd_changed(OSDTYPE_PROGBAR);
1596 mpctx->osd_function = mpctx->paused ? OSD_PAUSE : OSD_PLAY;
1599 if (mpctx->osd_show_percentage_until - now > 36000000)
1600 mpctx->osd_show_percentage_until = 0;
1602 if (!last_update)
1603 last_update = now;
1604 diff = now >= last_update ? now - last_update : 0;
1606 last_update = now;
1608 // Look for the first message in the stack with high enough level.
1609 for (msg = osd_msg_stack; msg; last = msg, msg = prev) {
1610 prev = msg->prev;
1611 if (msg->level > opts->osd_level && hidden_dec_done)
1612 continue;
1613 // The message has a high enough level or it is the first hidden one
1614 // in both cases we decrement the timer or kill it.
1615 if (!msg->started || msg->time > diff) {
1616 if (msg->started)
1617 msg->time -= diff;
1618 else
1619 msg->started = 1;
1620 // display it
1621 if (msg->level <= opts->osd_level)
1622 return msg;
1623 hidden_dec_done = 1;
1624 continue;
1626 // kill the message
1627 talloc_free(msg);
1628 if (last) {
1629 last->prev = prev;
1630 msg = last;
1631 } else {
1632 osd_msg_stack = prev;
1633 msg = NULL;
1636 // Nothing found
1637 return NULL;
1641 * \brief Display the OSD bar.
1643 * Display the OSD bar or fall back on a simple message.
1647 void set_osd_bar(struct MPContext *mpctx, int type, const char *name,
1648 double min, double max, double val)
1650 struct MPOpts *opts = &mpctx->opts;
1651 if (opts->osd_level < 1)
1652 return;
1654 if (mpctx->sh_video) {
1655 mpctx->osd_visible = (GetTimerMS() + 1000) | 1;
1656 vo_osd_progbar_type = type;
1657 vo_osd_progbar_value = 256 * (val - min) / (max - min);
1658 vo_osd_changed(OSDTYPE_PROGBAR);
1659 return;
1662 set_osd_msg(OSD_MSG_BAR, 1, opts->osd_duration, "%s: %d %%",
1663 name, ROUND(100 * (val - min) / (max - min)));
1667 * \brief Display text subtitles on the OSD
1669 void set_osd_subtitle(struct MPContext *mpctx, subtitle *subs)
1671 int i;
1672 vo_sub = subs;
1673 vo_osd_changed(OSDTYPE_SUBTITLE);
1674 if (!mpctx->sh_video) {
1675 // reverse order, since newest set_osd_msg is displayed first
1676 for (i = SUB_MAX_TEXT - 1; i >= 0; i--) {
1677 if (!subs || i >= subs->lines || !subs->text[i])
1678 rm_osd_msg(OSD_MSG_SUB_BASE + i);
1679 else {
1680 // HACK: currently display time for each sub line
1681 // except the last is set to 2 seconds.
1682 int display_time = i == subs->lines - 1 ? 180000 : 2000;
1683 set_osd_msg(OSD_MSG_SUB_BASE + i, 1, display_time,
1684 "%s", subs->text[i]);
1691 * \brief Update the OSD message line.
1693 * This function displays the current message on the vo OSD or on the term.
1694 * If the stack is empty and the OSD level is high enough the timer
1695 * is displayed (only on the vo OSD).
1699 static void update_osd_msg(struct MPContext *mpctx)
1701 struct MPOpts *opts = &mpctx->opts;
1702 mp_osd_msg_t *msg;
1703 struct osd_state *osd = mpctx->osd;
1704 char osd_text_timer[128];
1706 if (mpctx->add_osd_seek_info) {
1707 double percentage = get_percent_pos(mpctx);
1708 set_osd_bar(mpctx, 0, "Position", 0, 100, percentage);
1709 if (mpctx->sh_video)
1710 mpctx->osd_show_percentage_until = (GetTimerMS() + 1000) | 1;
1711 mpctx->add_osd_seek_info = false;
1714 // Look if we have a msg
1715 if ((msg = get_osd_msg(mpctx))) {
1716 if (strcmp(osd->osd_text, msg->msg)) {
1717 osd_set_text(osd, msg->msg);
1718 if (mpctx->sh_video)
1719 vo_osd_changed(OSDTYPE_OSD);
1720 else if (opts->term_osd)
1721 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "%s%s\n", opts->term_osd_esc,
1722 msg->msg);
1724 return;
1727 if (mpctx->sh_video) {
1728 // fallback on the timer
1729 if (opts->osd_level >= 2) {
1730 int len = get_time_length(mpctx);
1731 int percentage = -1;
1732 char percentage_text[10];
1733 char fractions_text[4];
1734 double fpts = get_current_time(mpctx);
1735 int pts = fpts;
1737 if (mpctx->osd_show_percentage_until)
1738 percentage = get_percent_pos(mpctx);
1740 if (percentage >= 0)
1741 snprintf(percentage_text, 9, " (%d%%)", percentage);
1742 else
1743 percentage_text[0] = 0;
1745 if (opts->osd_fractions == 1) {
1746 //print fractions as sub-second timestamp
1747 snprintf(fractions_text, sizeof(fractions_text), ".%02d",
1748 (int)((fpts - pts) * 100));
1749 } else if (opts->osd_fractions == 2) {
1750 /* Print fractions by estimating the frame count within the
1751 * second.
1753 * Rounding or cutting off numbers after the decimal point
1754 * causes problems because of float's precision and movies
1755 * whose first frame is not exactly at timestamp 0. Therefore,
1756 * we add 0.2 and cut off at the decimal point, which proved
1757 * to be good heuristic.
1759 double fps = mpctx->sh_video->fps;
1760 if (fps <= 1 || fps > 99)
1761 strcpy(fractions_text, ".??");
1762 else
1763 snprintf(fractions_text, sizeof(fractions_text), ".%02d",
1764 (int) ((fpts - pts) * fps + 0.2));
1765 } else {
1766 //do not print fractions
1767 fractions_text[0] = 0;
1770 if (opts->osd_level == 3)
1771 snprintf(osd_text_timer, sizeof(osd_text_timer),
1772 "%c %02d:%02d:%02d%s / %02d:%02d:%02d%s",
1773 mpctx->osd_function, pts / 3600, (pts / 60) % 60, pts % 60,
1774 fractions_text, len / 3600, (len / 60) % 60, len % 60,
1775 percentage_text);
1776 else
1777 snprintf(osd_text_timer, sizeof(osd_text_timer),
1778 "%c %02d:%02d:%02d%s%s",
1779 mpctx->osd_function, pts / 3600, (pts / 60) % 60,
1780 pts % 60, fractions_text, percentage_text);
1781 } else
1782 osd_text_timer[0] = 0;
1784 if (strcmp(osd->osd_text, osd_text_timer)) {
1785 osd_set_text(osd, osd_text_timer);
1786 vo_osd_changed(OSDTYPE_OSD);
1788 return;
1791 // Clear the term osd line
1792 if (opts->term_osd && osd->osd_text[0]) {
1793 osd->osd_text[0] = 0;
1794 printf("%s\n", opts->term_osd_esc);
1799 void reinit_audio_chain(struct MPContext *mpctx)
1801 struct MPOpts *opts = &mpctx->opts;
1802 struct ao *ao;
1803 if (!mpctx->sh_audio)
1804 return;
1805 if (!(mpctx->initialized_flags & INITIALIZED_ACODEC)) {
1806 current_module = "init_audio_codec";
1807 mp_msg(MSGT_CPLAYER, MSGL_INFO, "==========================================================================\n");
1808 if (!init_best_audio_codec(mpctx->sh_audio, audio_codec_list, audio_fm_list))
1809 goto init_error;
1810 mpctx->initialized_flags |= INITIALIZED_ACODEC;
1811 mp_msg(MSGT_CPLAYER, MSGL_INFO, "==========================================================================\n");
1815 current_module = "af_preinit";
1816 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1817 mpctx->initialized_flags |= INITIALIZED_AO;
1818 mpctx->ao = ao_create();
1819 mpctx->ao->samplerate = force_srate;
1820 mpctx->ao->format = opts->audio_output_format;
1822 ao = mpctx->ao;
1824 // first init to detect best values
1825 if (!init_audio_filters(mpctx->sh_audio, // preliminary init
1826 // input:
1827 mpctx->sh_audio->samplerate,
1828 // output:
1829 &ao->samplerate, &ao->channels, &ao->format)) {
1830 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Error at audio filter chain "
1831 "pre-init!\n");
1832 exit_player(mpctx, EXIT_ERROR);
1834 if (!ao->initialized) {
1835 current_module = "ao2_init";
1836 ao->buffersize = opts->ao_buffersize;
1837 ao_init(ao, opts->audio_driver_list);
1838 if (!ao->initialized) {
1839 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
1840 "Could not open/initialize audio device -> no sound.\n");
1841 goto init_error;
1843 ao->buffer.start = talloc_new(ao);
1844 mp_msg(MSGT_CPLAYER, MSGL_INFO,
1845 "AO: [%s] %dHz %dch %s (%d bytes per sample)\n",
1846 ao->driver->info->short_name,
1847 ao->samplerate, ao->channels,
1848 af_fmt2str_short(ao->format),
1849 af_fmt2bits(ao->format) / 8);
1850 mp_msg(MSGT_CPLAYER, MSGL_V, "AO: Description: %s\nAO: Author: %s\n",
1851 ao->driver->info->name, ao->driver->info->author);
1852 if (strlen(ao->driver->info->comment) > 0)
1853 mp_msg(MSGT_CPLAYER, MSGL_V, "AO: Comment: %s\n",
1854 ao->driver->info->comment);
1857 // init audio filters:
1858 current_module = "af_init";
1859 if (!build_afilter_chain(mpctx)) {
1860 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
1861 "Couldn't find matching filter/ao format!\n");
1862 goto init_error;
1864 mpctx->mixer.ao = ao;
1865 mpctx->mixer.volstep = volstep;
1866 mpctx->syncing_audio = true;
1867 return;
1869 init_error:
1870 uninit_player(mpctx, INITIALIZED_ACODEC | INITIALIZED_AO);
1871 mpctx->sh_audio = mpctx->d_audio->sh = NULL; // -> nosound
1872 mpctx->d_audio->id = -2;
1876 // Return pts value corresponding to the end point of audio written to the
1877 // ao so far.
1878 static double written_audio_pts(struct MPContext *mpctx)
1880 sh_audio_t *sh_audio = mpctx->sh_audio;
1881 demux_stream_t *d_audio = mpctx->d_audio;
1882 // first calculate the end pts of audio that has been output by decoder
1883 double a_pts = sh_audio->pts;
1884 if (a_pts != MP_NOPTS_VALUE)
1885 // Good, decoder supports new way of calculating audio pts.
1886 // sh_audio->pts is the timestamp of the latest input packet with
1887 // known pts that the decoder has decoded. sh_audio->pts_bytes is
1888 // the amount of bytes the decoder has written after that timestamp.
1889 a_pts += sh_audio->pts_bytes / (double) sh_audio->o_bps;
1890 else {
1891 // Decoder doesn't support new way of calculating pts (or we're
1892 // being called before it has decoded anything with known timestamp).
1893 // Use the old method of audio pts calculation: take the timestamp
1894 // of last packet with known pts the decoder has read data from,
1895 // and add amount of bytes read after the beginning of that packet
1896 // divided by input bps. This will be inaccurate if the input/output
1897 // ratio is not constant for every audio packet or if it is constant
1898 // but not accurately known in sh_audio->i_bps.
1900 a_pts = d_audio->pts;
1901 if (a_pts == MP_NOPTS_VALUE)
1902 return a_pts;
1904 // ds_tell_pts returns bytes read after last timestamp from
1905 // demuxing layer, decoder might use sh_audio->a_in_buffer for bytes
1906 // it has read but not decoded
1907 if (sh_audio->i_bps)
1908 a_pts += (ds_tell_pts(d_audio) - sh_audio->a_in_buffer_len) /
1909 (double)sh_audio->i_bps;
1911 // Now a_pts hopefully holds the pts for end of audio from decoder.
1912 // Substract data in buffers between decoder and audio out.
1914 // Decoded but not filtered
1915 a_pts -= sh_audio->a_buffer_len / (double)sh_audio->o_bps;
1917 // Data buffered in audio filters, measured in bytes of "missing" output
1918 double buffered_output = af_calc_delay(sh_audio->afilter);
1920 // Data that was ready for ao but was buffered because ao didn't fully
1921 // accept everything to internal buffers yet
1922 buffered_output += mpctx->ao->buffer.len;
1924 // Filters divide audio length by playback_speed, so multiply by it
1925 // to get the length in original units without speedup or slowdown
1926 a_pts -= buffered_output * mpctx->opts.playback_speed / mpctx->ao->bps;
1928 return a_pts + mpctx->video_offset;
1931 // Return pts value corresponding to currently playing audio.
1932 double playing_audio_pts(struct MPContext *mpctx)
1934 double pts = written_audio_pts(mpctx);
1935 if (pts == MP_NOPTS_VALUE)
1936 return pts;
1937 return pts - mpctx->opts.playback_speed *ao_get_delay(mpctx->ao);
1940 static bool is_av_sub(int type)
1942 return type == 'b' || type == 'p' || type == 'x';
1945 void update_subtitles(struct MPContext *mpctx, double refpts,
1946 double sub_offset, bool reset)
1948 struct MPOpts *opts = &mpctx->opts;
1949 struct sh_video *sh_video = mpctx->sh_video;
1950 struct demux_stream *d_sub = mpctx->d_sub;
1951 double curpts = refpts + sub_delay;
1952 unsigned char *packet = NULL;
1953 int len;
1954 struct sh_sub *sh_sub = d_sub->sh;
1955 int type = sh_sub ? sh_sub->type : 'v';
1956 static subtitle subs;
1957 if (reset) {
1958 if (sh_sub)
1959 sub_reset(sh_sub, mpctx->osd);
1960 sub_clear_text(&subs, MP_NOPTS_VALUE);
1961 if (vo_sub)
1962 set_osd_subtitle(mpctx, NULL);
1963 if (vo_spudec) {
1964 spudec_reset(vo_spudec);
1965 vo_osd_changed(OSDTYPE_SPU);
1967 #ifdef CONFIG_FFMPEG
1968 if (is_av_sub(type))
1969 reset_avsub(sh_sub);
1970 #endif
1971 return;
1973 // find sub
1974 if (mpctx->subdata) {
1975 if (sub_fps == 0)
1976 sub_fps = sh_video ? sh_video->fps : 25;
1977 current_module = "find_sub";
1978 find_sub(mpctx, mpctx->subdata, curpts *
1979 (mpctx->subdata->sub_uses_time ? 100. : sub_fps));
1980 if (vo_sub)
1981 mpctx->vo_sub_last = vo_sub;
1984 // DVD sub:
1985 if (vobsub_id >= 0 || type == 'v') {
1986 int timestamp;
1987 current_module = "spudec";
1988 /* Get a sub packet from the DVD or a vobsub */
1989 while (1) {
1990 // Vobsub
1991 len = 0;
1992 if (vo_vobsub) {
1993 if (curpts >= 0) {
1994 len = vobsub_get_packet(vo_vobsub, curpts,
1995 (void **)&packet, &timestamp);
1996 if (len > 0)
1997 mp_dbg(MSGT_CPLAYER, MSGL_V, "\rVOB sub: len=%d "
1998 "v_pts=%5.3f v_timer=%5.3f sub=%5.3f ts=%d \n",
1999 len, refpts, sh_video->timer,
2000 timestamp / 90000.0, timestamp);
2002 } else {
2003 // DVD sub
2004 len = ds_get_packet_sub(d_sub, (unsigned char **)&packet);
2005 if (len > 0) {
2006 // XXX This is wrong, sh_video->pts can be arbitrarily
2007 // much behind demuxing position. Unfortunately using
2008 // d_video->pts which would have been the simplest
2009 // improvement doesn't work because mpeg specific hacks
2010 // in video.c set d_video->pts to 0.
2011 float x = d_sub->pts - refpts;
2012 if (x > -20 && x < 20) // prevent missing subs on pts reset
2013 timestamp = 90000 * d_sub->pts;
2014 else
2015 timestamp = 90000 * curpts;
2016 mp_dbg(MSGT_CPLAYER, MSGL_V, "\rDVD sub: len=%d "
2017 "v_pts=%5.3f s_pts=%5.3f ts=%d \n", len,
2018 refpts, d_sub->pts, timestamp);
2021 if (len <= 0 || !packet)
2022 break;
2023 // create it only here, since with some broken demuxers we might
2024 // type = v but no DVD sub and we currently do not change the
2025 // "original frame size" ever after init, leading to wrong-sized
2026 // PGS subtitles.
2027 if (!vo_spudec)
2028 vo_spudec = spudec_new(NULL);
2029 if (vo_vobsub || timestamp >= 0)
2030 spudec_assemble(vo_spudec, packet, len, timestamp);
2032 } else if (is_text_sub(type) || is_av_sub(type) || type == 'd') {
2033 if (type == 'd' && !d_sub->demuxer->teletext) {
2034 tt_stream_props tsp = { 0 };
2035 void *ptr = &tsp;
2036 if (teletext_control(NULL, TV_VBI_CONTROL_START, &ptr) ==
2037 VBI_CONTROL_TRUE)
2038 d_sub->demuxer->teletext = ptr;
2040 if (d_sub->non_interleaved)
2041 ds_get_next_pts(d_sub);
2043 while (d_sub->first) {
2044 double subpts = ds_get_next_pts(d_sub) + sub_offset;
2045 if (subpts > curpts) {
2046 // Libass handled subs can be fed to it in advance
2047 if (!opts->ass_enabled || !is_text_sub(type))
2048 break;
2049 // Try to avoid demuxing whole file at once
2050 if (d_sub->non_interleaved && subpts > curpts + 1)
2051 break;
2053 double duration = d_sub->first->duration;
2054 len = ds_get_packet_sub(d_sub, &packet);
2055 if (is_av_sub(type)) {
2056 #ifdef CONFIG_FFMPEG
2057 int ret = decode_avsub(sh_sub, packet, len, subpts, duration);
2058 if (ret < 0)
2059 mp_msg(MSGT_SPUDEC, MSGL_WARN, "lavc failed decoding "
2060 "subtitle\n");
2061 #endif
2062 continue;
2064 if (type == 'm') {
2065 if (len < 2)
2066 continue;
2067 len = FFMIN(len - 2, AV_RB16(packet));
2068 packet += 2;
2070 if (type == 'd') {
2071 if (d_sub->demuxer->teletext) {
2072 uint8_t *p = packet;
2073 p++;
2074 len--;
2075 while (len >= 46) {
2076 int sublen = p[1];
2077 if (p[0] == 2 || p[0] == 3)
2078 teletext_control(d_sub->demuxer->teletext,
2079 TV_VBI_CONTROL_DECODE_DVB, p + 2);
2080 p += sublen + 2;
2081 len -= sublen + 2;
2084 continue;
2086 if (sh_sub && sh_sub->active) {
2087 sub_decode(sh_sub, mpctx->osd, packet, len, subpts, duration);
2088 continue;
2090 if (subpts != MP_NOPTS_VALUE) {
2091 if (duration < 0)
2092 sub_clear_text(&subs, MP_NOPTS_VALUE);
2093 if (type == 'a') { // ssa/ass subs without libass => convert to plaintext
2094 int i;
2095 unsigned char *p = packet;
2096 for (i = 0; i < 8 && *p != '\0'; p++)
2097 if (*p == ',')
2098 i++;
2099 if (*p == '\0') /* Broken line? */
2100 continue;
2101 len -= p - packet;
2102 packet = p;
2104 double endpts = MP_NOPTS_VALUE;
2105 if (subpts != MP_NOPTS_VALUE && duration >= 0)
2106 endpts = subpts + duration;
2107 sub_add_text(&subs, packet, len, endpts);
2108 set_osd_subtitle(mpctx, &subs);
2110 if (d_sub->non_interleaved)
2111 ds_get_next_pts(d_sub);
2113 if (!opts->ass_enabled)
2114 if (sub_clear_text(&subs, curpts))
2115 set_osd_subtitle(mpctx, &subs);
2117 if (vo_spudec) {
2118 spudec_heartbeat(vo_spudec, 90000 * curpts);
2119 if (spudec_changed(vo_spudec))
2120 vo_osd_changed(OSDTYPE_SPU);
2123 current_module = NULL;
2126 static void update_teletext(sh_video_t *sh_video, demuxer_t *demuxer, int reset)
2128 int page_changed;
2130 if (!demuxer->teletext)
2131 return;
2133 //Also forcing page update when such ioctl is not supported or call error occured
2134 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_IS_CHANGED,
2135 &page_changed) != VBI_CONTROL_TRUE)
2136 page_changed = 1;
2138 if (!page_changed)
2139 return;
2141 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_VBIPAGE,
2142 &vo_osd_teletext_page) != VBI_CONTROL_TRUE)
2143 vo_osd_teletext_page = NULL;
2144 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_HALF_PAGE,
2145 &vo_osd_teletext_half) != VBI_CONTROL_TRUE)
2146 vo_osd_teletext_half = 0;
2147 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_MODE,
2148 &vo_osd_teletext_mode) != VBI_CONTROL_TRUE)
2149 vo_osd_teletext_mode = 0;
2150 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_FORMAT,
2151 &vo_osd_teletext_format) != VBI_CONTROL_TRUE)
2152 vo_osd_teletext_format = 0;
2153 vo_osd_changed(OSDTYPE_TELETEXT);
2155 teletext_control(demuxer->teletext, TV_VBI_CONTROL_MARK_UNCHANGED, NULL);
2158 static int check_framedrop(struct MPContext *mpctx, double frame_time)
2160 struct MPOpts *opts = &mpctx->opts;
2161 // check for frame-drop:
2162 current_module = "check_framedrop";
2163 if (mpctx->sh_audio && !mpctx->ao->untimed && !mpctx->d_audio->eof) {
2164 static int dropped_frames;
2165 float delay = opts->playback_speed * ao_get_delay(mpctx->ao);
2166 float d = delay - mpctx->delay;
2167 ++total_frame_cnt;
2168 // we should avoid dropping too many frames in sequence unless we
2169 // are too late. and we allow 100ms A-V delay here:
2170 if (d < -dropped_frames * frame_time - 0.100 && !mpctx->paused
2171 && !mpctx->restart_playback) {
2172 ++drop_frame_cnt;
2173 ++dropped_frames;
2174 return frame_dropping;
2175 } else
2176 dropped_frames = 0;
2178 return 0;
2182 #ifdef HAVE_RTC
2183 int rtc_fd = -1;
2184 #endif
2186 static float timing_sleep(struct MPContext *mpctx, float time_frame)
2188 #ifdef HAVE_RTC
2189 if (rtc_fd >= 0) {
2190 // -------- RTC -----------
2191 current_module = "sleep_rtc";
2192 while (time_frame > 0.000) {
2193 unsigned long rtc_ts;
2194 if (read(rtc_fd, &rtc_ts, sizeof(rtc_ts)) <= 0)
2195 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
2196 "Linux RTC read error: %s\n", strerror(errno));
2197 time_frame -= get_relative_time(mpctx);
2199 } else
2200 #endif
2202 // assume kernel HZ=100 for softsleep, works with larger HZ but with
2203 // unnecessarily high CPU usage
2204 struct MPOpts *opts = &mpctx->opts;
2205 float margin = opts->softsleep ? 0.011 : 0;
2206 current_module = "sleep_timer";
2207 while (time_frame > margin) {
2208 usec_sleep(1000000 * (time_frame - margin));
2209 time_frame -= get_relative_time(mpctx);
2211 if (opts->softsleep) {
2212 current_module = "sleep_soft";
2213 if (time_frame < 0)
2214 mp_tmsg(MSGT_AVSYNC, MSGL_WARN,
2215 "Warning! Softsleep underflow!\n");
2216 while (time_frame > 0)
2217 time_frame -= get_relative_time(mpctx); // burn the CPU
2220 return time_frame;
2223 static int select_subtitle(MPContext *mpctx)
2225 struct MPOpts *opts = &mpctx->opts;
2226 // find the best sub to use
2227 int id;
2228 int found = 0;
2229 mpctx->global_sub_pos = -1; // no subs by default
2230 if (vobsub_id >= 0) {
2231 // if user asks for a vobsub id, use that first.
2232 id = vobsub_id;
2233 found = mp_property_do("sub_vob", M_PROPERTY_SET, &id, mpctx) ==
2234 M_PROPERTY_OK;
2237 if (!found && opts->sub_id >= 0) {
2238 // if user asks for a dvd sub id, use that next.
2239 id = opts->sub_id;
2240 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) ==
2241 M_PROPERTY_OK;
2244 if (!found) {
2245 // if there are text subs to use, use those. (autosubs come last here)
2246 id = 0;
2247 found = mp_property_do("sub_file", M_PROPERTY_SET, &id, mpctx) ==
2248 M_PROPERTY_OK;
2251 if (!found && opts->sub_id == -1) {
2252 // finally select subs by language and container hints
2253 if (opts->sub_id == -1)
2254 opts->sub_id =
2255 demuxer_sub_track_by_lang_and_default(mpctx->d_sub->demuxer,
2256 opts->sub_lang);
2257 if (opts->sub_id >= 0) {
2258 id = opts->sub_id;
2259 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) ==
2260 M_PROPERTY_OK;
2263 return found;
2266 #ifdef CONFIG_DVDNAV
2267 #ifndef FF_B_TYPE
2268 #define FF_B_TYPE 3
2269 #endif
2270 /// store decoded video image
2271 static mp_image_t *mp_dvdnav_copy_mpi(mp_image_t *to_mpi,
2272 mp_image_t *from_mpi)
2274 mp_image_t *mpi;
2276 /// Do not store B-frames
2277 if (from_mpi->pict_type == FF_B_TYPE)
2278 return to_mpi;
2280 if (to_mpi &&
2281 to_mpi->w == from_mpi->w &&
2282 to_mpi->h == from_mpi->h &&
2283 to_mpi->imgfmt == from_mpi->imgfmt)
2284 mpi = to_mpi;
2285 else {
2286 if (to_mpi)
2287 free_mp_image(to_mpi);
2288 if (from_mpi->w == 0 || from_mpi->h == 0)
2289 return NULL;
2290 mpi = alloc_mpi(from_mpi->w, from_mpi->h, from_mpi->imgfmt);
2293 copy_mpi(mpi, from_mpi);
2294 return mpi;
2297 static void mp_dvdnav_reset_stream(MPContext *ctx)
2299 struct MPOpts *opts = &ctx->opts;
2300 if (ctx->sh_video) {
2301 /// clear video pts
2302 ctx->d_video->pts = 0.0f;
2303 ctx->sh_video->pts = 0.0f;
2304 ctx->sh_video->i_pts = 0.0f;
2305 ctx->sh_video->last_pts = 0.0f;
2306 ctx->sh_video->num_buffered_pts = 0;
2307 ctx->sh_video->num_frames = 0;
2308 ctx->sh_video->num_frames_decoded = 0;
2309 ctx->sh_video->timer = 0.0f;
2310 ctx->sh_video->stream_delay = 0.0f;
2311 ctx->sh_video->timer = 0;
2312 ctx->demuxer->stream_pts = MP_NOPTS_VALUE;
2315 if (ctx->sh_audio) {
2316 /// free audio packets and reset
2317 ds_free_packs(ctx->d_audio);
2318 audio_delay -= ctx->sh_audio->stream_delay;
2319 ctx->delay = -audio_delay;
2320 ao_reset(ctx->ao);
2321 resync_audio_stream(ctx->sh_audio);
2324 audio_delay = 0.0f;
2325 ctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(ctx->stream);
2326 if (opts->sub_lang && opts->sub_id == dvdsub_lang_id) {
2327 dvdsub_lang_id = mp_dvdnav_sid_from_lang(ctx->stream, opts->sub_lang);
2328 if (dvdsub_lang_id != opts->sub_id) {
2329 opts->sub_id = dvdsub_lang_id;
2330 select_subtitle(ctx);
2334 /// clear all EOF related flags
2335 ctx->d_video->eof = ctx->d_audio->eof = ctx->stream->eof = 0;
2338 /// Restore last decoded DVDNAV (still frame)
2339 static mp_image_t *mp_dvdnav_restore_smpi(struct MPContext *mpctx,
2340 int *in_size,
2341 unsigned char **start,
2342 mp_image_t *decoded_frame)
2344 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2345 return decoded_frame;
2347 /// a change occurred in dvdnav stream
2348 if (mp_dvdnav_cell_has_changed(mpctx->stream, 0)) {
2349 mp_dvdnav_read_wait(mpctx->stream, 1, 1);
2350 mp_dvdnav_context_free(mpctx);
2351 mp_dvdnav_reset_stream(mpctx);
2352 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
2353 mp_dvdnav_cell_has_changed(mpctx->stream, 1);
2356 if (*in_size < 0) {
2357 float len;
2359 /// Display still frame, if any
2360 if (mpctx->nav_smpi && !mpctx->nav_buffer)
2361 decoded_frame = mpctx->nav_smpi;
2363 /// increment video frame : continue playing after still frame
2364 len = get_time_length(mpctx);
2365 if (mpctx->sh_video->pts >= len &&
2366 mpctx->sh_video->pts > 0.0 && len > 0.0) {
2367 mp_dvdnav_skip_still(mpctx->stream);
2368 mp_dvdnav_skip_wait(mpctx->stream);
2370 mpctx->sh_video->pts += 1 / mpctx->sh_video->fps;
2372 if (mpctx->nav_buffer) {
2373 *start = mpctx->nav_start;
2374 *in_size = mpctx->nav_in_size;
2375 if (mpctx->nav_start)
2376 memcpy(*start, mpctx->nav_buffer, mpctx->nav_in_size);
2380 return decoded_frame;
2383 /// Save last decoded DVDNAV (still frame)
2384 static void mp_dvdnav_save_smpi(struct MPContext *mpctx, int in_size,
2385 unsigned char *start,
2386 mp_image_t *decoded_frame)
2388 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2389 return;
2391 free(mpctx->nav_buffer);
2392 mpctx->nav_buffer = NULL;
2393 mpctx->nav_start = NULL;
2394 mpctx->nav_in_size = -1;
2396 if (in_size > 0)
2397 mpctx->nav_buffer = malloc(in_size);
2398 if (mpctx->nav_buffer) {
2399 mpctx->nav_start = start;
2400 mpctx->nav_in_size = in_size;
2401 memcpy(mpctx->nav_buffer, start, in_size);
2404 if (decoded_frame && mpctx->nav_smpi != decoded_frame)
2405 mpctx->nav_smpi = mp_dvdnav_copy_mpi(mpctx->nav_smpi, decoded_frame);
2407 #endif /* CONFIG_DVDNAV */
2409 /* Modify video timing to match the audio timeline. There are two main
2410 * reasons this is needed. First, video and audio can start from different
2411 * positions at beginning of file or after a seek (MPlayer starts both
2412 * immediately even if they have different pts). Second, the file can have
2413 * audio timestamps that are inconsistent with the duration of the audio
2414 * packets, for example two consecutive timestamp values differing by
2415 * one second but only a packet with enough samples for half a second
2416 * of playback between them.
2418 static void adjust_sync(struct MPContext *mpctx, double frame_time)
2420 current_module = "av_sync";
2422 if (!mpctx->sh_audio || mpctx->syncing_audio)
2423 return;
2425 double a_pts = written_audio_pts(mpctx) - mpctx->delay;
2426 double v_pts = mpctx->sh_video->pts;
2427 double av_delay = a_pts - v_pts;
2428 // Try to sync vo_flip() so it will *finish* at given time
2429 av_delay += mpctx->last_vo_flip_duration;
2430 av_delay -= audio_delay; // This much pts difference is desired
2432 double change = av_delay * 0.1;
2433 double max_change = default_max_pts_correction >= 0 ?
2434 default_max_pts_correction : frame_time * 0.1;
2435 if (change < -max_change)
2436 change = -max_change;
2437 else if (change > max_change)
2438 change = max_change;
2439 mpctx->delay += change;
2440 mpctx->total_avsync_change += change;
2443 static int write_to_ao(struct MPContext *mpctx, void *data, int len, int flags,
2444 double pts)
2446 if (mpctx->paused)
2447 return 0;
2448 struct ao *ao = mpctx->ao;
2449 double bps = ao->bps / mpctx->opts.playback_speed;
2450 ao->pts = pts;
2451 // hack used by some mpeg-writing AOs
2452 ao->brokenpts = ((mpctx->sh_video ? mpctx->sh_video->timer : 0) +
2453 mpctx->delay) * 90000.0;
2454 int played = ao_play(mpctx->ao, data, len, flags);
2455 if (played > 0) {
2456 mpctx->delay += played / bps;
2457 // Keep correct pts for remaining data - could be used to flush
2458 // remaining buffer when closing ao.
2459 ao->pts += played / bps;
2461 return played;
2464 #define ASYNC_PLAY_DONE -3
2465 static int audio_start_sync(struct MPContext *mpctx, int playsize)
2467 struct ao *ao = mpctx->ao;
2468 struct MPOpts *opts = &mpctx->opts;
2469 sh_audio_t * const sh_audio = mpctx->sh_audio;
2470 int res;
2472 // Timing info may not be set without
2473 res = decode_audio(sh_audio, &ao->buffer, 1);
2474 if (res < 0)
2475 return res;
2477 int bytes;
2478 bool did_retry = false;
2479 double written_pts;
2480 double bps = ao->bps / opts->playback_speed;
2481 while (1) {
2482 written_pts = written_audio_pts(mpctx);
2483 double ptsdiff = written_pts - mpctx->sh_video->pts - mpctx->delay
2484 - audio_delay;
2485 bytes = ptsdiff * bps;
2486 bytes -= bytes % (ao->channels * af_fmt2bits(ao->format) / 8);
2488 // ogg demuxers give packets without timing
2489 if (written_pts <= 1 && sh_audio->pts == MP_NOPTS_VALUE) {
2490 if (!did_retry) {
2491 // Try to read more data to see packets that have pts
2492 int res = decode_audio(sh_audio, &ao->buffer, ao->bps);
2493 if (res < 0)
2494 return res;
2495 did_retry = true;
2496 continue;
2498 bytes = 0;
2501 if (fabs(ptsdiff) > 300) // pts reset or just broken?
2502 bytes = 0;
2504 if (bytes > 0)
2505 break;
2507 mpctx->syncing_audio = false;
2508 int a = FFMIN(-bytes, FFMAX(playsize, 20000));
2509 int res = decode_audio(sh_audio, &ao->buffer, a);
2510 bytes += ao->buffer.len;
2511 if (bytes >= 0) {
2512 memmove(ao->buffer.start,
2513 ao->buffer.start + ao->buffer.len - bytes, bytes);
2514 ao->buffer.len = bytes;
2515 if (res < 0)
2516 return res;
2517 return decode_audio(sh_audio, &ao->buffer, playsize);
2519 ao->buffer.len = 0;
2520 if (res < 0)
2521 return res;
2523 int fillbyte = 0;
2524 if ((ao->format & AF_FORMAT_SIGN_MASK) == AF_FORMAT_US)
2525 fillbyte = 0x80;
2526 if (bytes >= playsize) {
2527 /* This case could fall back to the one below with
2528 * bytes = playsize, but then silence would keep accumulating
2529 * in a_out_buffer if the AO accepts less data than it asks for
2530 * in playsize. */
2531 char *p = malloc(playsize);
2532 memset(p, fillbyte, playsize);
2533 write_to_ao(mpctx, p, playsize, 0, written_pts - bytes / bps);
2534 free(p);
2535 return ASYNC_PLAY_DONE;
2537 mpctx->syncing_audio = false;
2538 decode_audio_prepend_bytes(&ao->buffer, bytes, fillbyte);
2539 return decode_audio(sh_audio, &ao->buffer, playsize);
2542 static int fill_audio_out_buffers(struct MPContext *mpctx)
2544 struct MPOpts *opts = &mpctx->opts;
2545 struct ao *ao = mpctx->ao;
2546 unsigned int t;
2547 double tt;
2548 int playsize;
2549 int playflags = 0;
2550 bool audio_eof = false;
2551 bool partial_fill = false;
2552 sh_audio_t * const sh_audio = mpctx->sh_audio;
2553 bool modifiable_audio_format = !(ao->format & AF_FORMAT_SPECIAL_MASK);
2554 int unitsize = ao->channels * af_fmt2bits(ao->format) / 8;
2556 current_module = "play_audio";
2558 if (ao->untimed && mpctx->sh_video && mpctx->delay > 0)
2559 return 0;
2561 // hack used by some mpeg-writing AOs
2562 ao->brokenpts = ((mpctx->sh_video ? mpctx->sh_video->timer : 0) +
2563 mpctx->delay) * 90000.0;
2565 if (mpctx->paused)
2566 playsize = 1; // just initialize things (audio pts at least)
2567 else
2568 playsize = ao_get_space(ao);
2570 // Fill buffer if needed:
2571 current_module = "decode_audio";
2572 t = GetTimer();
2574 if (!opts->initial_audio_sync || !modifiable_audio_format)
2575 mpctx->syncing_audio = false;
2577 int res;
2578 if (mpctx->syncing_audio && mpctx->sh_video)
2579 res = audio_start_sync(mpctx, playsize);
2580 else
2581 res = decode_audio(sh_audio, &ao->buffer, playsize);
2582 if (res < 0) { // EOF, error or format change
2583 if (res == -2) {
2584 /* The format change isn't handled too gracefully. A more precise
2585 * implementation would require draining buffered old-format audio
2586 * while displaying video, then doing the output format switch.
2588 uninit_player(mpctx, INITIALIZED_AO);
2589 reinit_audio_chain(mpctx);
2590 return -1;
2591 } else if (res == ASYNC_PLAY_DONE)
2592 return 0;
2593 else if (mpctx->d_audio->eof)
2594 audio_eof = true;
2596 t = GetTimer() - t;
2597 tt = t * 0.000001f;
2598 audio_time_usage += tt;
2599 if (mpctx->timeline && modifiable_audio_format) {
2600 double endpts = mpctx->timeline[mpctx->timeline_part + 1].start;
2601 double bytes = (endpts - written_audio_pts(mpctx) + audio_delay)
2602 * ao->bps / opts->playback_speed;
2603 if (playsize > bytes) {
2604 playsize = FFMAX(bytes, 0);
2605 playflags |= AOPLAY_FINAL_CHUNK;
2606 audio_eof = true;
2607 partial_fill = true;
2611 assert(ao->buffer.len % unitsize == 0);
2612 if (playsize > ao->buffer.len) {
2613 partial_fill = true;
2614 playsize = ao->buffer.len;
2615 if (audio_eof)
2616 playflags |= AOPLAY_FINAL_CHUNK;
2618 playsize -= playsize % unitsize;
2619 if (!playsize)
2620 return partial_fill && audio_eof ? -2 : -partial_fill;
2622 // play audio:
2623 current_module = "play_audio";
2625 int played = write_to_ao(mpctx, ao->buffer.start, playsize, playflags,
2626 written_audio_pts(mpctx));
2627 assert(played % unitsize == 0);
2628 ao->buffer_playable_size = playsize - played;
2630 if (played > 0) {
2631 ao->buffer.len -= played;
2632 memmove(ao->buffer.start, ao->buffer.start + played, ao->buffer.len);
2633 } else if (!mpctx->paused && audio_eof && ao_get_delay(ao) < .04) {
2634 // Sanity check to avoid hanging in case current ao doesn't output
2635 // partial chunks and doesn't check for AOPLAY_FINAL_CHUNK
2636 return -2;
2639 return -partial_fill;
2642 static int sleep_until_near_frame(struct MPContext *mpctx, float *time_frame,
2643 bool sync_to_audio, float *aq_sleep_time)
2645 struct MPOpts *opts = &mpctx->opts;
2646 double audio_limit = 2;
2647 current_module = "calc_sleep_time";
2649 if (mpctx->restart_playback)
2650 return 0;
2652 *time_frame -= get_relative_time(mpctx); // reset timer
2654 if (sync_to_audio) {
2655 float delay = ao_get_delay(mpctx->ao);
2656 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "delay=%f\n", delay);
2658 if (opts->autosync) {
2660 * Adjust this raw delay value by calculating the expected
2661 * delay for this frame and generating a new value which is
2662 * weighted between the two. The higher autosync is, the
2663 * closer to the delay value gets to that which "-nosound"
2664 * would have used, and the longer it will take for A/V
2665 * sync to settle at the right value (but it eventually will.)
2666 * This settling time is very short for values below 100.
2668 float predicted = mpctx->delay / opts->playback_speed + *time_frame;
2669 float difference = delay - predicted;
2670 delay = predicted + difference / (float)opts->autosync;
2673 *time_frame = delay - mpctx->delay / opts->playback_speed;
2675 // delay = amount of audio buffered in soundcard/driver
2676 delay = FFMIN(delay, 0.5);
2677 delay = FFMAX(delay, 0.1);
2678 audio_limit = delay;
2679 } else {
2680 // If we're lagging more than 200 ms behind the right playback rate,
2681 // don't try to "catch up".
2682 // If benchmark is set always output frames as fast as possible
2683 // without sleeping.
2684 if (*time_frame < -0.2 || opts->benchmark)
2685 *time_frame = 0;
2688 double t = *time_frame - mpctx->video_out->flip_queue_offset;
2690 if (t <= 0.05)
2691 return 0;
2693 t -= 0.05;
2694 if (t > audio_limit * 0.6)
2695 t = audio_limit * 0.5;
2696 *aq_sleep_time += t;
2697 mp_input_get_cmd(mpctx->input, t * 1000 + 1, 1);
2698 return 1;
2701 int reinit_video_chain(struct MPContext *mpctx)
2703 struct MPOpts *opts = &mpctx->opts;
2704 sh_video_t * const sh_video = mpctx->sh_video;
2705 if (!sh_video)
2706 return 0;
2707 double ar = -1.0;
2708 //================== Init VIDEO (codec & libvo) ==========================
2709 if (!opts->fixed_vo || !(mpctx->initialized_flags & INITIALIZED_VO)) {
2710 current_module = "preinit_libvo";
2712 //shouldn't we set dvideo->id=-2 when we fail?
2713 //if((mpctx->video_out->preinit(vo_subdevice))!=0){
2714 if (!(mpctx->video_out = init_best_video_out(opts, mpctx->x11_state,
2715 mpctx->key_fifo,
2716 mpctx->input))) {
2717 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "Error opening/initializing "
2718 "the selected video_out (-vo) device.\n");
2719 goto err_out;
2721 mpctx->initialized_flags |= INITIALIZED_VO;
2724 if (stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_ASPECT_RATIO,
2725 &ar) != STREAM_UNSUPPORTED)
2726 mpctx->sh_video->stream_aspect = ar;
2727 current_module = "init_video_filters";
2729 char *vf_arg[] = {
2730 "_oldargs_", (char *)mpctx->video_out, NULL
2732 sh_video->vfilter = vf_open_filter(opts, NULL, "vo", vf_arg);
2734 #ifdef CONFIG_MENU
2735 if (use_menu) {
2736 char *vf_arg[] = {
2737 "_oldargs_", menu_root, NULL
2739 vf_menu = vf_open_plugin(opts, libmenu_vfs, sh_video->vfilter, "menu",
2740 vf_arg);
2741 if (!vf_menu) {
2742 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Can't open libmenu video filter "
2743 "with root menu %s.\n", menu_root);
2744 use_menu = 0;
2747 if (vf_menu)
2748 sh_video->vfilter = vf_menu;
2749 #endif
2751 #ifdef CONFIG_ASS
2752 if (opts->ass_enabled) {
2753 int i;
2754 int insert = 1;
2755 if (opts->vf_settings)
2756 for (i = 0; opts->vf_settings[i].name; ++i)
2757 if (strcmp(opts->vf_settings[i].name, "ass") == 0) {
2758 insert = 0;
2759 break;
2761 if (insert) {
2762 extern vf_info_t vf_info_ass;
2763 const vf_info_t *libass_vfs[] = {
2764 &vf_info_ass, NULL
2766 char *vf_arg[] = {
2767 "auto", "1", NULL
2769 int retcode = 0;
2770 struct vf_instance *vf_ass = vf_open_plugin_noerr(opts, libass_vfs,
2771 sh_video->vfilter,
2772 "ass", vf_arg,
2773 &retcode);
2774 if (vf_ass)
2775 sh_video->vfilter = vf_ass;
2776 else if (retcode == -1) // vf_ass open() returns -1 VO has EOSD
2777 mp_msg(MSGT_CPLAYER, MSGL_V, "[ass] vf_ass not needed\n");
2778 else
2779 mp_msg(MSGT_CPLAYER, MSGL_ERR,
2780 "ASS: cannot add video filter\n");
2783 #endif
2785 sh_video->vfilter = append_filters(sh_video->vfilter, opts->vf_settings);
2787 #ifdef CONFIG_ASS
2788 if (opts->ass_enabled)
2789 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_INIT_EOSD,
2790 mpctx->ass_library);
2791 #endif
2793 current_module = "init_video_codec";
2795 mp_msg(MSGT_CPLAYER, MSGL_INFO, "==========================================================================\n");
2796 init_best_video_codec(sh_video, video_codec_list, video_fm_list);
2797 mp_msg(MSGT_CPLAYER, MSGL_INFO, "==========================================================================\n");
2799 if (!sh_video->initialized) {
2800 if (!opts->fixed_vo)
2801 uninit_player(mpctx, INITIALIZED_VO);
2802 goto err_out;
2805 mpctx->initialized_flags |= INITIALIZED_VCODEC;
2807 if (sh_video->codec)
2808 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
2809 "ID_VIDEO_CODEC=%s\n", sh_video->codec->name);
2811 sh_video->last_pts = MP_NOPTS_VALUE;
2812 sh_video->num_buffered_pts = 0;
2813 sh_video->next_frame_time = 0;
2815 if (opts->auto_quality > 0) {
2816 // Auto quality option enabled
2817 output_quality = get_video_quality_max(sh_video);
2818 if (opts->auto_quality > output_quality)
2819 opts->auto_quality = output_quality;
2820 else
2821 output_quality = opts->auto_quality;
2822 mp_msg(MSGT_CPLAYER, MSGL_V,
2823 "AutoQ: setting quality to %d.\n", output_quality);
2824 set_video_quality(sh_video, output_quality);
2827 // ========== Init display (sh_video->disp_w*sh_video->disp_h/out_fmt) ============
2829 current_module = "init_vo";
2831 return 1;
2833 err_out:
2834 mpctx->sh_video = mpctx->d_video->sh = NULL;
2835 return 0;
2838 static double update_video_nocorrect_pts(struct MPContext *mpctx)
2840 struct sh_video *sh_video = mpctx->sh_video;
2841 double frame_time = 0;
2842 struct vo *video_out = mpctx->video_out;
2843 while (1) {
2844 current_module = "filter_video";
2845 // In nocorrect-pts mode there is no way to properly time these frames
2846 if (vo_get_buffered_frame(video_out, 0) >= 0)
2847 break;
2848 if (vf_output_queued_frame(sh_video->vfilter))
2849 break;
2850 unsigned char *packet = NULL;
2851 frame_time = sh_video->next_frame_time;
2852 if (mpctx->restart_playback)
2853 frame_time = 0;
2854 int in_size = video_read_frame(sh_video, &sh_video->next_frame_time,
2855 &packet, force_fps);
2856 if (in_size < 0) {
2857 #ifdef CONFIG_DVDNAV
2858 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
2859 if (mp_dvdnav_is_eof(mpctx->stream))
2860 return -1;
2861 if (mpctx->d_video)
2862 mpctx->d_video->eof = 0;
2863 if (mpctx->d_audio)
2864 mpctx->d_audio->eof = 0;
2865 mpctx->stream->eof = 0;
2866 } else
2867 #endif
2868 return -1;
2870 if (in_size > max_framesize)
2871 max_framesize = in_size;
2872 sh_video->timer += frame_time;
2873 if (mpctx->sh_audio)
2874 mpctx->delay -= frame_time;
2875 // video_read_frame can change fps (e.g. for ASF video)
2876 vo_fps = sh_video->fps;
2877 int framedrop_type = check_framedrop(mpctx, frame_time);
2878 current_module = "decode video";
2880 void *decoded_frame;
2881 #ifdef CONFIG_DVDNAV
2882 decoded_frame = mp_dvdnav_restore_smpi(mpctx, &in_size, &packet, NULL);
2883 if (in_size >= 0 && !decoded_frame)
2884 #endif
2885 decoded_frame = decode_video(sh_video, NULL, packet, in_size,
2886 framedrop_type, sh_video->pts);
2887 #ifdef CONFIG_DVDNAV
2888 // Save last still frame for future display
2889 mp_dvdnav_save_smpi(mpctx, in_size, packet, decoded_frame);
2890 #endif
2891 if (decoded_frame) {
2892 current_module = "filter video";
2893 filter_video(sh_video, decoded_frame, sh_video->pts);
2895 break;
2897 return frame_time;
2900 static void determine_frame_pts(struct MPContext *mpctx)
2902 struct sh_video *sh_video = mpctx->sh_video;
2903 struct MPOpts *opts = &mpctx->opts;
2905 if (opts->user_pts_assoc_mode)
2906 sh_video->pts_assoc_mode = opts->user_pts_assoc_mode;
2907 else if (sh_video->pts_assoc_mode == 0) {
2908 if (mpctx->d_video->demuxer->timestamp_type == TIMESTAMP_TYPE_PTS
2909 && sh_video->codec_reordered_pts != MP_NOPTS_VALUE)
2910 sh_video->pts_assoc_mode = 1;
2911 else
2912 sh_video->pts_assoc_mode = 2;
2913 } else {
2914 int probcount1 = sh_video->num_reordered_pts_problems;
2915 int probcount2 = sh_video->num_sorted_pts_problems;
2916 if (sh_video->pts_assoc_mode == 2) {
2917 int tmp = probcount1;
2918 probcount1 = probcount2;
2919 probcount2 = tmp;
2921 if (probcount1 >= probcount2 * 1.5 + 2) {
2922 sh_video->pts_assoc_mode = 3 - sh_video->pts_assoc_mode;
2923 mp_msg(MSGT_CPLAYER, MSGL_V, "Switching to pts association mode "
2924 "%d.\n", sh_video->pts_assoc_mode);
2927 sh_video->pts = sh_video->pts_assoc_mode == 1 ?
2928 sh_video->codec_reordered_pts : sh_video->sorted_pts;
2931 static double update_video(struct MPContext *mpctx)
2933 struct sh_video *sh_video = mpctx->sh_video;
2934 struct vo *video_out = mpctx->video_out;
2935 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_SET_OSD_OBJ,
2936 mpctx->osd); // hack for vf_expand
2937 if (!mpctx->opts.correct_pts)
2938 return update_video_nocorrect_pts(mpctx);
2940 double pts;
2942 while (1) {
2943 current_module = "filter_video";
2944 if (!mpctx->hrseek_active
2945 && vo_get_buffered_frame(video_out, false) >= 0)
2946 break;
2947 // XXX Time used in this call is not counted in any performance
2948 // timer now
2949 if (vf_output_queued_frame(sh_video->vfilter))
2950 break;
2951 int in_size = 0;
2952 unsigned char *buf = NULL;
2953 pts = MP_NOPTS_VALUE;
2954 struct demux_packet *pkt = ds_get_packet2(mpctx->d_video);
2955 if (pkt) {
2956 in_size = pkt->len;
2957 buf = pkt->buffer;
2958 pts = pkt->pts;
2960 if (pts != MP_NOPTS_VALUE)
2961 pts += mpctx->video_offset;
2962 if (in_size > max_framesize)
2963 max_framesize = in_size;
2964 current_module = "decode video";
2965 if (pts >= mpctx->hrseek_pts - .005)
2966 mpctx->hrseek_framedrop = false;
2967 int framedrop_type = mpctx->hrseek_framedrop ? 1 :
2968 check_framedrop(mpctx, sh_video->frametime);
2969 void *decoded_frame = decode_video(sh_video, pkt, buf, in_size,
2970 framedrop_type, pts);
2971 if (decoded_frame) {
2972 determine_frame_pts(mpctx);
2973 current_module = "filter video";
2974 filter_video(sh_video, decoded_frame, sh_video->pts);
2975 } else if (!pkt) {
2976 if (vo_get_buffered_frame(video_out, true) < 0)
2977 return -1;
2979 break;
2982 if (!video_out->frame_loaded)
2983 return 0;
2985 pts = video_out->next_pts;
2986 if (pts == MP_NOPTS_VALUE) {
2987 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Video pts after filters MISSING\n");
2988 // Try to use decoder pts from before filters
2989 pts = sh_video->pts;
2990 if (pts == MP_NOPTS_VALUE)
2991 pts = sh_video->last_pts;
2993 if (mpctx->hrseek_active && pts < mpctx->hrseek_pts - .005) {
2994 vo_skip_frame(video_out);
2995 return 0;
2997 mpctx->hrseek_active = false;
2998 sh_video->pts = pts;
2999 if (sh_video->last_pts == MP_NOPTS_VALUE)
3000 sh_video->last_pts = sh_video->pts;
3001 else if (sh_video->last_pts > sh_video->pts) {
3002 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Decreasing video pts: %f < %f\n",
3003 sh_video->pts, sh_video->last_pts);
3004 /* If the difference in pts is small treat it as jitter around the
3005 * right value (possibly caused by incorrect timestamp ordering) and
3006 * just show this frame immediately after the last one.
3007 * Treat bigger differences as timestamp resets and start counting
3008 * timing of later frames from the position of this one. */
3009 if (sh_video->last_pts - sh_video->pts > 0.5)
3010 sh_video->last_pts = sh_video->pts;
3011 else
3012 sh_video->pts = sh_video->last_pts;
3014 double frame_time = sh_video->pts - sh_video->last_pts;
3015 sh_video->last_pts = sh_video->pts;
3016 sh_video->timer += frame_time;
3017 if (mpctx->sh_audio)
3018 mpctx->delay -= frame_time;
3019 return frame_time;
3022 void pause_player(struct MPContext *mpctx)
3024 if (mpctx->paused)
3025 return;
3026 mpctx->paused = 1;
3027 mpctx->step_frames = 0;
3028 mpctx->time_frame -= get_relative_time(mpctx);
3030 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
3031 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
3033 if (mpctx->ao && mpctx->sh_audio)
3034 ao_pause(mpctx->ao); // pause audio, keep data if possible
3037 void unpause_player(struct MPContext *mpctx)
3039 if (!mpctx->paused)
3040 return;
3041 mpctx->paused = 0;
3043 if (mpctx->ao && mpctx->sh_audio)
3044 ao_resume(mpctx->ao);
3045 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok
3046 && !mpctx->step_frames)
3047 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL); // resume video
3048 (void)get_relative_time(mpctx); // ignore time that passed during pause
3051 void add_step_frame(struct MPContext *mpctx)
3053 mpctx->step_frames++;
3054 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
3055 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
3056 unpause_player(mpctx);
3059 static void pause_loop(struct MPContext *mpctx)
3061 struct MPOpts *opts = &mpctx->opts;
3062 mp_cmd_t *cmd;
3063 #ifdef CONFIG_STREAM_CACHE
3064 int old_cache_fill = stream_cache_size > 0 ?
3065 cache_fill_status(mpctx->stream) : 0;
3066 #endif
3067 if (!opts->quiet) {
3068 if (opts->term_osd && !mpctx->sh_video) {
3069 set_osd_tmsg(OSD_MSG_PAUSE, 1, 0, " ===== PAUSE =====");
3070 update_osd_msg(mpctx);
3071 } else
3072 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "\n%s\r",
3073 mp_gtext(" ===== PAUSE ====="));
3074 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_PAUSED\n");
3077 while ((cmd = mp_input_get_cmd(mpctx->input, 20, 1)) == NULL
3078 || cmd->id == MP_CMD_SET_MOUSE_POS || cmd->pausing == 4) {
3079 if (cmd) {
3080 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
3081 run_command(mpctx, cmd);
3082 mp_cmd_free(cmd);
3083 continue;
3085 if (mpctx->sh_video && mpctx->video_out)
3086 vo_check_events(mpctx->video_out);
3087 #ifdef CONFIG_MENU
3088 if (vf_menu)
3089 vf_menu_pause_update(vf_menu);
3090 #endif
3091 usec_sleep(20000);
3092 update_osd_msg(mpctx);
3093 int hack = vo_osd_changed(0);
3094 vo_osd_changed(hack);
3095 if (hack)
3096 break;
3097 #ifdef CONFIG_STREAM_CACHE
3098 if (!opts->quiet && stream_cache_size > 0) {
3099 int new_cache_fill = cache_fill_status(mpctx->stream);
3100 if (new_cache_fill != old_cache_fill) {
3101 if (opts->term_osd && !mpctx->sh_video) {
3102 set_osd_tmsg(OSD_MSG_PAUSE, 1, 0, "%s %d%%",
3103 mp_gtext(" ===== PAUSE ====="),
3104 new_cache_fill);
3105 update_osd_msg(mpctx);
3106 } else
3107 mp_msg(MSGT_CPLAYER, MSGL_STATUS, "%s %d%%\r",
3108 mp_gtext(" ===== PAUSE ====="),
3109 new_cache_fill);
3110 old_cache_fill = new_cache_fill;
3113 #endif
3118 // Find the right mute status and record position for new file position
3119 static void edl_seek_reset(MPContext *mpctx)
3121 mpctx->edl_muted = 0;
3122 next_edl_record = edl_records;
3124 while (next_edl_record) {
3125 if (next_edl_record->start_sec >= get_current_time(mpctx))
3126 break;
3128 if (next_edl_record->action == EDL_MUTE)
3129 mpctx->edl_muted = !mpctx->edl_muted;
3130 next_edl_record = next_edl_record->next;
3132 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
3133 mixer_mute(&mpctx->mixer);
3137 // Execute EDL command for the current position if one exists
3138 static void edl_update(MPContext *mpctx)
3140 if (!next_edl_record)
3141 return;
3143 if (!mpctx->sh_video) {
3144 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
3145 "Cannot use EDL without video, disabling.\n");
3146 free_edl(edl_records);
3147 next_edl_record = NULL;
3148 edl_records = NULL;
3149 return;
3152 if (get_current_time(mpctx) >= next_edl_record->start_sec) {
3153 if (next_edl_record->action == EDL_SKIP) {
3154 mpctx->osd_function = OSD_FFW;
3155 queue_seek(mpctx, MPSEEK_RELATIVE, next_edl_record->length_sec, 0);
3156 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_SKIP: start [%f], stop "
3157 "[%f], length [%f]\n", next_edl_record->start_sec,
3158 next_edl_record->stop_sec, next_edl_record->length_sec);
3159 } else if (next_edl_record->action == EDL_MUTE) {
3160 mpctx->edl_muted = !mpctx->edl_muted;
3161 if ((mpctx->user_muted | mpctx->edl_muted) != mpctx->mixer.muted)
3162 mixer_mute(&mpctx->mixer);
3163 mp_msg(MSGT_CPLAYER, MSGL_DBG4, "EDL_MUTE: [%f]\n",
3164 next_edl_record->start_sec);
3166 next_edl_record = next_edl_record->next;
3170 static void reinit_decoders(struct MPContext *mpctx)
3172 reinit_video_chain(mpctx);
3173 reinit_audio_chain(mpctx);
3174 mp_property_do("sub", M_PROPERTY_SET, &(int){mpctx->global_sub_pos}, mpctx);
3177 static void seek_reset(struct MPContext *mpctx, bool reset_ao)
3179 if (mpctx->sh_video) {
3180 current_module = "seek_video_reset";
3181 resync_video_stream(mpctx->sh_video);
3182 mpctx->sh_video->timer = 0;
3183 vo_seek_reset(mpctx->video_out);
3184 mpctx->sh_video->timer = 0;
3185 mpctx->sh_video->num_buffered_pts = 0;
3186 mpctx->sh_video->last_pts = MP_NOPTS_VALUE;
3187 mpctx->delay = 0;
3188 mpctx->time_frame = 0;
3189 mpctx->restart_playback = true;
3190 // Not all demuxers set d_video->pts during seek, so this value
3191 // (which is used by at least vobsub and edl code below) may
3192 // be completely wrong (probably 0).
3193 mpctx->sh_video->pts = mpctx->d_video->pts + mpctx->video_offset;
3194 mpctx->video_pts = mpctx->sh_video->pts;
3195 update_subtitles(mpctx, mpctx->sh_video->pts, mpctx->video_offset,
3196 true);
3197 update_teletext(mpctx->sh_video, mpctx->demuxer, 1);
3200 if (mpctx->sh_audio) {
3201 current_module = "seek_audio_reset";
3202 resync_audio_stream(mpctx->sh_audio);
3203 if (reset_ao)
3204 ao_reset(mpctx->ao);
3205 mpctx->ao->buffer.len = mpctx->ao->buffer_playable_size;
3206 mpctx->sh_audio->a_buffer_len = 0;
3207 if (!mpctx->sh_video)
3208 update_subtitles(mpctx, mpctx->sh_audio->pts,
3209 mpctx->video_offset, true);
3212 if (vo_vobsub && mpctx->sh_video) {
3213 current_module = "seek_vobsub_reset";
3214 vobsub_seek(vo_vobsub, mpctx->sh_video->pts);
3217 edl_seek_reset(mpctx);
3219 mpctx->hrseek_active = false;
3220 mpctx->hrseek_framedrop = false;
3221 mpctx->total_avsync_change = 0;
3222 audio_time_usage = 0;
3223 video_time_usage = 0;
3224 vout_time_usage = 0;
3225 drop_frame_cnt = 0;
3227 current_module = NULL;
3230 static bool timeline_set_part(struct MPContext *mpctx, int i)
3232 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
3233 struct timeline_part *n = mpctx->timeline + i;
3234 mpctx->timeline_part = i;
3235 mpctx->video_offset = n->start - n->source_start;
3236 if (n->source == p->source)
3237 return false;
3238 enum stop_play_reason orig_stop_play = mpctx->stop_play;
3239 if (!mpctx->sh_video && mpctx->stop_play == KEEP_PLAYING)
3240 mpctx->stop_play = AT_END_OF_FILE; // let audio uninit drain data
3241 uninit_player(mpctx, INITIALIZED_VCODEC | (mpctx->opts.fixed_vo ? 0 : INITIALIZED_VO) | (mpctx->opts.gapless_audio ? 0 : INITIALIZED_AO) | INITIALIZED_ACODEC | INITIALIZED_SUB);
3242 mpctx->stop_play = orig_stop_play;
3243 mpctx->demuxer = n->source->demuxer;
3244 mpctx->d_video = mpctx->demuxer->video;
3245 mpctx->d_audio = mpctx->demuxer->audio;
3246 mpctx->d_sub = mpctx->demuxer->sub;
3247 mpctx->sh_video = mpctx->d_video->sh;
3248 mpctx->sh_audio = mpctx->d_audio->sh;
3249 return true;
3252 // Given pts, switch playback to the corresponding part.
3253 // Return offset within that part.
3254 static double timeline_set_from_time(struct MPContext *mpctx, double pts,
3255 bool *need_reset)
3257 if (pts < 0)
3258 pts = 0;
3259 for (int i = 0; i < mpctx->num_timeline_parts; i++) {
3260 struct timeline_part *p = mpctx->timeline + i;
3261 if (pts < (p + 1)->start) {
3262 *need_reset = timeline_set_part(mpctx, i);
3263 return pts - p->start + p->source_start;
3266 return -1;
3270 // return -1 if seek failed (non-seekable stream?), 0 otherwise
3271 static int seek(MPContext *mpctx, struct seek_params seek,
3272 bool timeline_fallthrough)
3274 struct MPOpts *opts = &mpctx->opts;
3276 current_module = "seek";
3277 if (mpctx->stop_play == AT_END_OF_FILE)
3278 mpctx->stop_play = KEEP_PLAYING;
3279 bool hr_seek = mpctx->demuxer->accurate_seek && opts->correct_pts;
3280 hr_seek &= seek.exact >= 0 && seek.type != MPSEEK_FACTOR;
3281 hr_seek &= opts->hr_seek == 0 && seek.type == MPSEEK_ABSOLUTE
3282 || opts->hr_seek > 0 || seek.exact > 0;
3283 if (seek.type == MPSEEK_FACTOR
3284 || seek.type == MPSEEK_ABSOLUTE
3285 && seek.amount < mpctx->last_chapter_pts
3286 || seek.amount < 0)
3287 mpctx->last_chapter_seek = -2;
3288 if (mpctx->timeline && seek.type == MPSEEK_FACTOR) {
3289 seek.amount *= mpctx->timeline[mpctx->num_timeline_parts].start;
3290 seek.type = MPSEEK_ABSOLUTE;
3292 if ((mpctx->demuxer->accurate_seek || mpctx->timeline)
3293 && seek.type == MPSEEK_RELATIVE) {
3294 seek.type = MPSEEK_ABSOLUTE;
3295 seek.direction = seek.amount > 0 ? 1 : -1;
3296 seek.amount += get_current_time(mpctx);
3299 /* At least the liba52 decoder wants to read from the input stream
3300 * during initialization, so reinit must be done after the demux_seek()
3301 * call that clears possible stream EOF. */
3302 bool need_reset = false;
3303 double demuxer_amount = seek.amount;
3304 if (mpctx->timeline) {
3305 demuxer_amount = timeline_set_from_time(mpctx, seek.amount,
3306 &need_reset);
3307 if (demuxer_amount == -1) {
3308 mpctx->stop_play = AT_END_OF_FILE;
3309 // Clear audio from current position
3310 if (mpctx->sh_audio) {
3311 ao_reset(mpctx->ao);
3312 mpctx->sh_audio->a_buffer_len = 0;
3314 return -1;
3317 int demuxer_style = 0;
3318 switch (seek.type) {
3319 case MPSEEK_FACTOR:
3320 demuxer_style |= SEEK_FACTOR; // fallthrough
3321 case MPSEEK_ABSOLUTE:
3322 demuxer_style |= SEEK_ABSOLUTE;
3324 if (hr_seek || seek.direction < 0)
3325 demuxer_style |= SEEK_BACKWARD;
3326 else if (seek.direction > 0)
3327 demuxer_style |= SEEK_FORWARD;
3329 int seekresult = demux_seek(mpctx->demuxer, demuxer_amount, audio_delay,
3330 demuxer_style);
3331 if (need_reset)
3332 reinit_decoders(mpctx);
3333 if (seekresult == 0)
3334 return -1;
3336 seek_reset(mpctx, !timeline_fallthrough);
3338 /* Use the target time as "current position" for further relative
3339 * seeks etc until a new video frame has been decoded */
3340 if (seek.type == MPSEEK_ABSOLUTE) {
3341 mpctx->video_pts = seek.amount;
3342 mpctx->last_seek_pts = seek.amount;
3343 } else
3344 mpctx->last_seek_pts = MP_NOPTS_VALUE;
3346 if (hr_seek) {
3347 mpctx->hrseek_active = true;
3348 mpctx->hrseek_framedrop = true;
3349 mpctx->hrseek_pts = seek.amount;
3352 mpctx->start_timestamp = GetTimerMS();
3354 return 0;
3357 void queue_seek(struct MPContext *mpctx, enum seek_type type, double amount,
3358 int exact)
3360 struct seek_params *seek = &mpctx->seek;
3361 switch (type) {
3362 case MPSEEK_RELATIVE:
3363 if (seek->type == MPSEEK_FACTOR)
3364 return; // Well... not common enough to bother doing better
3365 seek->amount += amount;
3366 seek->exact = FFMAX(seek->exact, exact);
3367 if (seek->type == MPSEEK_NONE)
3368 seek->exact = exact;
3369 if (seek->type == MPSEEK_ABSOLUTE)
3370 return;
3371 if (seek->amount == 0) {
3372 *seek = (struct seek_params){ 0 };
3373 return;
3375 seek->type = MPSEEK_RELATIVE;
3376 return;
3377 case MPSEEK_ABSOLUTE:
3378 case MPSEEK_FACTOR:
3379 *seek = (struct seek_params) {
3380 .type = type,
3381 .amount = amount,
3382 .exact = exact,
3384 return;
3385 case MPSEEK_NONE:
3386 *seek = (struct seek_params){ 0 };
3387 return;
3389 abort();
3393 double get_time_length(struct MPContext *mpctx)
3395 if (mpctx->timeline)
3396 return mpctx->timeline[mpctx->num_timeline_parts].start;
3398 struct demuxer *demuxer = mpctx->demuxer;
3399 double get_time_ans;
3400 // <= 0 means DEMUXER_CTRL_NOTIMPL or DEMUXER_CTRL_DONTKNOW
3401 if (demux_control(demuxer, DEMUXER_CTRL_GET_TIME_LENGTH,
3402 (void *) &get_time_ans) > 0)
3403 return get_time_ans;
3405 struct sh_video *sh_video = mpctx->d_video->sh;
3406 struct sh_audio *sh_audio = mpctx->d_audio->sh;
3407 if (sh_video && sh_video->i_bps && sh_audio && sh_audio->i_bps)
3408 return (double) (demuxer->movi_end - demuxer->movi_start) /
3409 (sh_video->i_bps + sh_audio->i_bps);
3410 if (sh_video && sh_video->i_bps)
3411 return (double) (demuxer->movi_end - demuxer->movi_start) /
3412 sh_video->i_bps;
3413 if (sh_audio && sh_audio->i_bps)
3414 return (double) (demuxer->movi_end - demuxer->movi_start) /
3415 sh_audio->i_bps;
3416 return 0;
3419 /* If there are timestamps from stream level then use those (for example
3420 * DVDs can have consistent times there while the MPEG-level timestamps
3421 * reset). */
3422 double get_current_time(struct MPContext *mpctx)
3424 struct demuxer *demuxer = mpctx->demuxer;
3425 if (demuxer->stream_pts != MP_NOPTS_VALUE)
3426 return demuxer->stream_pts;
3427 struct sh_video *sh_video = demuxer->video->sh;
3428 if (sh_video)
3429 return mpctx->video_pts;
3430 double apts = playing_audio_pts(mpctx);
3431 if (apts != MP_NOPTS_VALUE)
3432 return apts;
3433 return mpctx->last_seek_pts;
3436 int get_percent_pos(struct MPContext *mpctx)
3438 struct demuxer *demuxer = mpctx->demuxer;
3439 int ans = 0;
3440 if (mpctx->timeline)
3441 ans = get_current_time(mpctx) * 100 /
3442 mpctx->timeline[mpctx->num_timeline_parts].start;
3443 else if (demux_control(demuxer, DEMUXER_CTRL_GET_PERCENT_POS, &ans) > 0)
3445 else {
3446 int len = (demuxer->movi_end - demuxer->movi_start) / 100;
3447 off_t pos = demuxer->filepos > 0 ?
3448 demuxer->filepos : stream_tell(demuxer->stream);
3449 if (len > 0)
3450 ans = (pos - demuxer->movi_start) / len;
3451 else
3452 ans = 0;
3454 if (ans < 0)
3455 ans = 0;
3456 if (ans > 100)
3457 ans = 100;
3458 return ans;
3461 // -2 is no chapters, -1 is before first chapter
3462 int get_current_chapter(struct MPContext *mpctx)
3464 double current_pts = get_current_time(mpctx);
3465 if (!mpctx->chapters)
3466 return FFMAX(mpctx->last_chapter_seek,
3467 demuxer_get_current_chapter(mpctx->demuxer, current_pts));
3469 int i;
3470 for (i = 1; i < mpctx->num_chapters; i++)
3471 if (current_pts < mpctx->chapters[i].start)
3472 break;
3473 return FFMAX(mpctx->last_chapter_seek, i - 1);
3476 // currently returns a string allocated with malloc, not talloc
3477 char *chapter_display_name(struct MPContext *mpctx, int chapter)
3479 if (!mpctx->chapters)
3480 return demuxer_chapter_display_name(mpctx->demuxer, chapter);
3481 return talloc_strdup(NULL, mpctx->chapters[chapter].name);
3484 int seek_chapter(struct MPContext *mpctx, int chapter, double *seek_pts,
3485 char **chapter_name)
3487 mpctx->last_chapter_seek = -2;
3488 if (!mpctx->chapters) {
3489 int res = demuxer_seek_chapter(mpctx->demuxer, chapter, seek_pts,
3490 chapter_name);
3491 if (res >= 0) {
3492 if (*seek_pts == -1)
3493 seek_reset(mpctx, true);
3494 else {
3495 mpctx->last_chapter_seek = res;
3496 mpctx->last_chapter_pts = *seek_pts;
3499 return res;
3502 if (chapter >= mpctx->num_chapters)
3503 return -1;
3504 if (chapter < 0)
3505 chapter = 0;
3506 *seek_pts = mpctx->chapters[chapter].start;
3507 mpctx->last_chapter_seek = chapter;
3508 mpctx->last_chapter_pts = *seek_pts;
3509 if (chapter_name)
3510 *chapter_name = talloc_strdup(NULL, mpctx->chapters[chapter].name);
3511 return chapter;
3515 static void run_playloop(struct MPContext *mpctx)
3517 struct MPOpts *opts = &mpctx->opts;
3518 float aq_sleep_time = 0;
3519 bool full_audio_buffers = false;
3521 if (opts->chapterrange[1] > 0) {
3522 int cur_chapter = get_current_chapter(mpctx);
3523 if (cur_chapter != -1 && cur_chapter + 1 > opts->chapterrange[1])
3524 mpctx->stop_play = PT_NEXT_ENTRY;
3527 if (!mpctx->sh_audio && mpctx->d_audio->sh) {
3528 mpctx->sh_audio = mpctx->d_audio->sh;
3529 mpctx->sh_audio->ds = mpctx->d_audio;
3530 reinit_audio_chain(mpctx);
3533 /*========================== PLAY AUDIO ============================*/
3535 if (!mpctx->sh_video)
3536 mpctx->restart_playback = false;
3538 if (mpctx->sh_audio && !mpctx->restart_playback) {
3539 int status = fill_audio_out_buffers(mpctx);
3540 full_audio_buffers = status >= 0 && !mpctx->ao->untimed;
3541 if (status == -2)
3542 // at eof, all audio at least written to ao
3543 if (!mpctx->sh_video)
3544 mpctx->stop_play = AT_END_OF_FILE;
3548 if (!mpctx->sh_video) {
3549 if (mpctx->step_frames) {
3550 mpctx->step_frames = 0;
3551 pause_player(mpctx);
3553 // handle audio-only case:
3554 double a_pos = 0, a_buf = 0;
3555 // sh_audio can be NULL due to video stream switching
3556 // TODO: handle this better
3557 if (mpctx->sh_audio) {
3558 a_buf = ao_get_delay(mpctx->ao);
3559 a_pos = written_audio_pts(mpctx) - mpctx->opts.playback_speed *
3560 a_buf;
3563 print_status(mpctx, a_pos, false);
3565 update_subtitles(mpctx, a_pos, mpctx->video_offset, false);
3566 update_osd_msg(mpctx);
3567 if (end_at.type == END_AT_TIME && end_at.pos < a_pos)
3568 mpctx->stop_play = AT_END_OF_FILE;
3569 else if (mpctx->timeline && mpctx->stop_play == AT_END_OF_FILE
3570 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts
3571 && mpctx->sh_audio) {
3572 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
3573 if (!opts->gapless_audio && p->source != (p + 1)->source
3574 && a_buf > 0.05) {
3575 mpctx->stop_play = KEEP_PLAYING;
3576 mp_input_get_cmd(mpctx->input, (a_buf - .05) * 1000, true);
3577 } else {
3578 seek(mpctx, (struct seek_params){ .type = MPSEEK_ABSOLUTE,
3579 .amount = (p + 1)->start },
3580 true);
3582 } else if (!mpctx->stop_play) {
3583 int sleep_time = 100;
3584 if (mpctx->sh_audio) {
3585 if (mpctx->ao->untimed)
3586 sleep_time = 0;
3587 else if (full_audio_buffers)
3588 sleep_time = FFMAX(20, a_buf * 1000 - 50);
3589 else
3590 sleep_time = 20;
3591 sleep_time = FFMIN(sleep_time, 100);
3593 mp_input_get_cmd(mpctx->input, sleep_time, true);
3595 } else {
3597 /*========================== PLAY VIDEO ============================*/
3599 vo_pts = mpctx->sh_video->timer * 90000.0;
3600 vo_fps = mpctx->sh_video->fps;
3602 bool blit_frame = mpctx->video_out->frame_loaded;
3603 if (!blit_frame || mpctx->hrseek_active) {
3604 double frame_time = update_video(mpctx);
3605 blit_frame = mpctx->video_out->frame_loaded;
3606 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "*** ftime=%5.3f ***\n", frame_time);
3607 if (mpctx->sh_video->vf_initialized < 0) {
3608 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
3609 "\nFATAL: Could not initialize video filters (-vf) "
3610 "or video output (-vo).\n");
3611 mpctx->stop_play = PT_NEXT_ENTRY;
3612 return;
3614 if (frame_time < 0)
3615 mpctx->stop_play = AT_END_OF_FILE;
3616 else if (!mpctx->restart_playback) {
3617 mpctx->time_frame += frame_time / opts->playback_speed;
3618 adjust_sync(mpctx, frame_time);
3621 if (mpctx->timeline) {
3622 struct timeline_part *next =
3623 mpctx->timeline + mpctx->timeline_part + 1;
3624 if (mpctx->sh_video->pts >= next->start
3625 || mpctx->stop_play == AT_END_OF_FILE
3626 && mpctx->timeline_part + 1 < mpctx->num_timeline_parts) {
3627 seek(mpctx, (struct seek_params){ .type = MPSEEK_ABSOLUTE,
3628 .amount = next->start },
3629 true);
3630 return;
3634 // ================================================================
3636 current_module = "vo_check_events";
3637 vo_check_events(mpctx->video_out);
3639 #ifdef CONFIG_X11
3640 if (stop_xscreensaver) {
3641 current_module = "stop_xscreensaver";
3642 xscreensaver_heartbeat(mpctx->x11_state);
3644 #endif
3645 if (heartbeat_cmd) {
3646 static unsigned last_heartbeat;
3647 unsigned now = GetTimerMS();
3648 if (now - last_heartbeat > 30000) {
3649 last_heartbeat = now;
3650 system(heartbeat_cmd);
3654 bool frame_time_remaining = sleep_until_near_frame(mpctx,
3655 &mpctx->time_frame,
3656 full_audio_buffers,
3657 &aq_sleep_time);
3659 //=================== FLIP PAGE (VIDEO BLT): ======================
3661 current_module = "flip_page";
3662 if (!frame_time_remaining && blit_frame) {
3663 struct sh_video *sh_video = mpctx->sh_video;
3664 mpctx->video_pts = sh_video->pts;
3665 update_subtitles(mpctx, sh_video->pts, mpctx->video_offset, false);
3666 update_teletext(sh_video, mpctx->demuxer, 0);
3667 update_osd_msg(mpctx);
3668 struct vf_instance *vf = sh_video->vfilter;
3669 vf->control(vf, VFCTRL_DRAW_EOSD, mpctx->osd);
3670 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
3671 vo_osd_changed(0);
3673 mpctx->time_frame -= mpctx->video_out->flip_queue_offset;
3674 aq_sleep_time += mpctx->time_frame;
3675 // flag 256 means: libvo driver does its timing (dvb card)
3676 if (mpctx->time_frame > 0.001
3677 && !(mpctx->sh_video->output_flags & VFCAP_TIMER))
3678 mpctx->time_frame = timing_sleep(mpctx, mpctx->time_frame);
3679 mpctx->time_frame += mpctx->video_out->flip_queue_offset;
3681 unsigned int t2 = GetTimer();
3682 /* Playing with playback speed it's possible to get pathological
3683 * cases with mpctx->time_frame negative enough to cause an
3684 * overflow in pts_us calculation, thus the FFMAX. */
3685 double time_frame = FFMAX(mpctx->time_frame, -1);
3686 unsigned int pts_us = mpctx->last_time + time_frame * 1e6;
3687 int duration = -1;
3688 double pts2 = mpctx->video_out->next_pts2;
3689 if (pts2 != MP_NOPTS_VALUE && opts->correct_pts
3690 && !mpctx->restart_playback) {
3691 // expected A/V sync correction is ignored
3692 double diff = (pts2 - mpctx->video_pts);
3693 diff /= opts->playback_speed;
3694 if (mpctx->time_frame < 0)
3695 diff += mpctx->time_frame;
3696 if (diff < 0)
3697 diff = 0;
3698 if (diff > 10)
3699 diff = 10;
3700 duration = diff * 1e6;
3702 vo_flip_page(mpctx->video_out, pts_us | 1, duration);
3704 mpctx->last_vo_flip_duration = (GetTimer() - t2) * 0.000001;
3705 vout_time_usage += mpctx->last_vo_flip_duration;
3706 if (mpctx->video_out->driver->flip_page_timed) {
3707 // No need to adjust sync based on flip speed
3708 mpctx->last_vo_flip_duration = 0;
3709 // For print_status - VO call finishing early is OK for sync
3710 mpctx->time_frame -= get_relative_time(mpctx);
3712 if (mpctx->restart_playback) {
3713 mpctx->syncing_audio = true;
3714 if (mpctx->sh_audio)
3715 fill_audio_out_buffers(mpctx);
3716 mpctx->restart_playback = false;
3717 mpctx->time_frame = 0;
3718 get_relative_time(mpctx);
3720 print_status(mpctx, MP_NOPTS_VALUE, true);
3721 } else
3722 print_status(mpctx, MP_NOPTS_VALUE, false);
3724 if (opts->auto_quality > 0) {
3725 current_module = "autoq";
3726 if (output_quality < opts->auto_quality && aq_sleep_time > 0)
3727 ++output_quality;
3728 else if (output_quality > 1 && aq_sleep_time < 0)
3729 --output_quality;
3730 else if (output_quality > 0 && aq_sleep_time < -0.050f) // 50ms
3731 output_quality = 0;
3732 set_video_quality(mpctx->sh_video, output_quality);
3735 if (!frame_time_remaining && blit_frame) {
3736 if (play_n_frames >= 0) {
3737 --play_n_frames;
3738 if (play_n_frames <= 0)
3739 mpctx->stop_play = PT_NEXT_ENTRY;
3741 if (mpctx->step_frames > 0) {
3742 mpctx->step_frames--;
3743 if (mpctx->step_frames == 0)
3744 pause_player(mpctx);
3748 // FIXME: add size based support for -endpos
3749 if (end_at.type == END_AT_TIME &&
3750 !frame_time_remaining && end_at.pos <= mpctx->sh_video->pts)
3751 mpctx->stop_play = PT_NEXT_ENTRY;
3753 } // end if(mpctx->sh_video)
3755 #ifdef CONFIG_DVDNAV
3756 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
3757 nav_highlight_t hl;
3758 mp_dvdnav_get_highlight(mpctx->stream, &hl);
3759 if (!vo_spudec || !spudec_apply_palette_crop(vo_spudec, hl.palette, hl.sx, hl.sy, hl.ex, hl.ey)) {
3760 osd_set_nav_box(hl.sx, hl.sy, hl.ex, hl.ey);
3761 vo_osd_changed(OSDTYPE_DVDNAV);
3762 } else {
3763 osd_set_nav_box(0, 0, 0, 0);
3764 vo_osd_changed(OSDTYPE_DVDNAV);
3765 vo_osd_changed(OSDTYPE_SPU);
3768 if (mp_dvdnav_stream_has_changed(mpctx->stream)) {
3769 double ar = -1.0;
3770 if (mpctx->sh_video &&
3771 stream_control(mpctx->demuxer->stream,
3772 STREAM_CTRL_GET_ASPECT_RATIO, &ar)
3773 != STREAM_UNSUPPORTED)
3774 mpctx->sh_video->stream_aspect = ar;
3777 #endif
3779 //================= Keyboard events, SEEKing ====================
3781 current_module = "key_events";
3783 while (1) {
3784 mp_cmd_t *cmd;
3785 while ((cmd = mp_input_get_cmd(mpctx->input, 0, 1)) != NULL) {
3786 /* Allow running consecutive seek commands to combine them,
3787 * but execute the seek before running other commands.
3788 * If the user seeks continuously (keeps arrow key down)
3789 * try to finish showing a frame from one location before doing
3790 * another seek (which could lead to unchanging display). */
3791 if (mpctx->seek.type && cmd->id != MP_CMD_SEEK
3792 || mpctx->restart_playback && cmd->id == MP_CMD_SEEK
3793 && GetTimerMS() - mpctx->start_timestamp < 300)
3794 break;
3795 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
3796 run_command(mpctx, cmd);
3797 mp_cmd_free(cmd);
3798 if (mpctx->stop_play)
3799 break;
3801 if (!mpctx->paused || mpctx->stop_play || mpctx->seek.type
3802 || mpctx->restart_playback)
3803 break;
3804 if (mpctx->sh_video) {
3805 update_osd_msg(mpctx);
3806 int hack = vo_osd_changed(0);
3807 vo_osd_changed(hack);
3808 if (hack) {
3809 if (redraw_osd(mpctx->sh_video, mpctx->osd) < 0) {
3810 add_step_frame(mpctx);
3811 break;
3812 } else
3813 vo_osd_changed(0);
3816 pause_loop(mpctx);
3819 // handle -sstep
3820 if (step_sec > 0 && !mpctx->paused && !mpctx->restart_playback) {
3821 mpctx->osd_function = OSD_FFW;
3822 queue_seek(mpctx, MPSEEK_RELATIVE, step_sec, 0);
3825 edl_update(mpctx);
3827 /* Looping. */
3828 if (opts->loop_times >= 0 && (mpctx->stop_play == AT_END_OF_FILE ||
3829 mpctx->stop_play == PT_NEXT_ENTRY)) {
3830 mp_msg(MSGT_CPLAYER, MSGL_V, "loop_times = %d\n", opts->loop_times);
3832 if (opts->loop_times > 1)
3833 opts->loop_times--;
3834 else if (opts->loop_times == 1)
3835 opts->loop_times = -1;
3836 play_n_frames = play_n_frames_mf;
3837 mpctx->stop_play = 0;
3838 queue_seek(mpctx, MPSEEK_ABSOLUTE, opts->seek_to_sec, 0);
3841 if (mpctx->seek.type) {
3842 seek(mpctx, mpctx->seek, false);
3843 mpctx->seek = (struct seek_params){ 0 };
3848 static int read_keys(void *ctx, int fd)
3850 getch2(ctx);
3851 return MP_INPUT_NOTHING;
3854 static bool attachment_is_font(struct demux_attachment *att)
3856 if (!att->name || !att->type || !att->data || !att->data_size)
3857 return false;
3858 // match against MIME types
3859 if (strcmp(att->type, "application/x-truetype-font") == 0
3860 || strcmp(att->type, "application/x-font") == 0)
3861 return true;
3862 // fallback: match against file extension
3863 if (strlen(att->name) > 4) {
3864 char *ext = att->name + strlen(att->name) - 4;
3865 if (strcasecmp(ext, ".ttf") == 0 || strcasecmp(ext, ".ttc") == 0
3866 || strcasecmp(ext, ".otf") == 0)
3867 return true;
3869 return false;
3872 static int select_audio(demuxer_t *demuxer, int audio_id, char **audio_lang)
3874 if (audio_id == -1)
3875 audio_id = demuxer_audio_track_by_lang_and_default(demuxer, audio_lang);
3876 if (audio_id != -1) // -1 (automatic) is the default behaviour of demuxers
3877 demuxer_switch_audio(demuxer, audio_id);
3878 if (audio_id == -2) { // some demuxers don't yet know how to switch to no sound
3879 demuxer->audio->id = -2;
3880 demuxer->audio->sh = NULL;
3882 return demuxer->audio->id;
3885 static void print_version(const char *name)
3887 mp_msg(MSGT_CPLAYER, MSGL_INFO, MP_TITLE, name);
3889 /* Test for CPU capabilities (and corresponding OS support) for optimizing */
3890 GetCpuCaps(&gCpuCaps);
3891 #if ARCH_X86
3892 mp_msg(MSGT_CPLAYER, MSGL_V,
3893 "CPUflags: MMX: %d MMX2: %d 3DNow: %d 3DNowExt: %d SSE: %d SSE2: %d SSSE3: %d\n",
3894 gCpuCaps.hasMMX, gCpuCaps.hasMMX2,
3895 gCpuCaps.has3DNow, gCpuCaps.has3DNowExt,
3896 gCpuCaps.hasSSE, gCpuCaps.hasSSE2, gCpuCaps.hasSSSE3);
3897 #if CONFIG_RUNTIME_CPUDETECT
3898 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Compiled with runtime CPU detection.\n");
3899 #else
3900 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Compiled for x86 CPU with extensions:");
3901 if (HAVE_MMX)
3902 mp_msg(MSGT_CPLAYER, MSGL_V, " MMX");
3903 if (HAVE_MMX2)
3904 mp_msg(MSGT_CPLAYER, MSGL_V, " MMX2");
3905 if (HAVE_AMD3DNOW)
3906 mp_msg(MSGT_CPLAYER, MSGL_V, " 3DNow");
3907 if (HAVE_AMD3DNOWEXT)
3908 mp_msg(MSGT_CPLAYER, MSGL_V, " 3DNowExt");
3909 if (HAVE_SSE)
3910 mp_msg(MSGT_CPLAYER, MSGL_V, " SSE");
3911 if (HAVE_SSE2)
3912 mp_msg(MSGT_CPLAYER, MSGL_V, " SSE2");
3913 if (HAVE_SSSE3)
3914 mp_msg(MSGT_CPLAYER, MSGL_V, " SSSE3");
3915 if (HAVE_CMOV)
3916 mp_msg(MSGT_CPLAYER, MSGL_V, " CMOV");
3917 mp_msg(MSGT_CPLAYER, MSGL_V, "\n");
3918 #endif /* CONFIG_RUNTIME_CPUDETECT */
3919 #endif /* ARCH_X86 */
3920 print_libav_versions();
3923 #ifdef PTW32_STATIC_LIB
3924 static void detach_ptw32(void)
3926 pthread_win32_thread_detach_np();
3927 pthread_win32_process_detach_np();
3929 #endif
3931 /* This preprocessor directive is a hack to generate a mplayer-nomain.o object
3932 * file for some tools to link against. */
3933 #ifndef DISABLE_MAIN
3934 int main(int argc, char *argv[])
3936 #ifdef PTW32_STATIC_LIB
3937 pthread_win32_process_attach_np();
3938 pthread_win32_thread_attach_np();
3939 atexit(detach_ptw32);
3940 #endif
3941 if (argc > 1 && (!strcmp(argv[1], "-leak-report")
3942 || !strcmp(argv[1], "--leak-report")))
3943 talloc_enable_leak_report();
3945 char *mem_ptr;
3947 // movie info:
3949 /* Flag indicating whether MPlayer should exit without playing anything. */
3950 int opt_exit = 0;
3951 int i;
3953 struct MPContext *mpctx = &(struct MPContext){
3954 .osd_function = OSD_PLAY,
3955 .begin_skip = MP_NOPTS_VALUE,
3956 .play_tree_step = 1,
3957 .global_sub_pos = -1,
3958 .set_of_sub_pos = -1,
3959 .file_format = DEMUXER_TYPE_UNKNOWN,
3960 .last_dvb_step = 1,
3963 InitTimer();
3964 srand(GetTimerMS());
3966 mp_msg_init();
3967 init_libav();
3969 #ifdef CONFIG_X11
3970 mpctx->x11_state = vo_x11_init_state();
3971 #endif
3972 struct MPOpts *opts = &mpctx->opts;
3973 set_default_mplayer_options(opts);
3974 // Create the config context and register the options
3975 mpctx->mconfig = m_config_new(opts, cfg_include);
3976 m_config_register_options(mpctx->mconfig, mplayer_opts);
3977 m_config_register_options(mpctx->mconfig, common_opts);
3978 mp_input_register_options(mpctx->mconfig);
3980 // Preparse the command line
3981 m_config_preparse_command_line(mpctx->mconfig, argc, argv);
3983 #if (defined(__MINGW32__) || defined(__CYGWIN__)) && defined(CONFIG_WIN32DLL)
3984 set_path_env();
3985 #endif
3987 #ifdef CONFIG_TV
3988 stream_tv_defaults.immediate = 1;
3989 #endif
3991 parse_cfgfiles(mpctx, mpctx->mconfig);
3993 mpctx->playtree = m_config_parse_mp_command_line(mpctx->mconfig, argc, argv);
3994 if (mpctx->playtree == NULL)
3995 opt_exit = 1;
3996 else {
3997 mpctx->playtree = play_tree_cleanup(mpctx->playtree);
3998 if (mpctx->playtree) {
3999 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,
4000 mpctx->mconfig);
4001 if (mpctx->playtree_iter) {
4002 if (play_tree_iter_step(mpctx->playtree_iter, 0, 0) !=
4003 PLAY_TREE_ITER_ENTRY) {
4004 play_tree_iter_free(mpctx->playtree_iter);
4005 mpctx->playtree_iter = NULL;
4007 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,
4013 print_version("MPlayer2");
4015 #if defined(__MINGW32__) || defined(__CYGWIN__)
4017 HMODULE kernel32 = GetModuleHandle("Kernel32.dll");
4018 BOOL WINAPI (*setDEP)(DWORD) = NULL;
4019 BOOL WINAPI (*setDllDir)(LPCTSTR) = NULL;
4020 if (kernel32) {
4021 setDEP = GetProcAddress(kernel32, "SetProcessDEPPolicy");
4022 setDllDir = GetProcAddress(kernel32, "SetDllDirectoryA");
4024 if (setDEP)
4025 setDEP(3);
4026 if (setDllDir)
4027 setDllDir("");
4029 // stop Windows from showing all kinds of annoying error dialogs
4030 SetErrorMode(0x8003);
4031 // request 1ms timer resolution
4032 timeBeginPeriod(1);
4033 #endif
4035 #ifdef CONFIG_PRIORITY
4036 set_priority();
4037 #endif
4039 if (opts->video_driver_list &&
4040 strcmp(opts->video_driver_list[0], "help") == 0) {
4041 list_video_out();
4042 opt_exit = 1;
4045 if (opts->audio_driver_list &&
4046 strcmp(opts->audio_driver_list[0], "help") == 0) {
4047 list_audio_out();
4048 opt_exit = 1;
4051 /* Check codecs.conf. */
4052 if (!codecs_file || !parse_codec_cfg(codecs_file)) {
4053 if (!parse_codec_cfg(mem_ptr = get_path("codecs.conf"))) {
4054 if (!parse_codec_cfg(MPLAYER_CONFDIR "/codecs.conf")) {
4055 if (!parse_codec_cfg(NULL))
4056 exit_player_with_rc(mpctx, EXIT_NONE, 0);
4057 mp_tmsg(MSGT_CPLAYER, MSGL_V,
4058 "Using built-in default codecs.conf.\n");
4061 free(mem_ptr); // release the buffer created by get_path()
4064 if (audio_codec_list && strcmp(audio_codec_list[0], "help") == 0) {
4065 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available audio codecs:\n");
4066 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AUDIO_CODECS\n");
4067 list_codecs(1);
4068 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4069 opt_exit = 1;
4071 if (video_codec_list && strcmp(video_codec_list[0], "help") == 0) {
4072 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available video codecs:\n");
4073 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODECS\n");
4074 list_codecs(0);
4075 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4076 opt_exit = 1;
4078 if (video_fm_list && strcmp(video_fm_list[0], "help") == 0) {
4079 vfm_help();
4080 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4081 opt_exit = 1;
4083 if (audio_fm_list && strcmp(audio_fm_list[0], "help") == 0) {
4084 afm_help();
4085 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4086 opt_exit = 1;
4088 if (af_cfg.list && strcmp(af_cfg.list[0], "help") == 0) {
4089 af_help();
4090 printf("\n");
4091 opt_exit = 1;
4093 #ifdef CONFIG_X11
4094 if (vo_fstype_list && strcmp(vo_fstype_list[0], "help") == 0) {
4095 fstype_help();
4096 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4097 opt_exit = 1;
4099 #endif
4100 if ((opts->demuxer_name && strcmp(opts->demuxer_name, "help") == 0) ||
4101 (opts->audio_demuxer_name && strcmp(opts->audio_demuxer_name, "help") == 0) ||
4102 (opts->sub_demuxer_name && strcmp(opts->sub_demuxer_name, "help") == 0)) {
4103 demuxer_help();
4104 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
4105 opt_exit = 1;
4107 if (opts->list_properties) {
4108 property_print_help();
4109 opt_exit = 1;
4112 if (opt_exit)
4113 exit_player(mpctx, EXIT_NONE);
4115 if (!mpctx->filename && !opts->player_idle_mode) {
4116 // no file/vcd/dvd -> show HELP:
4117 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", mp_gtext(help_text));
4118 exit_player_with_rc(mpctx, EXIT_NONE, 0);
4121 /* Display what configure line was used */
4122 mp_msg(MSGT_CPLAYER, MSGL_V, "Configuration: " CONFIGURATION "\n");
4124 // Many users forget to include command line in bugreports...
4125 if (mp_msg_test(MSGT_CPLAYER, MSGL_V)) {
4126 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "CommandLine:");
4127 for (i = 1; i < argc; i++)
4128 mp_msg(MSGT_CPLAYER, MSGL_INFO, " '%s'", argv[i]);
4129 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
4132 //------ load global data first ------
4134 mpctx->osd = osd_create();
4136 // check font
4137 #ifdef CONFIG_FREETYPE
4138 init_freetype();
4139 #endif
4140 #ifdef CONFIG_FONTCONFIG
4141 if (font_fontconfig <= 0) {
4142 #endif
4143 #ifdef CONFIG_BITMAP_FONT
4144 if (font_name) {
4145 vo_font = read_font_desc(font_name, font_factor, verbose > 1);
4146 if (!vo_font)
4147 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot load bitmap font: %s\n",
4148 filename_recode(font_name));
4149 } else {
4150 // try default:
4151 vo_font = read_font_desc(mem_ptr = get_path("font/font.desc"),
4152 font_factor, verbose > 1);
4153 free(mem_ptr); // release the buffer created by get_path()
4154 if (!vo_font)
4155 vo_font = read_font_desc(MPLAYER_DATADIR "/font/font.desc",
4156 font_factor, verbose > 1);
4158 if (sub_font_name)
4159 mpctx->osd->sub_font = read_font_desc(sub_font_name, font_factor,
4160 verbose > 1);
4161 else
4162 mpctx->osd->sub_font = vo_font;
4163 #endif
4164 #ifdef CONFIG_FONTCONFIG
4166 #endif
4168 #ifdef CONFIG_ASS
4169 mpctx->ass_library = mp_ass_init(opts);
4170 mpctx->osd->ass_library = mpctx->ass_library;
4171 #endif
4173 #ifdef HAVE_RTC
4174 if (opts->rtc) {
4175 char *rtc_device = opts->rtc_device;
4176 // seteuid(0); /* Can't hurt to try to get root here */
4177 if ((rtc_fd = open(rtc_device ? rtc_device : "/dev/rtc", O_RDONLY)) < 0)
4178 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Failed to open %s: %s "
4179 "(it should be readable by the user.)\n",
4180 rtc_device ? rtc_device : "/dev/rtc", strerror(errno));
4181 else {
4182 unsigned long irqp = 1024; /* 512 seemed OK. 128 is jerky. */
4184 if (ioctl(rtc_fd, RTC_IRQP_SET, irqp) < 0) {
4185 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Linux RTC init error in "
4186 "ioctl (rtc_irqp_set %lu): %s\n",
4187 irqp, strerror(errno));
4188 mp_tmsg(MSGT_CPLAYER, MSGL_HINT, "Try adding \"echo %lu > /proc/sys/dev/rtc/max-user-freq\" to your system startup scripts.\n", irqp);
4189 close(rtc_fd);
4190 rtc_fd = -1;
4191 } else if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
4192 /* variable only by the root */
4193 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC init error in "
4194 "ioctl (rtc_pie_on): %s\n", strerror(errno));
4195 close(rtc_fd);
4196 rtc_fd = -1;
4197 } else
4198 mp_tmsg(MSGT_CPLAYER, MSGL_V,
4199 "Using Linux hardware RTC timing (%ldHz).\n", irqp);
4202 if (rtc_fd < 0)
4203 #endif /* HAVE_RTC */
4204 mp_msg(MSGT_CPLAYER, MSGL_V, "Using %s timing\n",
4205 opts->softsleep ? "software" : timer_name);
4207 #ifdef HAVE_TERMCAP
4208 load_termcap(NULL); // load key-codes
4209 #endif
4211 // ========== Init keyboard FIFO (connection to libvo) ============
4213 // Init input system
4214 current_module = "init_input";
4215 mpctx->input = mp_input_init(&opts->input);
4216 mpctx->key_fifo = mp_fifo_create(mpctx->input, opts);
4217 if (slave_mode)
4218 mp_input_add_cmd_fd(mpctx->input, 0, USE_FD0_CMD_SELECT, MP_INPUT_SLAVE_CMD_FUNC, NULL);
4219 else if (opts->consolecontrols)
4220 mp_input_add_key_fd(mpctx->input, 0, 1, read_keys, NULL, mpctx->key_fifo);
4221 // Set the libstream interrupt callback
4222 stream_set_interrupt_callback(mp_input_check_interrupt, mpctx->input);
4224 #ifdef CONFIG_MENU
4225 if (use_menu) {
4226 if (menu_cfg && menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
4227 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
4228 else {
4229 menu_cfg = get_path("menu.conf");
4230 if (menu_init(mpctx, mpctx->mconfig, mpctx->input, menu_cfg))
4231 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", menu_cfg);
4232 else {
4233 if (menu_init(mpctx, mpctx->mconfig, mpctx->input,
4234 MPLAYER_CONFDIR "/menu.conf"))
4235 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Menu initialized: %s\n", MPLAYER_CONFDIR "/menu.conf");
4236 else {
4237 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Menu init failed.\n");
4238 use_menu = 0;
4243 #endif
4245 current_module = NULL;
4247 /// Catch signals
4248 #ifndef __MINGW32__
4249 signal(SIGCHLD, child_sighandler);
4250 #endif
4252 #ifdef CONFIG_CRASH_DEBUG
4253 prog_path = argv[0];
4254 #endif
4255 //========= Catch terminate signals: ================
4256 // terminate requests:
4257 signal(SIGTERM, exit_sighandler); // kill
4258 signal(SIGHUP, exit_sighandler); // kill -HUP / xterm closed
4260 signal(SIGINT, exit_sighandler); // Interrupt from keyboard
4262 signal(SIGQUIT, exit_sighandler); // Quit from keyboard
4263 signal(SIGPIPE, exit_sighandler); // Some window managers cause this
4264 #ifdef CONFIG_SIGHANDLER
4265 // fatal errors:
4266 signal(SIGBUS, exit_sighandler); // bus error
4267 signal(SIGSEGV, exit_sighandler); // segfault
4268 signal(SIGILL, exit_sighandler); // illegal instruction
4269 signal(SIGFPE, exit_sighandler); // floating point exc.
4270 signal(SIGABRT, exit_sighandler); // abort()
4271 #ifdef CONFIG_CRASH_DEBUG
4272 if (crash_debug)
4273 signal(SIGTRAP, exit_sighandler);
4274 #endif
4275 #endif
4277 // ***************** Now, let's see the per-file stuff ******************
4279 play_next_file:
4281 // init global sub numbers
4282 mpctx->global_sub_size = 0;
4283 memset(mpctx->sub_counts, 0, sizeof(mpctx->sub_counts));
4285 if (mpctx->filename) {
4286 load_per_protocol_config(mpctx->mconfig, mpctx->filename);
4287 load_per_extension_config(mpctx->mconfig, mpctx->filename);
4288 load_per_file_config(mpctx->mconfig, mpctx->filename);
4291 if (opts->video_driver_list)
4292 load_per_output_config(mpctx->mconfig, PROFILE_CFG_VO,
4293 opts->video_driver_list[0]);
4294 if (opts->audio_driver_list)
4295 load_per_output_config(mpctx->mconfig, PROFILE_CFG_AO,
4296 opts->audio_driver_list[0]);
4298 // We must enable getch2 here to be able to interrupt network connection
4299 // or cache filling
4300 if (opts->consolecontrols && !slave_mode) {
4301 if (mpctx->initialized_flags & INITIALIZED_GETCH2)
4302 mp_tmsg(MSGT_CPLAYER, MSGL_WARN,
4303 "WARNING: getch2_init called twice!\n");
4304 else
4305 getch2_enable(); // prepare stdin for hotkeys...
4306 mpctx->initialized_flags |= INITIALIZED_GETCH2;
4307 mp_msg(MSGT_CPLAYER, MSGL_DBG2, "\n[[[init getch2]]]\n");
4310 // ================= GUI idle loop (STOP state) =========================
4311 while (opts->player_idle_mode && !mpctx->filename) {
4312 play_tree_t *entry = NULL;
4313 mp_cmd_t *cmd;
4314 if (mpctx->video_out && mpctx->video_out->config_ok)
4315 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
4316 while (!(cmd = mp_input_get_cmd(mpctx->input, 0, 0))) {
4317 if (mpctx->video_out)
4318 vo_check_events(mpctx->video_out);
4319 usec_sleep(20000);
4321 switch (cmd->id) {
4322 case MP_CMD_LOADFILE:
4323 // prepare a tree entry with the new filename
4324 entry = play_tree_new();
4325 play_tree_add_file(entry, cmd->args[0].v.s);
4326 // The entry is added to the main playtree after the switch().
4327 break;
4328 case MP_CMD_LOADLIST:
4329 entry = parse_playlist_file(mpctx->mconfig, bstr(cmd->args[0].v.s));
4330 break;
4331 case MP_CMD_QUIT:
4332 exit_player_with_rc(mpctx, EXIT_QUIT,
4333 (cmd->nargs > 0) ? cmd->args[0].v.i : 0);
4334 break;
4335 case MP_CMD_VO_FULLSCREEN:
4336 case MP_CMD_GET_PROPERTY:
4337 case MP_CMD_SET_PROPERTY:
4338 case MP_CMD_STEP_PROPERTY:
4339 run_command(mpctx, cmd);
4340 break;
4343 mp_cmd_free(cmd);
4345 if (entry) { // user entered a command that gave a valid entry
4346 if (mpctx->playtree)
4347 // the playtree is always a node with one child. let's clear it
4348 play_tree_free_list(mpctx->playtree->child, 1);
4349 else
4350 // .. or make a brand new playtree
4351 mpctx->playtree = play_tree_new();
4353 if (!mpctx->playtree)
4354 continue; // couldn't make playtree! wait for next command
4356 play_tree_set_child(mpctx->playtree, entry);
4358 /* Make iterator start at the top the of tree. */
4359 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,
4360 mpctx->mconfig);
4361 if (!mpctx->playtree_iter)
4362 continue;
4364 // find the first real item in the tree
4365 if (play_tree_iter_step(mpctx->playtree_iter, 0, 0) !=
4366 PLAY_TREE_ITER_ENTRY) {
4367 // no items!
4368 play_tree_iter_free(mpctx->playtree_iter);
4369 mpctx->playtree_iter = NULL;
4370 continue; // wait for next command
4372 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, 1);
4376 #ifdef CONFIG_ASS
4377 ass_set_style_overrides(mpctx->ass_library, opts->ass_force_style_list);
4378 #endif
4379 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
4380 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL);
4382 if (mpctx->filename) {
4383 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nPlaying %s.\n",
4384 filename_recode(mpctx->filename));
4385 if (use_filename_title && opts->vo_wintitle == NULL)
4386 opts->vo_wintitle = talloc_strdup(NULL,
4387 mp_basename(mpctx->filename));
4390 if (edl_filename) {
4391 if (edl_records)
4392 free_edl(edl_records);
4393 next_edl_record = edl_records = edl_parse_file();
4395 if (edl_output_filename) {
4396 if (edl_fd)
4397 fclose(edl_fd);
4398 if ((edl_fd = fopen(edl_output_filename, "w")) == NULL) {
4399 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
4400 "Can't open EDL file [%s] for writing.\n",
4401 filename_recode(edl_output_filename));
4405 //==================== Open VOB-Sub ============================
4407 current_module = "vobsub";
4408 if (opts->vobsub_name) {
4409 vo_vobsub = vobsub_open(opts->vobsub_name, spudec_ifo, 1, &vo_spudec);
4410 if (vo_vobsub == NULL)
4411 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot load subtitles: %s\n",
4412 filename_recode(opts->vobsub_name));
4413 } else if (opts->sub_auto && mpctx->filename) {
4414 char **vob = find_vob_subtitles(opts, mpctx->filename);
4415 for (int i = 0; i < MP_TALLOC_ELEMS(vob); i++) {
4416 vo_vobsub = vobsub_open(vob[i], spudec_ifo, 0, &vo_spudec);
4417 if (vo_vobsub)
4418 break;
4420 talloc_free(vob);
4422 if (vo_vobsub) {
4423 mpctx->initialized_flags |= INITIALIZED_VOBSUB;
4424 vobsub_set_from_lang(vo_vobsub, opts->sub_lang);
4425 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only,
4426 mpctx);
4428 // setup global sub numbering
4429 mpctx->sub_counts[SUB_SOURCE_VOBSUB] =
4430 vobsub_get_indexes_count(vo_vobsub);
4433 //============ Open & Sync STREAM --- fork cache2 ====================
4435 mpctx->stream = NULL;
4436 mpctx->demuxer = NULL;
4437 mpctx->d_audio = NULL;
4438 mpctx->d_video = NULL;
4439 mpctx->d_sub = NULL;
4440 mpctx->sh_audio = NULL;
4441 mpctx->sh_video = NULL;
4443 current_module = "open_stream";
4444 mpctx->stream = open_stream(mpctx->filename, opts, &mpctx->file_format);
4445 if (!mpctx->stream) { // error...
4446 mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY);
4447 goto goto_next_file;
4449 mpctx->initialized_flags |= INITIALIZED_STREAM;
4451 if (mpctx->file_format == DEMUXER_TYPE_PLAYLIST) {
4452 mp_msg(MSGT_CPLAYER, MSGL_ERR, "\nThis looks like a playlist, but "
4453 "playlist support will not be used automatically.\n"
4454 "MPlayer's playlist code is unsafe and should only be used with "
4455 "trusted sources.\nPlayback will probably fail.\n\n");
4456 #if 0
4457 play_tree_t *entry;
4458 // Handle playlist
4459 current_module = "handle_playlist";
4460 mp_msg(MSGT_CPLAYER, MSGL_V, "Parsing playlist %s...\n",
4461 filename_recode(mpctx->filename));
4462 entry = parse_playtree(mpctx->stream, mpctx->mconfig, 0);
4463 mpctx->eof = playtree_add_playlist(mpctx, entry);
4464 goto goto_next_file;
4465 #endif
4467 mpctx->stream->start_pos += seek_to_byte;
4469 if (stream_dump_type == 5) {
4470 unsigned char buf[4096];
4471 int len;
4472 FILE *f;
4473 current_module = "dumpstream";
4474 stream_reset(mpctx->stream);
4475 stream_seek(mpctx->stream, mpctx->stream->start_pos);
4476 f = fopen(opts->stream_dump_name, "wb");
4477 if (!f) {
4478 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "Cannot open dump file.\n");
4479 exit_player(mpctx, EXIT_ERROR);
4481 if (opts->chapterrange[0] > 1) {
4482 int chapter = opts->chapterrange[0] - 1;
4483 stream_control(mpctx->stream, STREAM_CTRL_SEEK_TO_CHAPTER, &chapter);
4485 struct stream_dump_progress info;
4486 stream_dump_progress_start(&info);
4487 while (!mpctx->stream->eof && !async_quit_request) {
4488 len = stream_read(mpctx->stream, buf, 4096);
4489 if (len > 0) {
4490 if (fwrite(buf, len, 1, f) != 1) {
4491 mp_tmsg(MSGT_GLOBAL, MSGL_FATAL, "%s: Error writing file.\n", opts->stream_dump_name);
4492 exit_player(mpctx, EXIT_ERROR);
4495 stream_dump_progress(&info, len, mpctx->stream);
4496 if (opts->chapterrange[1] > 0) {
4497 int chapter = -1;
4498 if (stream_control(mpctx->stream,
4499 STREAM_CTRL_GET_CURRENT_CHAPTER, &chapter) == STREAM_OK
4500 && chapter + 1 > opts->chapterrange[1])
4501 break;
4504 if (fclose(f)) {
4505 mp_tmsg(MSGT_GLOBAL, MSGL_FATAL, "%s: Error writing file.\n",
4506 opts->stream_dump_name);
4507 exit_player(mpctx, EXIT_ERROR);
4509 stream_dump_progress_end(&info, opts->stream_dump_name);
4510 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Stream dump complete.\n");
4511 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4514 #ifdef CONFIG_DVDREAD
4515 if (mpctx->stream->type == STREAMTYPE_DVD) {
4516 current_module = "dvd lang->id";
4517 if (opts->audio_lang && opts->audio_id == -1)
4518 opts->audio_id = dvd_aid_from_lang(mpctx->stream, opts->audio_lang);
4519 if (opts->sub_lang && opts->sub_id == -1)
4520 opts->sub_id = dvd_sid_from_lang(mpctx->stream, opts->sub_lang);
4521 // setup global sub numbering
4522 mpctx->sub_counts[SUB_SOURCE_DEMUX] = dvd_number_of_subs(mpctx->stream);
4523 current_module = NULL;
4525 #endif
4527 #ifdef CONFIG_DVDNAV
4528 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4529 current_module = "dvdnav lang->id";
4530 if (opts->audio_lang && opts->audio_id == -1)
4531 opts->audio_id = mp_dvdnav_aid_from_lang(mpctx->stream,
4532 opts->audio_lang);
4533 dvdsub_lang_id = -3;
4534 if (opts->sub_lang && opts->sub_id == -1)
4535 dvdsub_lang_id = opts->sub_id = mp_dvdnav_sid_from_lang(
4536 mpctx->stream, opts->sub_lang);
4537 // setup global sub numbering
4538 mpctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(
4539 mpctx->stream);
4540 current_module = NULL;
4542 #endif
4544 // CACHE2: initial prefill: 20% later: 5% (should be set by -cacheopts)
4545 goto_enable_cache:
4546 if (stream_cache_size > 0) {
4547 int res;
4548 float stream_cache_min_percent = opts->stream_cache_min_percent;
4549 float stream_cache_seek_min_percent = opts->stream_cache_seek_min_percent;
4550 current_module = "enable_cache";
4551 res = stream_enable_cache(mpctx->stream, stream_cache_size * 1024,
4552 stream_cache_size * 1024 * (stream_cache_min_percent / 100.0),
4553 stream_cache_size * 1024 * (stream_cache_seek_min_percent / 100.0));
4554 if (res == 0)
4555 if ((mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY)))
4556 goto goto_next_file;
4559 //============ Open DEMUXERS --- DETECT file type =======================
4560 current_module = "demux_open";
4562 mpctx->demuxer = demux_open(opts, mpctx->stream, mpctx->file_format,
4563 opts->audio_id, opts->video_id, opts->sub_id,
4564 mpctx->filename);
4566 // HACK to get MOV Reference Files working
4568 if (mpctx->demuxer && mpctx->demuxer->type == DEMUXER_TYPE_PLAYLIST) {
4569 unsigned char *playlist_entry;
4570 play_tree_t *list = NULL, *entry = NULL;
4572 current_module = "handle_demux_playlist";
4573 while (ds_get_packet(mpctx->demuxer->video, &playlist_entry) > 0) {
4574 char *temp;
4575 const char *bname;
4577 mp_msg(MSGT_CPLAYER, MSGL_V, "Adding file %s to element entry.\n",
4578 filename_recode(playlist_entry));
4580 bname = mp_basename(playlist_entry);
4581 if ((strlen(bname) > 10) && !strncmp(bname, "qt", 2) &&
4582 !strncmp(bname + 3, "gateQT", 6))
4583 continue;
4585 if (!strcmp(playlist_entry, mpctx->filename)) // self-reference
4586 continue;
4588 entry = play_tree_new();
4590 if (mpctx->filename && !strcmp(mp_basename(playlist_entry),
4591 playlist_entry)) { // add reference path of current file
4592 temp = malloc((strlen(mpctx->filename) - strlen(mp_basename(
4593 mpctx->filename)) + strlen(playlist_entry) + 1));
4594 if (temp) {
4595 strncpy(temp, mpctx->filename, strlen(mpctx->filename) -
4596 strlen(mp_basename(mpctx->filename)));
4597 temp[strlen(mpctx->filename) - strlen(mp_basename(
4598 mpctx->filename))] = '\0';
4599 strcat(temp, playlist_entry);
4600 if (!strcmp(temp, mpctx->filename)) {
4601 free(temp);
4602 continue;
4604 play_tree_add_file(entry, temp);
4605 mp_msg(MSGT_CPLAYER, MSGL_V,
4606 "Resolving reference to %s.\n", temp);
4607 free(temp);
4609 } else
4610 play_tree_add_file(entry, playlist_entry);
4612 if (!list)
4613 list = entry;
4614 else
4615 play_tree_append_entry(list, entry);
4617 free_demuxer(mpctx->demuxer);
4618 mpctx->demuxer = NULL;
4620 if (list) {
4621 entry = play_tree_new();
4622 play_tree_set_child(entry, list);
4623 mpctx->stop_play = playtree_add_playlist(mpctx, entry);
4624 goto goto_next_file;
4628 if (!mpctx->demuxer) {
4629 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Failed to recognize file format.\n");
4630 goto goto_next_file;
4633 if (mpctx->demuxer->matroska_data.ordered_chapters)
4634 build_ordered_chapter_timeline(mpctx);
4636 if (mpctx->demuxer->type == DEMUXER_TYPE_EDL)
4637 build_edl_timeline(mpctx);
4639 if (mpctx->timeline) {
4640 mpctx->timeline_part = 0;
4641 mpctx->demuxer = mpctx->timeline[0].source->demuxer;
4643 int part_count = mpctx->num_timeline_parts;
4644 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline contains %d parts from %d "
4645 "sources. Total length %.3f seconds.\n", part_count,
4646 mpctx->num_sources, mpctx->timeline[part_count].start);
4647 mp_msg(MSGT_CPLAYER, MSGL_V, "Source files:\n");
4648 for (int i = 0; i < mpctx->num_sources; i++)
4649 mp_msg(MSGT_CPLAYER, MSGL_V, "%d: %s\n", i,
4650 filename_recode(mpctx->sources[i].demuxer->filename));
4651 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline parts: (number, start, "
4652 "source_start, source):\n");
4653 for (int i = 0; i < part_count; i++) {
4654 struct timeline_part *p = mpctx->timeline + i;
4655 mp_msg(MSGT_CPLAYER, MSGL_V, "%3d %9.3f %9.3f %3td\n", i, p->start,
4656 p->source_start, p->source - mpctx->sources);
4658 mp_msg(MSGT_CPLAYER, MSGL_V, "END %9.3f\n",
4659 mpctx->timeline[part_count].start);
4662 if (!mpctx->sources) {
4663 mpctx->sources = talloc_ptrtype(NULL, mpctx->sources);
4664 *mpctx->sources = (struct content_source){
4665 .stream = mpctx->stream,
4666 .demuxer = mpctx->demuxer
4668 mpctx->num_sources = 1;
4671 mpctx->initialized_flags |= INITIALIZED_DEMUXER;
4673 #ifdef CONFIG_ASS
4674 if (opts->ass_enabled && mpctx->ass_library) {
4675 for (int j = 0; j < mpctx->num_sources; j++) {
4676 struct demuxer *d = mpctx->sources[j].demuxer;
4677 for (int i = 0; i < d->num_attachments; i++) {
4678 struct demux_attachment *att = d->attachments + i;
4679 if (opts->use_embedded_fonts && attachment_is_font(att))
4680 ass_add_font(mpctx->ass_library, att->name, att->data,
4681 att->data_size);
4685 #endif
4687 current_module = "demux_open2";
4689 mpctx->d_audio = mpctx->demuxer->audio;
4690 mpctx->d_video = mpctx->demuxer->video;
4691 mpctx->d_sub = mpctx->demuxer->sub;
4693 if (ts_prog) {
4694 int tmp = ts_prog;
4695 mp_property_do("switch_program", M_PROPERTY_SET, &tmp, mpctx);
4697 // select audio stream
4698 for (int i = 0; i < mpctx->num_sources; i++)
4699 select_audio(mpctx->sources[i].demuxer->audio->demuxer, opts->audio_id,
4700 opts->audio_lang);
4702 // DUMP STREAMS:
4703 if ((stream_dump_type) && (stream_dump_type < 4)) {
4704 FILE *f;
4705 demux_stream_t *ds = NULL;
4706 current_module = "dump";
4707 // select stream to dump
4708 switch (stream_dump_type) {
4709 case 1: ds = mpctx->d_audio;
4710 break;
4711 case 2: ds = mpctx->d_video;
4712 break;
4713 case 3: ds = mpctx->d_sub;
4714 break;
4716 if (!ds) {
4717 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
4718 "dump: FATAL: Selected stream missing!\n");
4719 exit_player(mpctx, EXIT_ERROR);
4721 // disable other streams:
4722 if (mpctx->d_audio && mpctx->d_audio != ds) {
4723 ds_free_packs(mpctx->d_audio);
4724 mpctx->d_audio->id = -2;
4726 if (mpctx->d_video && mpctx->d_video != ds) {
4727 ds_free_packs(mpctx->d_video);
4728 mpctx->d_video->id = -2;
4730 if (mpctx->d_sub && mpctx->d_sub != ds) {
4731 ds_free_packs(mpctx->d_sub);
4732 mpctx->d_sub->id = -2;
4734 // let's dump it!
4735 f = fopen(opts->stream_dump_name, "wb");
4736 if (!f) {
4737 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "Cannot open dump file.\n");
4738 exit_player(mpctx, EXIT_ERROR);
4740 struct stream_dump_progress info;
4741 stream_dump_progress_start(&info);
4742 while (!ds->eof) {
4743 unsigned char *start;
4744 int in_size = ds_get_packet(ds, &start);
4745 if ((mpctx->demuxer->file_format == DEMUXER_TYPE_AVI || mpctx->demuxer->file_format == DEMUXER_TYPE_ASF || mpctx->demuxer->file_format == DEMUXER_TYPE_MOV)
4746 && stream_dump_type == 2)
4747 fwrite(&in_size, 1, 4, f);
4748 if (in_size > 0) {
4749 fwrite(start, in_size, 1, f);
4750 stream_dump_progress(&info, in_size, mpctx->stream);
4752 if (opts->chapterrange[1] > 0) {
4753 int cur_chapter = demuxer_get_current_chapter(mpctx->demuxer, 0);
4754 if (cur_chapter != -1 && cur_chapter + 1 > opts->chapterrange[1])
4755 break;
4758 fclose(f);
4759 stream_dump_progress_end(&info, opts->stream_dump_name);
4760 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Stream dump complete.\n");
4761 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4764 mpctx->sh_audio = mpctx->d_audio->sh;
4765 mpctx->sh_video = mpctx->d_video->sh;
4767 if (mpctx->sh_video) {
4768 current_module = "video_read_properties";
4769 if (!video_read_properties(mpctx->sh_video)) {
4770 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Video: Cannot read properties.\n");
4771 mpctx->sh_video = mpctx->d_video->sh = NULL;
4772 } else {
4773 mp_tmsg(MSGT_CPLAYER, MSGL_V, "[V] filefmt:%d fourcc:0x%X "
4774 "size:%dx%d fps:%5.3f ftime:=%6.4f\n",
4775 mpctx->demuxer->file_format, mpctx->sh_video->format,
4776 mpctx->sh_video->disp_w, mpctx->sh_video->disp_h,
4777 mpctx->sh_video->fps, mpctx->sh_video->frametime);
4778 if (force_fps) {
4779 mpctx->sh_video->fps = force_fps;
4780 mpctx->sh_video->frametime = 1.0f / mpctx->sh_video->fps;
4782 vo_fps = mpctx->sh_video->fps;
4784 if (!mpctx->sh_video->fps && !force_fps && !opts->correct_pts) {
4785 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "FPS not specified in the "
4786 "header or invalid, use the -fps option.\n");
4792 if (!mpctx->sh_video && !mpctx->sh_audio) {
4793 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "No stream found.\n");
4794 #ifdef CONFIG_DVBIN
4795 if (mpctx->stream->type == STREAMTYPE_DVB) {
4796 int dir;
4797 int v = mpctx->last_dvb_step;
4798 if (v > 0)
4799 dir = DVB_CHANNEL_HIGHER;
4800 else
4801 dir = DVB_CHANNEL_LOWER;
4803 if (dvb_step_channel(mpctx->stream, dir)) {
4804 mpctx->stop_play = PT_NEXT_ENTRY;
4805 mpctx->dvbin_reopen = 1;
4808 #endif
4809 goto goto_next_file; // exit_player(_("Fatal error"));
4812 /* display clip info */
4813 demux_info_print(mpctx->demuxer);
4815 //================= Read SUBTITLES (DVD & TEXT) =========================
4816 if (vo_spudec == NULL && (mpctx->stream->type == STREAMTYPE_DVD
4817 || mpctx->stream->type == STREAMTYPE_DVDNAV))
4818 init_vo_spudec(mpctx);
4820 // after reading video params we should load subtitles because
4821 // we know fps so now we can adjust subtitle time to ~6 seconds AST
4822 // check .sub
4823 current_module = "read_subtitles_file";
4824 double sub_fps = mpctx->sh_video ? mpctx->sh_video->fps : 25;
4825 if (opts->sub_name) {
4826 for (i = 0; opts->sub_name[i] != NULL; ++i)
4827 add_subtitles(mpctx, opts->sub_name[i], sub_fps, 0);
4829 if (opts->sub_auto) { // auto load sub file ...
4830 char **tmp = find_text_subtitles(opts, mpctx->filename);
4831 int nsub = MP_TALLOC_ELEMS(tmp);
4832 for (int i = 0; i < nsub; i++)
4833 add_subtitles(mpctx, tmp[i], sub_fps, 1);
4834 talloc_free(tmp);
4836 if (mpctx->set_of_sub_size > 0)
4837 mpctx->sub_counts[SUB_SOURCE_SUBS] = mpctx->set_of_sub_size;
4839 if (select_subtitle(mpctx)) {
4840 if (mpctx->subdata)
4841 switch (stream_dump_type) {
4842 case 3: list_sub_file(mpctx->subdata);
4843 break;
4844 case 4: dump_mpsub(mpctx->subdata, mpctx->sh_video->fps);
4845 break;
4846 case 6: dump_srt(mpctx->subdata, mpctx->sh_video->fps);
4847 break;
4848 case 7: dump_microdvd(mpctx->subdata, mpctx->sh_video->fps);
4849 break;
4850 case 8: dump_jacosub(mpctx->subdata, mpctx->sh_video->fps);
4851 break;
4852 case 9: dump_sami(mpctx->subdata, mpctx->sh_video->fps);
4853 break;
4857 print_file_properties(mpctx, mpctx->filename);
4859 reinit_video_chain(mpctx);
4860 if (mpctx->sh_video) {
4861 if (mpctx->sh_video->output_flags & VFCAP_SPU && vo_spudec)
4862 spudec_set_hw_spu(vo_spudec, mpctx->video_out);
4863 #ifdef CONFIG_FREETYPE
4864 force_load_font = 1;
4865 #endif
4866 } else if (!mpctx->sh_audio)
4867 goto goto_next_file;
4869 //================== MAIN: ==========================
4870 current_module = "main";
4872 if (opts->playing_msg) {
4873 char *msg = property_expand_string(mpctx, opts->playing_msg);
4874 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", msg);
4875 free(msg);
4879 // Disable the term OSD in verbose mode
4880 if (verbose)
4881 opts->term_osd = 0;
4883 // Make sure old OSD does not stay around,
4884 // e.g. with -fixed-vo and same-resolution files
4885 clear_osd_msgs();
4886 update_osd_msg(mpctx);
4888 //================ SETUP AUDIO ==========================
4890 if (mpctx->sh_audio) {
4891 reinit_audio_chain(mpctx);
4892 if (mpctx->sh_audio && mpctx->sh_audio->codec)
4893 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
4894 "ID_AUDIO_CODEC=%s\n", mpctx->sh_audio->codec->name);
4897 current_module = "av_init";
4899 if (mpctx->sh_video) {
4900 mpctx->sh_video->timer = 0;
4901 if (!ignore_start)
4902 audio_delay += mpctx->sh_video->stream_delay;
4904 if (mpctx->sh_audio) {
4905 if (start_volume >= 0)
4906 mixer_setvolume(&mpctx->mixer, start_volume, start_volume);
4907 if (!ignore_start)
4908 audio_delay -= mpctx->sh_audio->stream_delay;
4909 mpctx->delay = -audio_delay;
4912 if (!mpctx->sh_audio) {
4913 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Audio: no sound\n");
4914 mp_msg(MSGT_CPLAYER, MSGL_V, "Freeing %d unused audio chunks.\n",
4915 mpctx->d_audio->packs);
4916 ds_free_packs(mpctx->d_audio); // free buffered chunks
4918 if (!mpctx->sh_video) {
4919 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Video: no video\n");
4920 mp_msg(MSGT_CPLAYER, MSGL_V, "Freeing %d unused video chunks.\n",
4921 mpctx->d_video->packs);
4922 ds_free_packs(mpctx->d_video);
4923 mpctx->d_video->id = -2;
4926 if (!mpctx->sh_video && !mpctx->sh_audio)
4927 goto goto_next_file;
4929 if (force_fps && mpctx->sh_video) {
4930 vo_fps = mpctx->sh_video->fps = force_fps;
4931 mpctx->sh_video->frametime = 1.0f / mpctx->sh_video->fps;
4932 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
4933 "FPS forced to be %5.3f (ftime: %5.3f).\n",
4934 mpctx->sh_video->fps, mpctx->sh_video->frametime);
4937 mp_input_set_section(mpctx->input, NULL);
4938 //TODO: add desired (stream-based) sections here
4939 if (mpctx->stream->type == STREAMTYPE_TV)
4940 mp_input_set_section(mpctx->input, "tv");
4941 if (mpctx->stream->type == STREAMTYPE_DVDNAV)
4942 mp_input_set_section(mpctx->input, "dvdnav");
4944 //==================== START PLAYING =======================
4946 if (opts->loop_times > 1)
4947 opts->loop_times--;
4948 else if (opts->loop_times == 1)
4949 opts->loop_times = -1;
4951 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Starting playback...\n");
4953 total_time_usage_start = GetTimer();
4954 audio_time_usage = 0;
4955 video_time_usage = 0;
4956 vout_time_usage = 0;
4957 total_frame_cnt = 0;
4958 drop_frame_cnt = 0; // fix for multifile fps benchmark
4959 play_n_frames = play_n_frames_mf;
4961 if (play_n_frames == 0) {
4962 mpctx->stop_play = PT_NEXT_ENTRY;
4963 goto goto_next_file;
4966 mpctx->time_frame = 0;
4967 mpctx->drop_message_shown = 0;
4968 mpctx->restart_playback = true;
4969 mpctx->video_pts = 0;
4970 mpctx->last_seek_pts = 0;
4971 mpctx->hrseek_active = false;
4972 mpctx->hrseek_framedrop = false;
4973 mpctx->step_frames = 0;
4974 mpctx->total_avsync_change = 0;
4975 mpctx->last_chapter_seek = -2;
4977 // If there's a timeline force an absolute seek to initialize state
4978 if (opts->seek_to_sec || mpctx->timeline) {
4979 queue_seek(mpctx, MPSEEK_ABSOLUTE, opts->seek_to_sec, 0);
4980 seek(mpctx, mpctx->seek, false);
4981 end_at.pos += opts->seek_to_sec;
4983 if (opts->chapterrange[0] > 0) {
4984 double pts;
4985 if (seek_chapter(mpctx, opts->chapterrange[0] - 1, &pts, NULL) >= 0
4986 && pts > -1.0) {
4987 queue_seek(mpctx, MPSEEK_ABSOLUTE, pts, 0);
4988 seek(mpctx, mpctx->seek, false);
4992 if (end_at.type == END_AT_SIZE) {
4993 mp_tmsg(MSGT_CPLAYER, MSGL_WARN,
4994 "Option -endpos in MPlayer does not yet support size units.\n");
4995 end_at.type = END_AT_NONE;
4998 #ifdef CONFIG_DVDNAV
4999 mp_dvdnav_context_free(mpctx);
5000 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
5001 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
5002 mp_dvdnav_cell_has_changed(mpctx->stream, 1);
5004 #endif
5006 mpctx->seek = (struct seek_params){ 0 };
5007 get_relative_time(mpctx); // reset current delta
5008 // Make sure VO knows current pause state
5009 if (mpctx->sh_video)
5010 vo_control(mpctx->video_out,
5011 mpctx->paused ? VOCTRL_PAUSE : VOCTRL_RESUME, NULL);
5013 while (!mpctx->stop_play)
5014 run_playloop(mpctx);
5016 mp_msg(MSGT_GLOBAL, MSGL_V, "EOF code: %d \n", mpctx->stop_play);
5018 #ifdef CONFIG_DVBIN
5019 if (mpctx->dvbin_reopen) {
5020 mpctx->stop_play = 0;
5021 uninit_player(mpctx, INITIALIZED_ALL - (INITIALIZED_STREAM | INITIALIZED_GETCH2 | (opts->fixed_vo ? INITIALIZED_VO : 0)));
5022 cache_uninit(mpctx->stream);
5023 mpctx->dvbin_reopen = 0;
5024 goto goto_enable_cache;
5026 #endif
5028 goto_next_file: // don't jump here after ao/vo/getch initialization!
5030 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
5032 if (opts->benchmark) {
5033 double tot = video_time_usage + vout_time_usage + audio_time_usage;
5034 double total_time_usage;
5035 total_time_usage_start = GetTimer() - total_time_usage_start;
5036 total_time_usage = (float)total_time_usage_start * 0.000001;
5037 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\nBENCHMARKs: VC:%8.3fs VO:%8.3fs "
5038 "A:%8.3fs Sys:%8.3fs = %8.3fs\n",
5039 video_time_usage, vout_time_usage, audio_time_usage,
5040 total_time_usage - tot, total_time_usage);
5041 if (total_time_usage > 0.0)
5042 mp_msg(MSGT_CPLAYER, MSGL_INFO, "BENCHMARK%%: VC:%8.4f%% "
5043 "VO:%8.4f%% A:%8.4f%% Sys:%8.4f%% = %8.4f%%\n",
5044 100.0 * video_time_usage / total_time_usage,
5045 100.0 * vout_time_usage / total_time_usage,
5046 100.0 * audio_time_usage / total_time_usage,
5047 100.0 * (total_time_usage - tot) / total_time_usage,
5048 100.0);
5049 if (total_frame_cnt && frame_dropping)
5050 mp_msg(MSGT_CPLAYER, MSGL_INFO, "BENCHMARKn: disp: %d (%3.2f fps)"
5051 " drop: %d (%d%%) total: %d (%3.2f fps)\n",
5052 total_frame_cnt - drop_frame_cnt,
5053 (total_time_usage > 0.5) ? ((total_frame_cnt -
5054 drop_frame_cnt) / total_time_usage) : 0,
5055 drop_frame_cnt,
5056 100 * drop_frame_cnt / total_frame_cnt,
5057 total_frame_cnt,
5058 (total_time_usage > 0.5) ?
5059 (total_frame_cnt / total_time_usage) : 0);
5062 // time to uninit all, except global stuff:
5063 int uninitialize_parts = INITIALIZED_ALL;
5064 if (opts->fixed_vo)
5065 uninitialize_parts -= INITIALIZED_VO;
5066 if (opts->gapless_audio && mpctx->stop_play == AT_END_OF_FILE)
5067 uninitialize_parts -= INITIALIZED_AO;
5068 uninit_player(mpctx, uninitialize_parts);
5070 if (mpctx->set_of_sub_size > 0) {
5071 current_module = "sub_free";
5072 for (i = 0; i < mpctx->set_of_sub_size; ++i) {
5073 sub_free(mpctx->set_of_subtitles[i]);
5074 #ifdef CONFIG_ASS
5075 if (mpctx->set_of_ass_tracks[i])
5076 ass_free_track(mpctx->set_of_ass_tracks[i]);
5077 #endif
5079 mpctx->set_of_sub_size = 0;
5081 mpctx->vo_sub_last = vo_sub = NULL;
5082 mpctx->subdata = NULL;
5083 #ifdef CONFIG_ASS
5084 mpctx->osd->ass_track = NULL;
5085 if (mpctx->ass_library)
5086 ass_clear_fonts(mpctx->ass_library);
5087 #endif
5089 if (!mpctx->stop_play) // In case some goto jumped here...
5090 mpctx->stop_play = PT_NEXT_ENTRY;
5092 int playtree_direction = 1;
5094 if (mpctx->stop_play == PT_NEXT_ENTRY
5095 || mpctx->stop_play == PT_PREV_ENTRY) {
5096 if (play_tree_iter_step(mpctx->playtree_iter, mpctx->play_tree_step, 0)
5097 != PLAY_TREE_ITER_ENTRY) {
5098 play_tree_iter_free(mpctx->playtree_iter);
5099 mpctx->playtree_iter = NULL;
5101 mpctx->play_tree_step = 1;
5102 } else if (mpctx->stop_play == PT_UP_NEXT ||
5103 mpctx->stop_play == PT_UP_PREV) {
5104 int direction = mpctx->stop_play == PT_UP_NEXT ? 1 : -1;
5105 if (mpctx->playtree_iter) {
5106 if (play_tree_iter_up_step(mpctx->playtree_iter, direction, 0) !=
5107 PLAY_TREE_ITER_ENTRY) {
5108 play_tree_iter_free(mpctx->playtree_iter);
5109 mpctx->playtree_iter = NULL;
5112 } else if (mpctx->stop_play == PT_STOP) {
5113 play_tree_iter_free(mpctx->playtree_iter);
5114 mpctx->playtree_iter = NULL;
5115 } else // NEXT PREV SRC
5116 playtree_direction = mpctx->stop_play == PT_PREV_SRC ? -1 : 1;
5118 while (mpctx->playtree_iter != NULL) {
5119 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,
5120 playtree_direction);
5121 if (mpctx->filename == NULL) {
5122 if (play_tree_iter_step(mpctx->playtree_iter, playtree_direction,
5123 0) != PLAY_TREE_ITER_ENTRY) {
5124 play_tree_iter_free(mpctx->playtree_iter);
5125 mpctx->playtree_iter = NULL;
5128 } else
5129 break;
5132 if (mpctx->playtree_iter != NULL || opts->player_idle_mode) {
5133 if (!mpctx->playtree_iter)
5134 mpctx->filename = NULL;
5135 mpctx->stop_play = 0;
5136 goto play_next_file;
5139 exit_player_with_rc(mpctx, EXIT_EOF, 0);
5141 return 1;
5143 #endif /* DISABLE_MAIN */