audio: add af_lavrresample, remove old resampling filters
[mplayer.git] / mplayer.c
blobdab8535235e1819a267b6b8eb014e180956accf1
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>
24 #ifdef PTW32_STATIC_LIB
25 #include <pthread.h>
26 #endif
28 #include <libavutil/intreadwrite.h>
30 #include "config.h"
31 #include "talloc.h"
33 #include "osdep/io.h"
35 #if defined(__MINGW32__) || defined(__CYGWIN__)
36 #include <windows.h>
37 // No proper file descriptor event handling; keep waking up to poll input
38 #define WAKEUP_PERIOD 0.02
39 #else
40 /* Even if we can immediately wake up in response to most input events,
41 * there are some timers which are not registered to the event loop
42 * and need to be checked periodically (like automatic mouse cursor hiding).
43 * OSD content updates behave similarly. Also some uncommon input devices
44 * may not have proper FD event support.
46 #define WAKEUP_PERIOD 0.5
47 #endif
48 #include <string.h>
49 #include <unistd.h>
51 // #include <sys/mman.h>
52 #include <sys/types.h>
53 #ifndef __MINGW32__
54 #include <sys/ioctl.h>
55 #include <sys/wait.h>
56 #else
57 #define SIGHUP 1 /* hangup */
58 #define SIGQUIT 3 /* quit */
59 #define SIGKILL 9 /* kill (cannot be caught or ignored) */
60 #define SIGBUS 10 /* bus error */
61 #define SIGPIPE 13 /* broken pipe */
62 #endif
64 #include <sys/time.h>
65 #include <sys/stat.h>
67 #include <signal.h>
68 #include <time.h>
69 #include <fcntl.h>
70 #include <limits.h>
72 #include <errno.h>
74 #include "mp_msg.h"
75 #include "av_log.h"
78 #include "m_option.h"
79 #include "m_config.h"
80 #include "mplayer.h"
81 #include "m_property.h"
83 #include "sub/subreader.h"
84 #include "sub/find_subfiles.h"
85 #include "sub/dec_sub.h"
86 #include "sub/sub_cc.h"
88 #include "mp_osd.h"
89 #include "libvo/video_out.h"
90 #include "screenshot.h"
92 #include "sub/sub.h"
93 #include "libmpcodecs/dec_teletext.h"
94 #include "cpudetect.h"
95 #include "version.h"
97 #ifdef CONFIG_X11
98 #include "libvo/x11_common.h"
99 #endif
101 #include "libao2/audio_out.h"
103 #include "codec-cfg.h"
105 #include "sub/spudec.h"
106 #include "sub/vobsub.h"
108 #include "osdep/getch2.h"
109 #include "osdep/timer.h"
111 #include "input/input.h"
113 int slave_mode = 0;
114 int enable_mouse_movements = 0;
115 float start_volume = -1;
117 #include "osdep/priority.h"
119 char *heartbeat_cmd;
121 #ifdef HAVE_RTC
122 #ifdef __linux__
123 #include <linux/rtc.h>
124 #else
125 #include <rtc.h>
126 #define RTC_IRQP_SET RTCIO_IRQP_SET
127 #define RTC_PIE_ON RTCIO_PIE_ON
128 #endif /* __linux__ */
129 #endif /* HAVE_RTC */
131 #include "stream/tv.h"
132 #include "stream/stream_radio.h"
133 #ifdef CONFIG_DVBIN
134 #include "stream/dvbin.h"
135 #endif
136 #include "stream/cache2.h"
138 //**************************************************************************//
139 // Playtree
140 //**************************************************************************//
141 #include "playtree.h"
142 #include "playtreeparser.h"
144 //**************************************************************************//
145 // Config
146 //**************************************************************************//
147 #include "parser-cfg.h"
148 #include "parser-mpcmd.h"
150 //**************************************************************************//
151 // Config file
152 //**************************************************************************//
154 #include "path.h"
156 //**************************************************************************//
157 //**************************************************************************//
158 // Input media streaming & demultiplexer:
159 //**************************************************************************//
161 static int max_framesize = 0;
163 #include "stream/stream.h"
164 #include "libmpdemux/demuxer.h"
165 #include "libmpdemux/stheader.h"
167 #ifdef CONFIG_DVDREAD
168 #include "stream/stream_dvd.h"
169 #endif
170 #include "stream/stream_dvdnav.h"
172 #include "libmpcodecs/dec_audio.h"
173 #include "libmpcodecs/dec_video.h"
174 #include "libmpcodecs/mp_image.h"
175 #include "libmpcodecs/vf.h"
176 #include "libmpcodecs/vd.h"
178 #include "mixer.h"
180 #include "mp_core.h"
181 #include "options.h"
182 #include "defaultopts.h"
184 static const char help_text[] = _(
185 "Usage: mplayer [options] [url|path/]filename\n"
186 "\n"
187 "Basic options: (complete list in the man page)\n"
188 " -vo <drv> select video output driver ('-vo help' for a list)\n"
189 " -ao <drv> select audio output driver ('-ao help' for a list)\n"
190 #ifdef CONFIG_VCD
191 " vcd://<trackno> play (S)VCD (Super Video CD) track (raw device, no mount)\n"
192 #endif
193 #ifdef CONFIG_DVDREAD
194 " dvd://<titleno> play DVD title from device instead of plain file\n"
195 #endif
196 " -alang/-slang select DVD audio/subtitle language (by 2-char country code)\n"
197 " -ss <position> seek to given (seconds or hh:mm:ss) position\n"
198 " -nosound do not play sound\n"
199 " -fs fullscreen playback (or -vm, -zoom, details in the man page)\n"
200 " -x <x> -y <y> set display resolution (for use with -vm or -zoom)\n"
201 " -sub <file> specify subtitle file to use (also see -subfps, -subdelay)\n"
202 " -playlist <file> specify playlist file\n"
203 " -vid x -aid y select video (x) and audio (y) stream to play\n"
204 " -fps x -srate y change video (x fps) and audio (y Hz) rate\n"
205 " -pp <quality> enable postprocessing filter (details in the man page)\n"
206 " -framedrop enable frame dropping (for slow machines)\n"
207 "\n"
208 "Basic keys: (complete list in the man page, also check input.conf)\n"
209 " <- or -> seek backward/forward 10 seconds\n"
210 " down or up seek backward/forward 1 minute\n"
211 " pgdown or pgup seek backward/forward 10 minutes\n"
212 " < or > step backward/forward in playlist\n"
213 " p or SPACE pause movie (press any key to continue)\n"
214 " q or ESC stop playing and quit program\n"
215 " + or - adjust audio delay by +/- 0.1 second\n"
216 " o cycle OSD mode: none / seekbar / seekbar + timer\n"
217 " * or / increase or decrease PCM volume\n"
218 " x or z adjust subtitle delay by +/- 0.1 second\n"
219 " r or t adjust subtitle position up/down, also see -vf expand\n"
220 " double click toggle fullscreen\n"
221 " right click pause (press again to continue)\n"
222 "\n"
223 " * * * SEE THE MAN PAGE FOR DETAILS, FURTHER (ADVANCED) OPTIONS AND KEYS * * *\n"
224 "\n");
227 #define Exit_SIGILL_RTCpuSel _(\
228 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
229 " It may be a bug in our new runtime CPU-detection code...\n"\
230 " Please read DOCS/HTML/en/bugreports.html.\n")
232 #define Exit_SIGILL _(\
233 "- MPlayer crashed by an 'Illegal Instruction'.\n"\
234 " It usually happens when you run it on a CPU different than the one it was\n"\
235 " compiled/optimized for.\n"\
236 " Verify this!\n")
238 #define Exit_SIGSEGV_SIGFPE _(\
239 "- MPlayer crashed by bad usage of CPU/FPU/RAM.\n"\
240 " Recompile MPlayer with --enable-debug and make a 'gdb' backtrace and\n"\
241 " disassembly. Details in DOCS/HTML/en/bugreports_what.html#bugreports_crash.\n")
243 #define Exit_SIGCRASH _(\
244 "- MPlayer crashed. This shouldn't happen.\n"\
245 " It can be a bug in the MPlayer code _or_ in your drivers _or_ in your\n"\
246 " gcc version. If you think it's MPlayer's fault, please read\n"\
247 " DOCS/HTML/en/bugreports.html and follow the instructions there. We can't and\n"\
248 " won't help unless you provide this information when reporting a possible bug.\n")
250 #define SystemTooSlow _("\n\n"\
251 " ************************************************\n"\
252 " **** Your system is too SLOW to play this! ****\n"\
253 " ************************************************\n\n"\
257 //**************************************************************************//
258 //**************************************************************************//
260 #include "mp_fifo.h"
262 // benchmark:
263 double video_time_usage;
264 double vout_time_usage;
265 static double audio_time_usage;
266 static int total_time_usage_start;
267 static int total_frame_cnt;
268 static int drop_frame_cnt; // total number of dropped frames
270 // options:
271 static int output_quality;
273 // seek:
274 static off_t seek_to_byte;
275 static off_t step_sec;
277 static m_time_size_t end_at = { .type = END_AT_NONE, .pos = 0 };
279 // codecs:
280 char **audio_codec_list; // override audio codec
281 char **video_codec_list; // override video codec
282 char **audio_fm_list; // override audio codec family
283 char **video_fm_list; // override video codec family
285 // this dvdsub_id was selected via slang
286 // use this to allow dvdnav to follow -slang across stream resets,
287 // in particular the subtitle ID for a language changes
288 int dvdsub_lang_id;
289 int vobsub_id = -1;
290 static char *spudec_ifo = NULL;
291 int forced_subs_only = 0;
293 // dump:
294 int stream_dump_type = 0;
296 // A-V sync:
297 static float default_max_pts_correction = -1;
298 float audio_delay = 0;
299 static int ignore_start = 0;
301 double force_fps = 0;
302 static int force_srate = 0;
303 int frame_dropping = 0; // option 0=no drop 1= drop vo 2= drop decode
304 static int play_n_frames = -1;
305 static int play_n_frames_mf = -1;
307 #include "sub/ass_mp.h"
309 char *current_module; // for debugging
312 // ---
314 FILE *edl_fd; // file to write to when in -edlout mode.
315 char *edl_output_filename; // file to put EDL entries in (-edlout)
317 int use_filedir_conf;
318 int use_filename_title;
320 #include "mpcommon.h"
321 #include "command.h"
323 #include "metadata.h"
325 static float get_relative_time(struct MPContext *mpctx)
327 unsigned int new_time = GetTimer();
328 unsigned int delta = new_time - mpctx->last_time;
329 mpctx->last_time = new_time;
330 return delta * 0.000001;
333 static int is_valid_metadata_type(struct MPContext *mpctx, metadata_t type)
335 switch (type) {
336 /* check for valid video stream */
337 case META_VIDEO_CODEC:
338 case META_VIDEO_BITRATE:
339 case META_VIDEO_RESOLUTION:
340 if (!mpctx->sh_video)
341 return 0;
342 break;
344 /* check for valid audio stream */
345 case META_AUDIO_CODEC:
346 case META_AUDIO_BITRATE:
347 case META_AUDIO_SAMPLES:
348 if (!mpctx->sh_audio)
349 return 0;
350 break;
352 /* check for valid demuxer */
353 case META_INFO_TITLE:
354 case META_INFO_ARTIST:
355 case META_INFO_ALBUM:
356 case META_INFO_YEAR:
357 case META_INFO_COMMENT:
358 case META_INFO_TRACK:
359 case META_INFO_GENRE:
360 if (!mpctx->demuxer)
361 return 0;
362 break;
364 default:
365 break;
368 return 1;
371 static char *get_demuxer_info(struct MPContext *mpctx, char *tag)
373 char **info = mpctx->demuxer->info;
374 int n;
376 if (!info || !tag)
377 return talloc_strdup(NULL, "");
379 for (n = 0; info[2 * n] != NULL; n++)
380 if (!strcasecmp(info[2 * n], tag))
381 break;
383 return talloc_strdup(NULL, info[2 * n + 1] ? info[2 * n + 1] : "");
386 char *get_metadata(struct MPContext *mpctx, metadata_t type)
388 sh_audio_t * const sh_audio = mpctx->sh_audio;
389 sh_video_t * const sh_video = mpctx->sh_video;
391 if (!is_valid_metadata_type(mpctx, type))
392 return NULL;
394 switch (type) {
395 case META_NAME:
396 return talloc_strdup(NULL, mp_basename(mpctx->filename));
397 case META_VIDEO_CODEC:
398 if (sh_video->format == 0x10000001)
399 return talloc_strdup(NULL, "mpeg1");
400 else if (sh_video->format == 0x10000002)
401 return talloc_strdup(NULL, "mpeg2");
402 else if (sh_video->format == 0x10000004)
403 return talloc_strdup(NULL, "mpeg4");
404 else if (sh_video->format == 0x10000005)
405 return talloc_strdup(NULL, "h264");
406 else if (sh_video->format >= 0x20202020)
407 return talloc_asprintf(NULL, "%.4s", (char *) &sh_video->format);
408 else
409 return talloc_asprintf(NULL, "0x%08X", sh_video->format);
410 case META_VIDEO_BITRATE:
411 return talloc_asprintf(NULL, "%d kbps",
412 (int) (sh_video->i_bps * 8 / 1024));
413 case META_VIDEO_RESOLUTION:
414 return talloc_asprintf(NULL, "%d x %d", sh_video->disp_w,
415 sh_video->disp_h);
416 case META_AUDIO_CODEC:
417 if (sh_audio->codec && sh_audio->codec->name)
418 return talloc_strdup(NULL, sh_audio->codec->name);
419 return talloc_strdup(NULL, "");
420 case META_AUDIO_BITRATE:
421 return talloc_asprintf(NULL, "%d kbps",
422 (int) (sh_audio->i_bps * 8 / 1000));
423 case META_AUDIO_SAMPLES:
424 return talloc_asprintf(NULL, "%d Hz, %d ch.", sh_audio->samplerate,
425 sh_audio->channels);
427 /* check for valid demuxer */
428 case META_INFO_TITLE:
429 return get_demuxer_info(mpctx, "Title");
431 case META_INFO_ARTIST:
432 return get_demuxer_info(mpctx, "Artist");
434 case META_INFO_ALBUM:
435 return get_demuxer_info(mpctx, "Album");
437 case META_INFO_YEAR:
438 return get_demuxer_info(mpctx, "Year");
440 case META_INFO_COMMENT:
441 return get_demuxer_info(mpctx, "Comment");
443 case META_INFO_TRACK:
444 return get_demuxer_info(mpctx, "Track");
446 case META_INFO_GENRE:
447 return get_demuxer_info(mpctx, "Genre");
449 default:
450 break;
453 return talloc_strdup(NULL, "");
456 static void print_file_properties(struct MPContext *mpctx, const char *filename)
458 double start_pts = MP_NOPTS_VALUE;
459 double video_start_pts = MP_NOPTS_VALUE;
460 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILENAME=%s\n",
461 filename_recode(filename));
462 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_DEMUXER=%s\n",
463 mpctx->demuxer->desc->name);
464 if (mpctx->sh_video) {
465 /* Assume FOURCC if all bytes >= 0x20 (' ') */
466 if (mpctx->sh_video->format >= 0x20202020)
467 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
468 "ID_VIDEO_FORMAT=%.4s\n", (char *)&mpctx->sh_video->format);
469 else
470 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
471 "ID_VIDEO_FORMAT=0x%08X\n", mpctx->sh_video->format);
472 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
473 "ID_VIDEO_BITRATE=%d\n", mpctx->sh_video->i_bps * 8);
474 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
475 "ID_VIDEO_WIDTH=%d\n", mpctx->sh_video->disp_w);
476 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
477 "ID_VIDEO_HEIGHT=%d\n", mpctx->sh_video->disp_h);
478 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
479 "ID_VIDEO_FPS=%5.3f\n", mpctx->sh_video->fps);
480 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
481 "ID_VIDEO_ASPECT=%1.4f\n", mpctx->sh_video->aspect);
482 video_start_pts = ds_get_next_pts(mpctx->d_video);
484 if (mpctx->sh_audio) {
485 /* Assume FOURCC if all bytes >= 0x20 (' ') */
486 if (mpctx->sh_audio->format >= 0x20202020)
487 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
488 "ID_AUDIO_FORMAT=%.4s\n", (char *)&mpctx->sh_audio->format);
489 else
490 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
491 "ID_AUDIO_FORMAT=%d\n", mpctx->sh_audio->format);
492 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
493 "ID_AUDIO_BITRATE=%d\n", mpctx->sh_audio->i_bps * 8);
494 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
495 "ID_AUDIO_RATE=%d\n", mpctx->sh_audio->samplerate);
496 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
497 "ID_AUDIO_NCH=%d\n", mpctx->sh_audio->channels);
498 start_pts = ds_get_next_pts(mpctx->d_audio);
500 if (video_start_pts != MP_NOPTS_VALUE) {
501 if (start_pts == MP_NOPTS_VALUE || !mpctx->sh_audio ||
502 (mpctx->sh_video && video_start_pts < start_pts))
503 start_pts = video_start_pts;
505 if (start_pts != MP_NOPTS_VALUE)
506 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_START_TIME=%.2f\n", start_pts);
507 else
508 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_START_TIME=unknown\n");
509 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
510 "ID_LENGTH=%.2f\n", get_time_length(mpctx));
511 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SEEKABLE=%d\n",
512 mpctx->stream->seek
513 && (!mpctx->demuxer || mpctx->demuxer->seekable));
514 if (mpctx->demuxer) {
515 int chapter_count = get_chapter_count(mpctx);
516 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_CHAPTERS=%d\n", chapter_count);
517 for (int i = 0; i < chapter_count; i++) {
518 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_CHAPTER_ID=%d\n", i);
519 // in milliseconds
520 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_CHAPTER_%d_START=%"PRIu64"\n",
521 i, (int64_t)(chapter_start_time(mpctx, i) * 1000.0));
522 char *name = chapter_name(mpctx, i);
523 if (name) {
524 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_CHAPTER_%d_NAME=%s\n", i,
525 name);
526 talloc_free(name);
532 /// step size of mixer changes
533 int volstep = 3;
535 #ifdef CONFIG_DVDNAV
536 static void mp_dvdnav_context_free(MPContext *ctx)
538 if (ctx->nav_smpi)
539 free_mp_image(ctx->nav_smpi);
540 ctx->nav_smpi = NULL;
541 free(ctx->nav_buffer);
542 ctx->nav_buffer = NULL;
543 ctx->nav_start = NULL;
544 ctx->nav_in_size = 0;
546 #endif
548 static void uninit_subs(struct demuxer *demuxer)
550 for (int i = 0; i < MAX_S_STREAMS; i++) {
551 struct sh_sub *sh = demuxer->s_streams[i];
552 if (sh && sh->initialized)
553 sub_uninit(sh);
557 void uninit_player(struct MPContext *mpctx, unsigned int mask)
559 mask &= mpctx->initialized_flags;
561 mp_msg(MSGT_CPLAYER, MSGL_DBG2, "\n*** uninit(0x%X)\n", mask);
563 if (mask & INITIALIZED_ACODEC) {
564 mpctx->initialized_flags &= ~INITIALIZED_ACODEC;
565 current_module = "uninit_acodec";
566 if (mpctx->sh_audio)
567 uninit_audio(mpctx->sh_audio);
568 mpctx->sh_audio = NULL;
569 mpctx->mixer.afilter = NULL;
572 if (mask & INITIALIZED_SUB) {
573 mpctx->initialized_flags &= ~INITIALIZED_SUB;
574 if (mpctx->osd->sh_sub)
575 sub_switchoff(mpctx->osd->sh_sub, mpctx->osd);
578 if (mask & INITIALIZED_VCODEC) {
579 mpctx->initialized_flags &= ~INITIALIZED_VCODEC;
580 current_module = "uninit_vcodec";
581 if (mpctx->sh_video)
582 uninit_video(mpctx->sh_video);
583 mpctx->sh_video = NULL;
586 if (mask & INITIALIZED_DEMUXER) {
587 mpctx->initialized_flags &= ~INITIALIZED_DEMUXER;
588 current_module = "free_demuxer";
589 if (mpctx->num_sources) {
590 mpctx->demuxer = mpctx->sources[0].demuxer;
591 for (int i = 1; i < mpctx->num_sources; i++) {
592 uninit_subs(mpctx->sources[i].demuxer);
593 free_stream(mpctx->sources[i].stream);
594 free_demuxer(mpctx->sources[i].demuxer);
597 talloc_free(mpctx->sources);
598 mpctx->sources = NULL;
599 mpctx->num_sources = 0;
600 talloc_free(mpctx->timeline);
601 mpctx->timeline = NULL;
602 mpctx->num_timeline_parts = 0;
603 talloc_free(mpctx->chapters);
604 mpctx->chapters = NULL;
605 mpctx->num_chapters = 0;
606 mpctx->video_offset = 0;
607 if (mpctx->demuxer) {
608 mpctx->stream = mpctx->demuxer->stream;
609 uninit_subs(mpctx->demuxer);
610 free_demuxer(mpctx->demuxer);
612 mpctx->demuxer = NULL;
615 // kill the cache process:
616 if (mask & INITIALIZED_STREAM) {
617 mpctx->initialized_flags &= ~INITIALIZED_STREAM;
618 current_module = "uninit_stream";
619 if (mpctx->stream)
620 free_stream(mpctx->stream);
621 mpctx->stream = NULL;
624 if (mask & INITIALIZED_VO) {
625 mpctx->initialized_flags &= ~INITIALIZED_VO;
626 current_module = "uninit_vo";
627 vo_destroy(mpctx->video_out);
628 mpctx->video_out = NULL;
629 #ifdef CONFIG_DVDNAV
630 mp_dvdnav_context_free(mpctx);
631 #endif
634 // Must be after libvo uninit, as few vo drivers (svgalib) have tty code.
635 if (mask & INITIALIZED_GETCH2) {
636 mpctx->initialized_flags &= ~INITIALIZED_GETCH2;
637 current_module = "uninit_getch2";
638 mp_msg(MSGT_CPLAYER, MSGL_DBG2, "\n[[[uninit getch2]]]\n");
639 // restore terminal:
640 getch2_disable();
643 if (mask & INITIALIZED_VOBSUB) {
644 mpctx->initialized_flags &= ~INITIALIZED_VOBSUB;
645 current_module = "uninit_vobsub";
646 if (vo_vobsub)
647 vobsub_close(vo_vobsub);
648 vo_vobsub = NULL;
651 if (mask & INITIALIZED_SPUDEC) {
652 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
653 current_module = "uninit_spudec";
654 spudec_free(vo_spudec);
655 vo_spudec = NULL;
658 if (mask & INITIALIZED_AO) {
659 mpctx->initialized_flags &= ~INITIALIZED_AO;
660 current_module = "uninit_ao";
661 mixer_uninit(&mpctx->mixer);
662 if (mpctx->ao)
663 ao_uninit(mpctx->ao, mpctx->stop_play != AT_END_OF_FILE);
664 mpctx->ao = NULL;
667 current_module = NULL;
670 void exit_player_with_rc(struct MPContext *mpctx, enum exit_reason how, int rc)
672 uninit_player(mpctx, INITIALIZED_ALL);
673 #if defined(__MINGW32__) || defined(__CYGWIN__)
674 timeEndPeriod(1);
675 #endif
677 current_module = "uninit_input";
678 mp_input_uninit(mpctx->input);
680 osd_free(mpctx->osd);
682 #ifdef CONFIG_ASS
683 ass_library_done(mpctx->ass_library);
684 mpctx->ass_library = NULL;
685 #endif
687 current_module = "exit_player";
689 if (mpctx->playtree_iter)
690 play_tree_iter_free(mpctx->playtree_iter);
691 mpctx->playtree_iter = NULL;
692 if (mpctx->playtree)
693 play_tree_free(mpctx->playtree, 1);
694 mpctx->playtree = NULL;
696 talloc_free(mpctx->key_fifo);
698 switch (how) {
699 case EXIT_QUIT:
700 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nExiting... (%s)\n", "Quit");
701 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=QUIT\n");
702 break;
703 case EXIT_EOF:
704 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nExiting... (%s)\n", "End of file");
705 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=EOF\n");
706 break;
707 case EXIT_ERROR:
708 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nExiting... (%s)\n", "Fatal error");
709 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=ERROR\n");
710 break;
711 default:
712 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_EXIT=NONE\n");
714 mp_msg(MSGT_CPLAYER, MSGL_DBG2,
715 "max framesize was %d bytes\n", max_framesize);
717 // must be last since e.g. mp_msg uses option values
718 // that will be freed by this.
719 if (mpctx->mconfig)
720 m_config_free(mpctx->mconfig);
721 mpctx->mconfig = NULL;
723 talloc_free(mpctx);
725 exit(rc);
728 static void exit_player(struct MPContext *mpctx, enum exit_reason how)
730 exit_player_with_rc(mpctx, how, 1);
733 #ifndef __MINGW32__
734 static void child_sighandler(int x)
736 pid_t pid;
737 while ((pid = waitpid(-1, NULL, WNOHANG)) > 0) ;
739 #endif
741 #ifdef CONFIG_CRASH_DEBUG
742 static char *prog_path;
743 static int crash_debug = 0;
744 #endif
746 static void exit_sighandler(int x)
748 static int sig_count = 0;
749 #ifdef CONFIG_CRASH_DEBUG
750 if (!crash_debug || x != SIGTRAP)
751 #endif
752 ++sig_count;
753 if (sig_count == 5) {
754 /* We're crashing bad and can't uninit cleanly :(
755 * by popular request, we make one last (dirty)
756 * effort to restore the user's
757 * terminal. */
758 getch2_disable();
759 exit(1);
761 if (sig_count == 6)
762 exit(1);
763 if (sig_count > 6) {
764 // can't stop :(
765 #ifndef __MINGW32__
766 kill(getpid(), SIGKILL);
767 #endif
769 mp_msg(MSGT_CPLAYER, MSGL_FATAL, "\n");
770 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
771 "\nMPlayer interrupted by signal %d in module: %s\n", x,
772 current_module ? current_module : "unknown");
773 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SIGNAL=%d\n", x);
774 if (sig_count <= 1)
775 switch (x) {
776 case SIGINT:
777 case SIGPIPE:
778 case SIGQUIT:
779 case SIGTERM:
780 case SIGKILL:
781 async_quit_request = 1;
782 return; // killed from keyboard (^C) or killed [-9]
783 case SIGILL:
784 #if CONFIG_RUNTIME_CPUDETECT
785 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGILL_RTCpuSel);
786 #else
787 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGILL);
788 #endif
789 case SIGFPE:
790 case SIGSEGV:
791 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGSEGV_SIGFPE);
792 default:
793 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, Exit_SIGCRASH);
794 #ifdef CONFIG_CRASH_DEBUG
795 if (crash_debug) {
796 int gdb_pid;
797 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forking...\n");
798 gdb_pid = fork();
799 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Forked...\n");
800 if (gdb_pid == 0) { // We are the child
801 char spid[20];
802 snprintf(spid, sizeof(spid), "%i", getppid());
803 getch2_disable(); // allow terminal to work properly with gdb
804 if (execlp("gdb", "gdb", prog_path, spid, "-ex", "bt", NULL) == -1)
805 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't start gdb\n");
806 } else if (gdb_pid < 0)
807 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Couldn't fork\n");
808 else
809 waitpid(gdb_pid, NULL, 0);
810 if (x == SIGTRAP)
811 return;
813 #endif
815 getch2_disable();
816 exit(1);
819 #include "cfg-mplayer.h"
821 static int cfg_include(struct m_config *conf, char *filename)
823 return m_config_parse_config_file(conf, filename);
826 #define DEF_CONFIG "# Write your default config options here!\n\n\n"
828 static void parse_cfgfiles(struct MPContext *mpctx, m_config_t *conf)
830 struct MPOpts *opts = &mpctx->opts;
831 char *conffile;
832 int conffile_fd;
833 if (!(opts->noconfig & 2) &&
834 m_config_parse_config_file(conf, MPLAYER_CONFDIR "/mplayer.conf") < 0)
835 exit_player(mpctx, EXIT_NONE);
836 if ((conffile = get_path("")) == NULL)
837 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Cannot find HOME directory.\n");
838 else {
839 mkdir(conffile, 0777);
840 free(conffile);
841 if ((conffile = get_path("config")) == NULL)
842 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "get_path(\"config\") problem\n");
843 else {
844 if ((conffile_fd = open(conffile, O_CREAT | O_EXCL | O_WRONLY,
845 0666)) != -1) {
846 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
847 "Creating config file: %s\n", conffile);
848 write(conffile_fd, DEF_CONFIG, sizeof(DEF_CONFIG) - 1);
849 close(conffile_fd);
851 if (!(opts->noconfig & 1) &&
852 m_config_parse_config_file(conf, conffile) < 0)
853 exit_player(mpctx, EXIT_NONE);
854 free(conffile);
859 #define PROFILE_CFG_PROTOCOL "protocol."
861 static void load_per_protocol_config(m_config_t *conf, const char * const file)
863 char *str;
864 char protocol[strlen(PROFILE_CFG_PROTOCOL) + strlen(file) + 1];
865 m_profile_t *p;
867 /* does filename actually uses a protocol ? */
868 str = strstr(file, "://");
869 if (!str)
870 return;
872 sprintf(protocol, "%s%s", PROFILE_CFG_PROTOCOL, file);
873 protocol[strlen(PROFILE_CFG_PROTOCOL) + strlen(file) - strlen(str)] = '\0';
874 p = m_config_get_profile(conf, protocol);
875 if (p) {
876 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
877 "Loading protocol-related profile '%s'\n", protocol);
878 m_config_set_profile(conf, p);
882 #define PROFILE_CFG_EXTENSION "extension."
884 static void load_per_extension_config(m_config_t *conf, const char * const file)
886 char *str;
887 char extension[strlen(PROFILE_CFG_EXTENSION) + 8];
888 m_profile_t *p;
890 /* does filename actually have an extension ? */
891 str = strrchr(file, '.');
892 if (!str)
893 return;
895 sprintf(extension, PROFILE_CFG_EXTENSION);
896 strncat(extension, ++str, 7);
897 p = m_config_get_profile(conf, extension);
898 if (p) {
899 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
900 "Loading extension-related profile '%s'\n", extension);
901 m_config_set_profile(conf, p);
905 #define PROFILE_CFG_VO "vo."
906 #define PROFILE_CFG_AO "ao."
908 static void load_per_output_config(m_config_t *conf, char *cfg, char *out)
910 char profile[strlen(cfg) + strlen(out) + 1];
911 m_profile_t *p;
913 sprintf(profile, "%s%s", cfg, out);
914 p = m_config_get_profile(conf, profile);
915 if (p) {
916 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
917 "Loading extension-related profile '%s'\n", profile);
918 m_config_set_profile(conf, p);
923 * Tries to load a config file
924 * @return 0 if file was not found, 1 otherwise
926 static int try_load_config(m_config_t *conf, const char *file)
928 if (!mp_path_exists(file))
929 return 0;
930 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Loading config '%s'\n", file);
931 m_config_parse_config_file(conf, file);
932 return 1;
935 static void load_per_file_config(m_config_t *conf, const char * const file)
937 char *confpath;
938 char cfg[MP_PATH_MAX];
939 const char *name;
941 if (strlen(file) > MP_PATH_MAX - 14) {
942 mp_msg(MSGT_CPLAYER, MSGL_WARN, "Filename is too long, "
943 "can not load file or directory specific config files\n");
944 return;
946 sprintf(cfg, "%s.conf", file);
948 name = mp_basename(cfg);
949 if (use_filedir_conf) {
950 char dircfg[MP_PATH_MAX];
951 strcpy(dircfg, cfg);
952 strcpy(dircfg + (name - cfg), "mplayer.conf");
953 try_load_config(conf, dircfg);
955 if (try_load_config(conf, cfg))
956 return;
959 if ((confpath = get_path(name)) != NULL) {
960 try_load_config(conf, confpath);
962 free(confpath);
966 /* When libmpdemux performs a blocking operation (network connection or
967 * cache filling) if the operation fails we use this function to check
968 * if it was interrupted by the user.
969 * The function returns a new value for eof. */
970 static int libmpdemux_was_interrupted(struct MPContext *mpctx, int stop_play)
972 mp_cmd_t *cmd;
973 if ((cmd = mp_input_get_cmd(mpctx->input, 0, 0)) != NULL) {
974 switch (cmd->id) {
975 case MP_CMD_QUIT:
976 exit_player_with_rc(mpctx, EXIT_QUIT,
977 (cmd->nargs > 0) ? cmd->args[0].v.i : 0);
978 case MP_CMD_PLAY_TREE_STEP: {
979 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_ENTRY : PT_PREV_ENTRY;
980 mpctx->play_tree_step =
981 (cmd->args[0].v.i == 0) ? 1 : cmd->args[0].v.i;
982 } break;
983 case MP_CMD_PLAY_TREE_UP_STEP: {
984 stop_play = (cmd->args[0].v.i > 0) ? PT_UP_NEXT : PT_UP_PREV;
985 } break;
986 case MP_CMD_PLAY_ALT_SRC_STEP: {
987 stop_play = (cmd->args[0].v.i > 0) ? PT_NEXT_SRC : PT_PREV_SRC;
988 } break;
990 mp_cmd_free(cmd);
992 return stop_play;
995 static int playtree_add_playlist(struct MPContext *mpctx, play_tree_t *entry)
997 play_tree_add_bpf(entry, bstr(mpctx->filename));
1000 if (!entry) {
1001 entry = mpctx->playtree_iter->tree;
1002 if (play_tree_iter_step(mpctx->playtree_iter, 1, 0)
1003 != PLAY_TREE_ITER_ENTRY)
1004 return PT_NEXT_ENTRY;
1005 if (mpctx->playtree_iter->tree == entry) { // Single file loop
1006 if (play_tree_iter_up_step(mpctx->playtree_iter, 1, 0)
1007 != PLAY_TREE_ITER_ENTRY)
1008 return PT_NEXT_ENTRY;
1010 play_tree_remove(entry, 1, 1);
1011 return PT_NEXT_SRC;
1013 play_tree_insert_entry(mpctx->playtree_iter->tree, entry);
1014 play_tree_set_params_from(entry, mpctx->playtree_iter->tree);
1015 entry = mpctx->playtree_iter->tree;
1016 if (play_tree_iter_step(mpctx->playtree_iter, 1, 0)
1017 != PLAY_TREE_ITER_ENTRY)
1018 return PT_NEXT_ENTRY;
1019 play_tree_remove(entry, 1, 1);
1021 return PT_NEXT_SRC;
1024 void add_subtitles(struct MPContext *mpctx, char *filename, float fps,
1025 int noerr)
1027 struct MPOpts *opts = &mpctx->opts;
1028 sub_data *subd = NULL;
1029 struct sh_sub *sh = NULL;
1031 if (filename == NULL || mpctx->set_of_sub_size >= MAX_SUBTITLE_FILES)
1032 return;
1034 if (opts->ass_enabled) {
1035 #ifdef CONFIG_ASS
1036 struct ass_track *asst;
1037 #ifdef CONFIG_ICONV
1038 asst = mp_ass_read_stream(mpctx->ass_library, opts, filename, sub_cp);
1039 #else
1040 asst = mp_ass_read_stream(mpctx->ass_library, opts, filename, 0);
1041 #endif
1042 bool is_native_ass = asst;
1043 if (!asst) {
1044 subd = sub_read_file(filename, fps, &mpctx->opts);
1045 if (subd) {
1046 asst = mp_ass_read_subdata(mpctx->ass_library, opts, subd, fps);
1047 sub_free(subd);
1048 subd = NULL;
1051 if (asst)
1052 sh = sd_ass_create_from_track(asst, is_native_ass, opts);
1053 #endif
1054 } else
1055 subd = sub_read_file(filename, fps, &mpctx->opts);
1058 if (!sh && !subd) {
1059 mp_tmsg(MSGT_CPLAYER, noerr ? MSGL_WARN : MSGL_ERR,
1060 "Cannot load subtitles: %s\n", filename_recode(filename));
1061 return;
1064 mpctx->set_of_ass_tracks[mpctx->set_of_sub_size] = sh;
1065 mpctx->set_of_subtitles[mpctx->set_of_sub_size] = subd;
1066 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
1067 "ID_FILE_SUB_ID=%d\n", mpctx->set_of_sub_size);
1068 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_FILE_SUB_FILENAME=%s\n",
1069 filename_recode(filename));
1070 ++mpctx->set_of_sub_size;
1071 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "SUB: Added subtitle file (%d): %s\n",
1072 mpctx->set_of_sub_size, filename_recode(filename));
1075 void init_vo_spudec(struct MPContext *mpctx)
1077 unsigned width, height;
1078 spudec_free(vo_spudec);
1079 mpctx->initialized_flags &= ~INITIALIZED_SPUDEC;
1080 vo_spudec = NULL;
1082 // we currently can't work without video stream
1083 if (!mpctx->sh_video)
1084 return;
1086 if (spudec_ifo) {
1087 unsigned int palette[16];
1088 current_module = "spudec_init_vobsub";
1089 if (vobsub_parse_ifo(NULL, spudec_ifo, palette, &width, &height,
1090 1, -1, NULL) >= 0)
1091 vo_spudec = spudec_new_scaled(palette, width, height, NULL, 0);
1094 width = mpctx->sh_video->disp_w;
1095 height = mpctx->sh_video->disp_h;
1097 #ifdef CONFIG_DVDREAD
1098 if (vo_spudec == NULL && mpctx->stream->type == STREAMTYPE_DVD) {
1099 current_module = "spudec_init_dvdread";
1100 vo_spudec = spudec_new_scaled(((dvd_priv_t *)(mpctx->stream->priv))->
1101 cur_pgc->palette, width, height, NULL, 0);
1103 #endif
1105 #ifdef CONFIG_DVDNAV
1106 if (vo_spudec == NULL && mpctx->stream->type == STREAMTYPE_DVDNAV) {
1107 unsigned int *palette = mp_dvdnav_get_spu_clut(mpctx->stream);
1108 current_module = "spudec_init_dvdnav";
1109 vo_spudec = spudec_new_scaled(palette, width, height, NULL, 0);
1111 #endif
1113 if (vo_spudec == NULL) {
1114 sh_sub_t *sh = mpctx->d_sub->sh;
1115 current_module = "spudec_init_normal";
1116 vo_spudec = spudec_new_scaled(NULL, width, height, sh->extradata,
1117 sh->extradata_len);
1118 spudec_set_font_factor(vo_spudec, font_factor);
1121 if (vo_spudec != NULL) {
1122 mpctx->initialized_flags |= INITIALIZED_SPUDEC;
1123 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only,
1124 mpctx);
1129 * In Mac OS X the SDL-lib is built upon Cocoa. The easiest way to
1130 * make it all work is to use the builtin SDL-bootstrap code, which
1131 * will be done automatically by replacing our main() if we include SDL.h.
1133 #if defined(__APPLE__) && defined(CONFIG_SDL)
1134 #ifdef CONFIG_SDL_SDL_H
1135 #include <SDL/SDL.h>
1136 #else
1137 #include <SDL.h>
1138 #endif
1139 #endif
1142 * \brief append a formatted string
1143 * \param buf buffer to print into
1144 * \param pos position of terminating 0 in buf
1145 * \param len maximum number of characters in buf, not including terminating 0
1146 * \param format printf format string
1148 static void saddf(char *buf, unsigned *pos, int len, const char *format, ...)
1150 va_list va;
1151 va_start(va, format);
1152 *pos += vsnprintf(&buf[*pos], len - *pos, format, va);
1153 va_end(va);
1154 if (*pos >= len) {
1155 buf[len] = 0;
1156 *pos = len;
1161 * \brief append time in the hh:mm:ss.f format
1162 * \param buf buffer to print into
1163 * \param pos position of terminating 0 in buf
1164 * \param len maximum number of characters in buf, not including terminating 0
1165 * \param time time value to convert/append
1167 static void sadd_hhmmssf(char *buf, unsigned *pos, int len, float time)
1169 int64_t tenths = 10 * time;
1170 int f1 = tenths % 10;
1171 int ss = (tenths / 10) % 60;
1172 int mm = (tenths / 600) % 60;
1173 int hh = tenths / 36000;
1174 if (time < 0) {
1175 saddf(buf, pos, len, "unknown");
1176 return;
1178 if (hh > 0)
1179 saddf(buf, pos, len, "%2d:", hh);
1180 if (hh > 0 || mm > 0)
1181 saddf(buf, pos, len, "%02d:", mm);
1182 saddf(buf, pos, len, "%02d.%1d", ss, f1);
1185 static void print_status(struct MPContext *mpctx, double a_pos, bool at_frame)
1187 struct MPOpts *opts = &mpctx->opts;
1188 sh_video_t * const sh_video = mpctx->sh_video;
1190 if (mpctx->sh_audio && a_pos == MP_NOPTS_VALUE)
1191 a_pos = playing_audio_pts(mpctx);
1192 if (mpctx->sh_audio && sh_video && at_frame) {
1193 mpctx->last_av_difference = a_pos - mpctx->video_pts - audio_delay;
1194 if (mpctx->time_frame > 0)
1195 mpctx->last_av_difference +=
1196 mpctx->time_frame * opts->playback_speed;
1197 if (a_pos == MP_NOPTS_VALUE || mpctx->video_pts == MP_NOPTS_VALUE)
1198 mpctx->last_av_difference = MP_NOPTS_VALUE;
1199 if (mpctx->last_av_difference > 0.5 && drop_frame_cnt > 50
1200 && !mpctx->drop_message_shown) {
1201 mp_tmsg(MSGT_AVSYNC, MSGL_WARN, SystemTooSlow);
1202 mpctx->drop_message_shown = true;
1205 if (opts->quiet)
1206 return;
1208 int width;
1209 char *line;
1210 unsigned pos = 0;
1211 get_screen_size();
1212 if (screen_width > 0)
1213 width = screen_width;
1214 else
1215 width = 80;
1216 #if defined(__MINGW32__) || defined(__CYGWIN__)
1217 /* Windows command line is broken (MinGW's rxvt works, but we
1218 * should not depend on that). */
1219 width--;
1220 #endif
1221 line = malloc(width + 1); // one additional char for the terminating null
1223 // Audio time
1224 if (mpctx->sh_audio) {
1225 if (a_pos != MP_NOPTS_VALUE)
1226 saddf(line, &pos, width, "A:%6.1f ", a_pos);
1227 else
1228 saddf(line, &pos, width, "A: ??? ");
1229 if (!sh_video && a_pos != MP_NOPTS_VALUE) {
1230 float len = get_time_length(mpctx);
1231 saddf(line, &pos, width, "(");
1232 sadd_hhmmssf(line, &pos, width, a_pos);
1233 saddf(line, &pos, width, ") of %.1f (", len);
1234 sadd_hhmmssf(line, &pos, width, len);
1235 saddf(line, &pos, width, ") ");
1239 // Video time
1240 if (sh_video) {
1241 if (mpctx->video_pts != MP_NOPTS_VALUE)
1242 saddf(line, &pos, width, "V:%6.1f ", mpctx->video_pts);
1243 else
1244 saddf(line, &pos, width, "V: ??? ", mpctx->video_pts);
1247 // A-V sync
1248 if (mpctx->sh_audio && sh_video) {
1249 if (mpctx->last_av_difference != MP_NOPTS_VALUE)
1250 saddf(line, &pos, width, "A-V:%7.3f ct:%7.3f ",
1251 mpctx->last_av_difference, mpctx->total_avsync_change);
1252 else
1253 saddf(line, &pos, width, "A-V: ??? ct:%7.3f ",
1254 mpctx->total_avsync_change);
1257 // Video stats
1258 if (sh_video)
1259 saddf(line, &pos, width, "%3d/%3d ",
1260 (int)sh_video->num_frames,
1261 (int)sh_video->num_frames_decoded);
1263 // CPU usage
1264 if (sh_video) {
1265 if (sh_video->timer > 0.5)
1266 saddf(line, &pos, width, "%2d%% %2d%% %4.1f%% ",
1267 (int)(100.0 * video_time_usage * opts->playback_speed / (double)sh_video->timer),
1268 (int)(100.0 * vout_time_usage * opts->playback_speed / (double)sh_video->timer),
1269 (100.0 * audio_time_usage * opts->playback_speed / (double)sh_video->timer));
1270 else
1271 saddf(line, &pos, width, "??%% ??%% ??,?%% ");
1272 } else if (mpctx->sh_audio) {
1273 if (mpctx->delay > 0.5)
1274 saddf(line, &pos, width, "%4.1f%% ",
1275 100.0 * audio_time_usage / (double)mpctx->delay);
1276 else
1277 saddf(line, &pos, width, "??,?%% ");
1280 // VO stats
1281 if (sh_video)
1282 saddf(line, &pos, width, "%d %d ", drop_frame_cnt, output_quality);
1284 #ifdef CONFIG_STREAM_CACHE
1285 // cache stats
1286 if (mpctx->stream->cached)
1287 saddf(line, &pos, width, "%d%% ", cache_fill_status(mpctx->stream));
1288 #endif
1290 // other
1291 if (opts->playback_speed != 1)
1292 saddf(line, &pos, width, "%4.2fx ", opts->playback_speed);
1294 // end
1295 if (erase_to_end_of_line) {
1296 line[pos] = 0;
1297 mp_msg(MSGT_STATUSLINE, MSGL_STATUS,
1298 "%s%s\r", line, erase_to_end_of_line);
1299 } else {
1300 memset(&line[pos], ' ', width - pos);
1301 line[width] = 0;
1302 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s\r", line);
1304 free(line);
1306 mpctx->status_printed = true;
1309 struct stream_dump_progress {
1310 uint64_t count;
1311 unsigned start_time;
1312 unsigned last_print_time;
1315 static void stream_dump_progress_start(struct stream_dump_progress *p)
1317 p->start_time = p->last_print_time = GetTimerMS();
1318 p->count = 0;
1321 static void stream_dump_progress(struct stream_dump_progress *p,
1322 uint64_t len, stream_t *stream)
1324 p->count += len;
1325 unsigned t = GetTimerMS();
1326 if (t - p->last_print_time < 1000)
1327 return;
1329 uint64_t start = stream->start_pos;
1330 uint64_t end = stream->end_pos;
1331 uint64_t pos = stream->pos;
1333 p->last_print_time = t;
1334 /* TODO: pretty print sizes; ETA */
1335 if (end > start && pos >= start && pos <= end) {
1336 mp_tmsg(MSGT_STATUSLINE, MSGL_STATUS,
1337 "dump: %"PRIu64 " bytes written (~%.1f%%)",
1338 p->count, 100.0 * (pos - start) / (end - start));
1339 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "\r");
1340 } else {
1341 mp_tmsg(MSGT_STATUSLINE, MSGL_STATUS,
1342 "dump: %"PRIu64 " bytes written", p->count);
1343 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "\r");
1347 static void stream_dump_progress_end(struct stream_dump_progress *p, char *name)
1349 mp_msg(MSGT_CPLAYER, MSGL_INFO, "dump: %"PRIu64 " bytes written to '%s'.\n",
1350 p->count, name);
1354 * \brief build a chain of audio filters that converts the input format
1355 * to the ao's format, taking into account the current playback_speed.
1356 * sh_audio describes the requested input format of the chain.
1357 * ao describes the requested output format of the chain.
1359 static int build_afilter_chain(struct MPContext *mpctx)
1361 struct sh_audio *sh_audio = mpctx->sh_audio;
1362 struct ao *ao = mpctx->ao;
1363 struct MPOpts *opts = &mpctx->opts;
1364 int new_srate;
1365 int result;
1366 if (!sh_audio) {
1367 mpctx->mixer.afilter = NULL;
1368 return 0;
1370 if (af_control_any_rev(sh_audio->afilter,
1371 AF_CONTROL_PLAYBACK_SPEED | AF_CONTROL_SET,
1372 &opts->playback_speed))
1373 new_srate = sh_audio->samplerate;
1374 else {
1375 new_srate = sh_audio->samplerate * opts->playback_speed;
1376 if (new_srate != ao->samplerate) {
1377 // limits are taken from libaf/af_resample.c
1378 if (new_srate < 8000)
1379 new_srate = 8000;
1380 if (new_srate > 192000)
1381 new_srate = 192000;
1382 opts->playback_speed = (float)new_srate / sh_audio->samplerate;
1385 result = init_audio_filters(sh_audio, new_srate,
1386 &ao->samplerate, &ao->channels, &ao->format);
1387 mpctx->mixer.afilter = sh_audio->afilter;
1388 return result;
1392 typedef struct mp_osd_msg mp_osd_msg_t;
1393 struct mp_osd_msg {
1394 /// Previous message on the stack.
1395 mp_osd_msg_t *prev;
1396 /// Message text.
1397 char *msg;
1398 int id, level, started;
1399 /// Display duration in ms.
1400 unsigned time;
1401 // Show full OSD for duration of message instead of static text ('P' key)
1402 bool show_position;
1405 /// OSD message stack.
1406 static mp_osd_msg_t *osd_msg_stack = NULL;
1409 * \brief Add a message on the OSD message stack
1411 * If a message with the same id is already present in the stack
1412 * it is pulled on top of the stack, otherwise a new message is created.
1415 static void set_osd_msg_va(int id, int level, int time, bool show_position,
1416 const char *fmt, va_list ap)
1418 mp_osd_msg_t *msg, *last = NULL;
1420 // look if the id is already in the stack
1421 for (msg = osd_msg_stack; msg && msg->id != id;
1422 last = msg, msg = msg->prev) ;
1423 // not found: alloc it
1424 if (!msg) {
1425 msg = talloc_zero(NULL, mp_osd_msg_t);
1426 msg->prev = osd_msg_stack;
1427 osd_msg_stack = msg;
1428 } else if (last) { // found, but it's not on top of the stack
1429 last->prev = msg->prev;
1430 msg->prev = osd_msg_stack;
1431 osd_msg_stack = msg;
1433 talloc_free(msg->msg);
1434 // write the msg
1435 msg->msg = talloc_vasprintf(msg, fmt, ap);
1436 // set id and time
1437 msg->id = id;
1438 msg->level = level;
1439 msg->time = time;
1440 msg->show_position = show_position;
1443 void set_osd_msg(int id, int level, int time, const char *fmt, ...)
1445 va_list ap;
1446 va_start(ap, fmt);
1447 set_osd_msg_va(id, level, time, false, fmt, ap);
1448 va_end(ap);
1451 void set_osd_tmsg(int id, int level, int time, const char *fmt, ...)
1453 va_list ap;
1454 va_start(ap, fmt);
1455 set_osd_msg_va(id, level, time, false, mp_gtext(fmt), ap);
1456 va_end(ap);
1459 void set_osd_progressmsg(int id, int level, int time, ...)
1461 va_list ap;
1462 va_start(ap, time);
1463 set_osd_msg_va(id, level, time, true, "", ap);
1464 va_end(ap);
1468 * \brief Remove a message from the OSD stack
1470 * This function can be used to get rid of a message right away.
1474 void rm_osd_msg(int id)
1476 mp_osd_msg_t *msg, *last = NULL;
1478 // Search for the msg
1479 for (msg = osd_msg_stack; msg && msg->id != id;
1480 last = msg, msg = msg->prev) ;
1481 if (!msg)
1482 return;
1484 // Detach it from the stack and free it
1485 if (last)
1486 last->prev = msg->prev;
1487 else
1488 osd_msg_stack = msg->prev;
1489 talloc_free(msg);
1493 * \brief Remove all messages from the OSD stack
1497 static void clear_osd_msgs(void)
1499 mp_osd_msg_t *msg = osd_msg_stack, *prev = NULL;
1500 while (msg) {
1501 prev = msg->prev;
1502 talloc_free(msg);
1503 msg = prev;
1505 osd_msg_stack = NULL;
1509 * \brief Get the current message from the OSD stack.
1511 * This function decrements the message timer and destroys the old ones.
1512 * The message that should be displayed is returned (if any).
1516 static mp_osd_msg_t *get_osd_msg(struct MPContext *mpctx)
1518 struct MPOpts *opts = &mpctx->opts;
1519 mp_osd_msg_t *msg, *prev, *last = NULL;
1520 static unsigned last_update = 0;
1521 unsigned now = GetTimerMS();
1522 unsigned diff;
1523 char hidden_dec_done = 0;
1525 if (mpctx->osd_visible) {
1526 // 36000000 means max timed visibility is 1 hour into the future, if
1527 // the difference is greater assume it's wrapped around from below 0
1528 if (mpctx->osd_visible - now > 36000000) {
1529 mpctx->osd_visible = 0;
1530 vo_osd_progbar_type = -1; // disable
1531 vo_osd_changed(OSDTYPE_PROGBAR);
1532 mpctx->osd_function = mpctx->paused ? OSD_PAUSE : OSD_PLAY;
1535 if (mpctx->osd_show_percentage_until - now > 36000000)
1536 mpctx->osd_show_percentage_until = 0;
1538 if (!last_update)
1539 last_update = now;
1540 diff = now >= last_update ? now - last_update : 0;
1542 last_update = now;
1544 // Look for the first message in the stack with high enough level.
1545 for (msg = osd_msg_stack; msg; last = msg, msg = prev) {
1546 prev = msg->prev;
1547 if (msg->level > opts->osd_level && hidden_dec_done)
1548 continue;
1549 // The message has a high enough level or it is the first hidden one
1550 // in both cases we decrement the timer or kill it.
1551 if (!msg->started || msg->time > diff) {
1552 if (msg->started)
1553 msg->time -= diff;
1554 else
1555 msg->started = 1;
1556 // display it
1557 if (msg->level <= opts->osd_level)
1558 return msg;
1559 hidden_dec_done = 1;
1560 continue;
1562 // kill the message
1563 talloc_free(msg);
1564 if (last) {
1565 last->prev = prev;
1566 msg = last;
1567 } else {
1568 osd_msg_stack = prev;
1569 msg = NULL;
1572 // Nothing found
1573 return NULL;
1577 * \brief Display the OSD bar.
1579 * Display the OSD bar or fall back on a simple message.
1583 void set_osd_bar(struct MPContext *mpctx, int type, const char *name,
1584 double min, double max, double val)
1586 struct MPOpts *opts = &mpctx->opts;
1587 if (opts->osd_level < 1)
1588 return;
1590 if (mpctx->sh_video) {
1591 mpctx->osd_visible = (GetTimerMS() + 1000) | 1;
1592 vo_osd_progbar_type = type;
1593 vo_osd_progbar_value = 256 * (val - min) / (max - min);
1594 vo_osd_changed(OSDTYPE_PROGBAR);
1595 return;
1598 set_osd_msg(OSD_MSG_BAR, 1, opts->osd_duration, "%s: %d %%",
1599 name, ROUND(100 * (val - min) / (max - min)));
1603 * \brief Display text subtitles on the OSD
1605 void set_osd_subtitle(struct MPContext *mpctx, subtitle *subs)
1607 int i;
1608 vo_sub = subs;
1609 vo_osd_changed(OSDTYPE_SUBTITLE);
1610 if (!mpctx->sh_video) {
1611 // reverse order, since newest set_osd_msg is displayed first
1612 for (i = SUB_MAX_TEXT - 1; i >= 0; i--) {
1613 if (!subs || i >= subs->lines || !subs->text[i])
1614 rm_osd_msg(OSD_MSG_SUB_BASE + i);
1615 else {
1616 // HACK: currently display time for each sub line
1617 // except the last is set to 2 seconds.
1618 int display_time = i == subs->lines - 1 ? 180000 : 2000;
1619 set_osd_msg(OSD_MSG_SUB_BASE + i, 1, display_time,
1620 "%s", subs->text[i]);
1627 * \brief Update the OSD message line.
1629 * This function displays the current message on the vo OSD or on the term.
1630 * If the stack is empty and the OSD level is high enough the timer
1631 * is displayed (only on the vo OSD).
1635 static void update_osd_msg(struct MPContext *mpctx)
1637 struct MPOpts *opts = &mpctx->opts;
1638 mp_osd_msg_t *msg;
1639 struct osd_state *osd = mpctx->osd;
1641 if (mpctx->add_osd_seek_info) {
1642 double percentage = get_percent_pos(mpctx);
1643 set_osd_bar(mpctx, 0, "Position", 0, 100, percentage);
1644 if (mpctx->sh_video)
1645 mpctx->osd_show_percentage_until = (GetTimerMS() + 1000) | 1;
1646 mpctx->add_osd_seek_info = false;
1649 // Look if we have a msg
1650 if ((msg = get_osd_msg(mpctx)) && !msg->show_position) {
1651 if (strcmp(osd->osd_text, msg->msg)) {
1652 osd_set_text(osd, msg->msg);
1653 if (mpctx->sh_video)
1654 vo_osd_changed(OSDTYPE_OSD);
1655 else if (opts->term_osd)
1656 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s%s\n", opts->term_osd_esc,
1657 msg->msg);
1659 return;
1662 int osdlevel = opts->osd_level;
1663 if (msg && msg->show_position)
1664 osdlevel = 3;
1666 if (mpctx->sh_video) {
1667 // fallback on the timer
1668 char osd_text_timer[128] = {0};
1669 if (osdlevel >= 2) {
1670 int len = get_time_length(mpctx);
1671 int percentage = -1;
1672 char percentage_text[10];
1673 char fractions_text[4];
1674 double fpts = get_current_time(mpctx);
1675 int pts = fpts;
1677 if (mpctx->osd_show_percentage_until)
1678 percentage = get_percent_pos(mpctx);
1680 if (percentage >= 0)
1681 snprintf(percentage_text, 9, " (%d%%)", percentage);
1682 else
1683 percentage_text[0] = 0;
1685 if (opts->osd_fractions == 1) {
1686 //print fractions as sub-second timestamp
1687 snprintf(fractions_text, sizeof(fractions_text), ".%02d",
1688 (int)((fpts - pts) * 100));
1689 } else if (opts->osd_fractions == 2) {
1690 /* Print fractions by estimating the frame count within the
1691 * second.
1693 * Rounding or cutting off numbers after the decimal point
1694 * causes problems because of float's precision and movies
1695 * whose first frame is not exactly at timestamp 0. Therefore,
1696 * we add 0.2 and cut off at the decimal point, which proved
1697 * to be good heuristic.
1699 double fps = mpctx->sh_video->fps;
1700 if (fps <= 1 || fps > 99)
1701 strcpy(fractions_text, ".??");
1702 else
1703 snprintf(fractions_text, sizeof(fractions_text), ".%02d",
1704 (int) ((fpts - pts) * fps + 0.2));
1705 } else {
1706 //do not print fractions
1707 fractions_text[0] = 0;
1710 osd_get_function_sym(osd_text_timer, sizeof(osd_text_timer),
1711 mpctx->osd_function);
1712 size_t blen = strlen(osd_text_timer);
1714 if (osdlevel == 3)
1715 snprintf(osd_text_timer + blen, sizeof(osd_text_timer) - blen,
1716 " %02d:%02d:%02d%s / %02d:%02d:%02d%s",
1717 pts / 3600, (pts / 60) % 60, pts % 60, fractions_text,
1718 len / 3600, (len / 60) % 60, len % 60,
1719 percentage_text);
1720 else
1721 snprintf(osd_text_timer + blen, sizeof(osd_text_timer) - blen,
1722 " %02d:%02d:%02d%s%s",
1723 pts / 3600, (pts / 60) % 60, pts % 60, fractions_text,
1724 percentage_text);
1727 if (strcmp(osd->osd_text, osd_text_timer)) {
1728 osd_set_text(osd, osd_text_timer);
1729 vo_osd_changed(OSDTYPE_OSD);
1731 return;
1734 // Clear the term osd line
1735 if (opts->term_osd && osd->osd_text[0]) {
1736 osd->osd_text[0] = 0;
1737 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s\n", opts->term_osd_esc);
1742 void reinit_audio_chain(struct MPContext *mpctx)
1744 struct MPOpts *opts = &mpctx->opts;
1745 struct ao *ao;
1746 if (!mpctx->sh_audio) {
1747 uninit_player(mpctx, INITIALIZED_AO);
1748 return;
1750 if (!(mpctx->initialized_flags & INITIALIZED_ACODEC)) {
1751 current_module = "init_audio_codec";
1752 if (!init_best_audio_codec(mpctx->sh_audio, audio_codec_list, audio_fm_list))
1753 goto init_error;
1754 mpctx->initialized_flags |= INITIALIZED_ACODEC;
1757 current_module = "af_preinit";
1758 if (!(mpctx->initialized_flags & INITIALIZED_AO)) {
1759 mpctx->initialized_flags |= INITIALIZED_AO;
1760 mpctx->ao = ao_create(opts, mpctx->input);
1761 mpctx->ao->samplerate = force_srate;
1762 mpctx->ao->format = opts->audio_output_format;
1764 ao = mpctx->ao;
1766 // first init to detect best values
1767 if (!init_audio_filters(mpctx->sh_audio, // preliminary init
1768 // input:
1769 mpctx->sh_audio->samplerate,
1770 // output:
1771 &ao->samplerate, &ao->channels, &ao->format)) {
1772 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Error at audio filter chain "
1773 "pre-init!\n");
1774 exit_player(mpctx, EXIT_ERROR);
1776 if (!ao->initialized) {
1777 current_module = "ao2_init";
1778 ao->buffersize = opts->ao_buffersize;
1779 ao_init(ao, opts->audio_driver_list);
1780 if (!ao->initialized) {
1781 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
1782 "Could not open/initialize audio device -> no sound.\n");
1783 goto init_error;
1785 ao->buffer.start = talloc_new(ao);
1786 mp_msg(MSGT_CPLAYER, MSGL_INFO,
1787 "AO: [%s] %dHz %dch %s (%d bytes per sample)\n",
1788 ao->driver->info->short_name,
1789 ao->samplerate, ao->channels,
1790 af_fmt2str_short(ao->format),
1791 af_fmt2bits(ao->format) / 8);
1792 mp_msg(MSGT_CPLAYER, MSGL_V, "AO: Description: %s\nAO: Author: %s\n",
1793 ao->driver->info->name, ao->driver->info->author);
1794 if (strlen(ao->driver->info->comment) > 0)
1795 mp_msg(MSGT_CPLAYER, MSGL_V, "AO: Comment: %s\n",
1796 ao->driver->info->comment);
1799 // init audio filters:
1800 current_module = "af_init";
1801 if (!build_afilter_chain(mpctx)) {
1802 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
1803 "Couldn't find matching filter/ao format!\n");
1804 goto init_error;
1806 mpctx->mixer.volstep = volstep;
1807 mpctx->mixer.softvol = opts->softvol;
1808 mpctx->mixer.softvol_max = opts->softvol_max;
1809 mixer_reinit(&mpctx->mixer, ao);
1810 mpctx->syncing_audio = true;
1811 return;
1813 init_error:
1814 uninit_player(mpctx, INITIALIZED_ACODEC | INITIALIZED_AO);
1815 mpctx->sh_audio = mpctx->d_audio->sh = NULL; // -> nosound
1816 mpctx->d_audio->id = -2;
1820 // Return pts value corresponding to the end point of audio written to the
1821 // ao so far.
1822 static double written_audio_pts(struct MPContext *mpctx)
1824 sh_audio_t *sh_audio = mpctx->sh_audio;
1825 if (!sh_audio)
1826 return MP_NOPTS_VALUE;
1827 demux_stream_t *d_audio = mpctx->d_audio;
1828 // first calculate the end pts of audio that has been output by decoder
1829 double a_pts = sh_audio->pts;
1830 if (a_pts != MP_NOPTS_VALUE)
1831 // Good, decoder supports new way of calculating audio pts.
1832 // sh_audio->pts is the timestamp of the latest input packet with
1833 // known pts that the decoder has decoded. sh_audio->pts_bytes is
1834 // the amount of bytes the decoder has written after that timestamp.
1835 a_pts += sh_audio->pts_bytes / (double) sh_audio->o_bps;
1836 else {
1837 // Decoder doesn't support new way of calculating pts (or we're
1838 // being called before it has decoded anything with known timestamp).
1839 // Use the old method of audio pts calculation: take the timestamp
1840 // of last packet with known pts the decoder has read data from,
1841 // and add amount of bytes read after the beginning of that packet
1842 // divided by input bps. This will be inaccurate if the input/output
1843 // ratio is not constant for every audio packet or if it is constant
1844 // but not accurately known in sh_audio->i_bps.
1846 a_pts = d_audio->pts;
1847 if (a_pts == MP_NOPTS_VALUE)
1848 return a_pts;
1850 // ds_tell_pts returns bytes read after last timestamp from
1851 // demuxing layer, decoder might use sh_audio->a_in_buffer for bytes
1852 // it has read but not decoded
1853 if (sh_audio->i_bps)
1854 a_pts += (ds_tell_pts(d_audio) - sh_audio->a_in_buffer_len) /
1855 (double)sh_audio->i_bps;
1857 // Now a_pts hopefully holds the pts for end of audio from decoder.
1858 // Substract data in buffers between decoder and audio out.
1860 // Decoded but not filtered
1861 a_pts -= sh_audio->a_buffer_len / (double)sh_audio->o_bps;
1863 // Data buffered in audio filters, measured in bytes of "missing" output
1864 double buffered_output = af_calc_delay(sh_audio->afilter);
1866 // Data that was ready for ao but was buffered because ao didn't fully
1867 // accept everything to internal buffers yet
1868 buffered_output += mpctx->ao->buffer.len;
1870 // Filters divide audio length by playback_speed, so multiply by it
1871 // to get the length in original units without speedup or slowdown
1872 a_pts -= buffered_output * mpctx->opts.playback_speed / mpctx->ao->bps;
1874 return a_pts + mpctx->video_offset;
1877 // Return pts value corresponding to currently playing audio.
1878 double playing_audio_pts(struct MPContext *mpctx)
1880 double pts = written_audio_pts(mpctx);
1881 if (pts == MP_NOPTS_VALUE)
1882 return pts;
1883 return pts - mpctx->opts.playback_speed *ao_get_delay(mpctx->ao);
1886 static bool is_av_sub(int type)
1888 return type == 'b' || type == 'p' || type == 'x';
1891 void update_subtitles(struct MPContext *mpctx, double refpts_tl, bool reset)
1893 mpctx->osd->sub_offset = mpctx->video_offset;
1894 struct MPOpts *opts = &mpctx->opts;
1895 struct sh_video *sh_video = mpctx->sh_video;
1896 struct demux_stream *d_sub = mpctx->d_sub;
1897 double refpts_s = refpts_tl - mpctx->osd->sub_offset;
1898 double curpts_s = refpts_s + opts->sub_delay;
1899 unsigned char *packet = NULL;
1900 int len;
1901 struct sh_sub *sh_sub = d_sub->sh;
1902 int type = sh_sub ? sh_sub->type : 'v';
1903 static subtitle subs;
1904 if (reset) {
1905 if (sh_sub)
1906 sub_reset(sh_sub, mpctx->osd);
1907 sub_clear_text(&subs, MP_NOPTS_VALUE);
1908 if (vo_sub)
1909 set_osd_subtitle(mpctx, NULL);
1910 if (vo_spudec) {
1911 spudec_reset(vo_spudec);
1912 vo_osd_changed(OSDTYPE_SPU);
1914 return;
1916 // find sub
1917 if (mpctx->subdata) {
1918 if (sub_fps == 0)
1919 sub_fps = sh_video ? sh_video->fps : 25;
1920 current_module = "find_sub";
1921 find_sub(mpctx, mpctx->subdata, curpts_s *
1922 (mpctx->subdata->sub_uses_time ? 100. : sub_fps));
1923 if (vo_sub)
1924 mpctx->vo_sub_last = vo_sub;
1927 // DVD sub:
1928 if (vobsub_id >= 0 || type == 'v') {
1929 int timestamp;
1930 current_module = "spudec";
1931 /* Get a sub packet from the DVD or a vobsub */
1932 while (1) {
1933 // Vobsub
1934 len = 0;
1935 if (vo_vobsub) {
1936 if (curpts_s >= 0) {
1937 len = vobsub_get_packet(vo_vobsub, curpts_s,
1938 (void **)&packet, &timestamp);
1939 if (len > 0)
1940 mp_dbg(MSGT_CPLAYER, MSGL_V, "\rVOB sub: len=%d "
1941 "v_pts=%5.3f v_timer=%5.3f sub=%5.3f ts=%d \n",
1942 len, refpts_s, sh_video->timer,
1943 timestamp / 90000.0, timestamp);
1945 } else {
1946 // DVD sub
1947 len = ds_get_packet_sub(d_sub, (unsigned char **)&packet);
1948 if (len > 0) {
1949 // XXX This is wrong, sh_video->pts can be arbitrarily
1950 // much behind demuxing position. Unfortunately using
1951 // d_video->pts which would have been the simplest
1952 // improvement doesn't work because mpeg specific hacks
1953 // in video.c set d_video->pts to 0.
1954 float x = d_sub->pts - refpts_s;
1955 if (x > -20 && x < 20) // prevent missing subs on pts reset
1956 timestamp = 90000 * d_sub->pts;
1957 else
1958 timestamp = 90000 * curpts_s;
1959 mp_dbg(MSGT_CPLAYER, MSGL_V, "\rDVD sub: len=%d "
1960 "v_pts=%5.3f s_pts=%5.3f ts=%d \n", len,
1961 refpts_s, d_sub->pts, timestamp);
1964 if (len <= 0 || !packet)
1965 break;
1966 // create it only here, since with some broken demuxers we might
1967 // type = v but no DVD sub and we currently do not change the
1968 // "original frame size" ever after init, leading to wrong-sized
1969 // PGS subtitles.
1970 if (!vo_spudec)
1971 vo_spudec = spudec_new(NULL);
1972 if (vo_vobsub || timestamp >= 0)
1973 spudec_assemble(vo_spudec, packet, len, timestamp);
1975 } else if (is_text_sub(type) || is_av_sub(type) || type == 'd') {
1976 if (type == 'd' && !d_sub->demuxer->teletext) {
1977 tt_stream_props tsp = { 0 };
1978 void *ptr = &tsp;
1979 if (teletext_control(NULL, TV_VBI_CONTROL_START, &ptr) ==
1980 VBI_CONTROL_TRUE)
1981 d_sub->demuxer->teletext = ptr;
1983 if (d_sub->non_interleaved)
1984 ds_get_next_pts(d_sub);
1986 while (d_sub->first) {
1987 double subpts_s = ds_get_next_pts(d_sub);
1988 if (subpts_s > curpts_s) {
1989 // Libass handled subs can be fed to it in advance
1990 if (!opts->ass_enabled || !is_text_sub(type))
1991 break;
1992 // Try to avoid demuxing whole file at once
1993 if (d_sub->non_interleaved && subpts_s > curpts_s + 1)
1994 break;
1996 double duration = d_sub->first->duration;
1997 len = ds_get_packet_sub(d_sub, &packet);
1998 if (type == 'm') {
1999 if (len < 2)
2000 continue;
2001 len = FFMIN(len - 2, AV_RB16(packet));
2002 packet += 2;
2004 if (type == 'd') {
2005 if (d_sub->demuxer->teletext) {
2006 uint8_t *p = packet;
2007 p++;
2008 len--;
2009 while (len >= 46) {
2010 int sublen = p[1];
2011 if (p[0] == 2 || p[0] == 3)
2012 teletext_control(d_sub->demuxer->teletext,
2013 TV_VBI_CONTROL_DECODE_DVB, p + 2);
2014 p += sublen + 2;
2015 len -= sublen + 2;
2018 continue;
2020 if (sh_sub && sh_sub->active) {
2021 sub_decode(sh_sub, mpctx->osd, packet, len, subpts_s, duration);
2022 continue;
2024 if (subpts_s != MP_NOPTS_VALUE) {
2025 if (duration < 0)
2026 sub_clear_text(&subs, MP_NOPTS_VALUE);
2027 if (type == 'a') { // ssa/ass subs without libass => convert to plaintext
2028 int i;
2029 unsigned char *p = packet;
2030 for (i = 0; i < 8 && *p != '\0'; p++)
2031 if (*p == ',')
2032 i++;
2033 if (*p == '\0') /* Broken line? */
2034 continue;
2035 len -= p - packet;
2036 packet = p;
2038 double endpts_s = MP_NOPTS_VALUE;
2039 if (subpts_s != MP_NOPTS_VALUE && duration >= 0)
2040 endpts_s = subpts_s + duration;
2041 sub_add_text(&subs, packet, len, endpts_s);
2042 set_osd_subtitle(mpctx, &subs);
2044 if (d_sub->non_interleaved)
2045 ds_get_next_pts(d_sub);
2047 if (!opts->ass_enabled)
2048 if (sub_clear_text(&subs, curpts_s))
2049 set_osd_subtitle(mpctx, &subs);
2051 if (vo_spudec) {
2052 spudec_heartbeat(vo_spudec, 90000 * curpts_s);
2053 if (spudec_changed(vo_spudec))
2054 vo_osd_changed(OSDTYPE_SPU);
2057 current_module = NULL;
2060 static void update_teletext(sh_video_t *sh_video, demuxer_t *demuxer, int reset)
2062 int page_changed;
2064 if (!demuxer->teletext)
2065 return;
2067 //Also forcing page update when such ioctl is not supported or call error occured
2068 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_IS_CHANGED,
2069 &page_changed) != VBI_CONTROL_TRUE)
2070 page_changed = 1;
2072 if (!page_changed)
2073 return;
2075 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_VBIPAGE,
2076 &vo_osd_teletext_page) != VBI_CONTROL_TRUE)
2077 vo_osd_teletext_page = NULL;
2078 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_HALF_PAGE,
2079 &vo_osd_teletext_half) != VBI_CONTROL_TRUE)
2080 vo_osd_teletext_half = 0;
2081 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_MODE,
2082 &vo_osd_teletext_mode) != VBI_CONTROL_TRUE)
2083 vo_osd_teletext_mode = 0;
2084 if (teletext_control(demuxer->teletext, TV_VBI_CONTROL_GET_FORMAT,
2085 &vo_osd_teletext_format) != VBI_CONTROL_TRUE)
2086 vo_osd_teletext_format = 0;
2087 vo_osd_changed(OSDTYPE_TELETEXT);
2089 teletext_control(demuxer->teletext, TV_VBI_CONTROL_MARK_UNCHANGED, NULL);
2092 static int check_framedrop(struct MPContext *mpctx, double frame_time)
2094 struct MPOpts *opts = &mpctx->opts;
2095 // check for frame-drop:
2096 current_module = "check_framedrop";
2097 if (mpctx->sh_audio && !mpctx->ao->untimed && !mpctx->d_audio->eof) {
2098 static int dropped_frames;
2099 float delay = opts->playback_speed * ao_get_delay(mpctx->ao);
2100 float d = delay - mpctx->delay;
2101 ++total_frame_cnt;
2102 // we should avoid dropping too many frames in sequence unless we
2103 // are too late. and we allow 100ms A-V delay here:
2104 if (d < -dropped_frames * frame_time - 0.100 && !mpctx->paused
2105 && !mpctx->restart_playback) {
2106 ++drop_frame_cnt;
2107 ++dropped_frames;
2108 return frame_dropping;
2109 } else
2110 dropped_frames = 0;
2112 return 0;
2116 #ifdef HAVE_RTC
2117 int rtc_fd = -1;
2118 #endif
2120 static float timing_sleep(struct MPContext *mpctx, float time_frame)
2122 #ifdef HAVE_RTC
2123 if (rtc_fd >= 0) {
2124 // -------- RTC -----------
2125 current_module = "sleep_rtc";
2126 while (time_frame > 0.000) {
2127 unsigned long rtc_ts;
2128 if (read(rtc_fd, &rtc_ts, sizeof(rtc_ts)) <= 0)
2129 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
2130 "Linux RTC read error: %s\n", strerror(errno));
2131 time_frame -= get_relative_time(mpctx);
2133 } else
2134 #endif
2136 // assume kernel HZ=100 for softsleep, works with larger HZ but with
2137 // unnecessarily high CPU usage
2138 struct MPOpts *opts = &mpctx->opts;
2139 float margin = opts->softsleep ? 0.011 : 0;
2140 current_module = "sleep_timer";
2141 while (time_frame > margin) {
2142 usec_sleep(1000000 * (time_frame - margin));
2143 time_frame -= get_relative_time(mpctx);
2145 if (opts->softsleep) {
2146 current_module = "sleep_soft";
2147 if (time_frame < 0)
2148 mp_tmsg(MSGT_AVSYNC, MSGL_WARN,
2149 "Warning! Softsleep underflow!\n");
2150 while (time_frame > 0)
2151 time_frame -= get_relative_time(mpctx); // burn the CPU
2154 return time_frame;
2157 static int select_subtitle(MPContext *mpctx)
2159 struct MPOpts *opts = &mpctx->opts;
2160 // find the best sub to use
2161 int id;
2162 int found = 0;
2163 mpctx->global_sub_pos = -1; // no subs by default
2164 if (vobsub_id >= 0) {
2165 // if user asks for a vobsub id, use that first.
2166 id = vobsub_id;
2167 found = mp_property_do("sub_vob", M_PROPERTY_SET, &id, mpctx) ==
2168 M_PROPERTY_OK;
2171 if (!found && opts->sub_id >= 0) {
2172 // if user asks for a dvd sub id, use that next.
2173 id = opts->sub_id;
2174 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) ==
2175 M_PROPERTY_OK;
2178 if (!found) {
2179 // if there are text subs to use, use those. (autosubs come last here)
2180 id = 0;
2181 found = mp_property_do("sub_file", M_PROPERTY_SET, &id, mpctx) ==
2182 M_PROPERTY_OK;
2185 if (!found && opts->sub_id == -1) {
2186 // finally select subs by language and container hints
2187 if (opts->sub_id == -1)
2188 opts->sub_id =
2189 demuxer_sub_track_by_lang_and_default(mpctx->d_sub->demuxer,
2190 opts->sub_lang);
2191 if (opts->sub_id >= 0) {
2192 id = opts->sub_id;
2193 found = mp_property_do("sub_demux", M_PROPERTY_SET, &id, mpctx) ==
2194 M_PROPERTY_OK;
2197 return found;
2200 #ifdef CONFIG_DVDNAV
2201 #ifndef FF_B_TYPE
2202 #define FF_B_TYPE 3
2203 #endif
2204 /// store decoded video image
2205 static mp_image_t *mp_dvdnav_copy_mpi(mp_image_t *to_mpi,
2206 mp_image_t *from_mpi)
2208 mp_image_t *mpi;
2210 /// Do not store B-frames
2211 if (from_mpi->pict_type == FF_B_TYPE)
2212 return to_mpi;
2214 if (to_mpi &&
2215 to_mpi->w == from_mpi->w &&
2216 to_mpi->h == from_mpi->h &&
2217 to_mpi->imgfmt == from_mpi->imgfmt)
2218 mpi = to_mpi;
2219 else {
2220 if (to_mpi)
2221 free_mp_image(to_mpi);
2222 if (from_mpi->w == 0 || from_mpi->h == 0)
2223 return NULL;
2224 mpi = alloc_mpi(from_mpi->w, from_mpi->h, from_mpi->imgfmt);
2227 copy_mpi(mpi, from_mpi);
2228 return mpi;
2231 static void mp_dvdnav_reset_stream(MPContext *ctx)
2233 struct MPOpts *opts = &ctx->opts;
2234 if (ctx->sh_video) {
2235 /// clear video pts
2236 ctx->d_video->pts = 0.0f;
2237 ctx->sh_video->pts = 0.0f;
2238 ctx->sh_video->i_pts = 0.0f;
2239 ctx->sh_video->last_pts = 0.0f;
2240 ctx->sh_video->num_buffered_pts = 0;
2241 ctx->sh_video->num_frames = 0;
2242 ctx->sh_video->num_frames_decoded = 0;
2243 ctx->sh_video->timer = 0.0f;
2244 ctx->sh_video->stream_delay = 0.0f;
2245 ctx->sh_video->timer = 0;
2246 ctx->demuxer->stream_pts = MP_NOPTS_VALUE;
2249 if (ctx->sh_audio) {
2250 /// free audio packets and reset
2251 ds_free_packs(ctx->d_audio);
2252 audio_delay -= ctx->sh_audio->stream_delay;
2253 ctx->delay = -audio_delay;
2254 ao_reset(ctx->ao);
2255 resync_audio_stream(ctx->sh_audio);
2258 audio_delay = 0.0f;
2259 ctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(ctx->stream);
2260 if (opts->sub_lang && opts->sub_id == dvdsub_lang_id) {
2261 dvdsub_lang_id = mp_dvdnav_sid_from_lang(ctx->stream, opts->sub_lang);
2262 if (dvdsub_lang_id != opts->sub_id) {
2263 opts->sub_id = dvdsub_lang_id;
2264 select_subtitle(ctx);
2268 /// clear all EOF related flags
2269 ctx->d_video->eof = ctx->d_audio->eof = ctx->stream->eof = 0;
2272 /// Restore last decoded DVDNAV (still frame)
2273 static mp_image_t *mp_dvdnav_restore_smpi(struct MPContext *mpctx,
2274 int *in_size,
2275 unsigned char **start,
2276 mp_image_t *decoded_frame)
2278 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2279 return decoded_frame;
2281 /// a change occurred in dvdnav stream
2282 if (mp_dvdnav_cell_has_changed(mpctx->stream, 0)) {
2283 mp_dvdnav_read_wait(mpctx->stream, 1, 1);
2284 mp_dvdnav_context_free(mpctx);
2285 mp_dvdnav_reset_stream(mpctx);
2286 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
2287 mp_dvdnav_cell_has_changed(mpctx->stream, 1);
2290 if (*in_size < 0) {
2291 float len;
2293 /// Display still frame, if any
2294 if (mpctx->nav_smpi && !mpctx->nav_buffer)
2295 decoded_frame = mpctx->nav_smpi;
2297 /// increment video frame : continue playing after still frame
2298 len = get_time_length(mpctx);
2299 if (mpctx->sh_video->pts >= len &&
2300 mpctx->sh_video->pts > 0.0 && len > 0.0) {
2301 mp_dvdnav_skip_still(mpctx->stream);
2302 mp_dvdnav_skip_wait(mpctx->stream);
2304 mpctx->sh_video->pts += 1 / mpctx->sh_video->fps;
2306 if (mpctx->nav_buffer) {
2307 *start = mpctx->nav_start;
2308 *in_size = mpctx->nav_in_size;
2309 if (mpctx->nav_start)
2310 memcpy(*start, mpctx->nav_buffer, mpctx->nav_in_size);
2314 return decoded_frame;
2317 /// Save last decoded DVDNAV (still frame)
2318 static void mp_dvdnav_save_smpi(struct MPContext *mpctx, int in_size,
2319 unsigned char *start,
2320 mp_image_t *decoded_frame)
2322 if (mpctx->stream->type != STREAMTYPE_DVDNAV)
2323 return;
2325 free(mpctx->nav_buffer);
2326 mpctx->nav_buffer = NULL;
2327 mpctx->nav_start = NULL;
2328 mpctx->nav_in_size = -1;
2330 if (in_size > 0)
2331 mpctx->nav_buffer = malloc(in_size);
2332 if (mpctx->nav_buffer) {
2333 mpctx->nav_start = start;
2334 mpctx->nav_in_size = in_size;
2335 memcpy(mpctx->nav_buffer, start, in_size);
2338 if (decoded_frame && mpctx->nav_smpi != decoded_frame)
2339 mpctx->nav_smpi = mp_dvdnav_copy_mpi(mpctx->nav_smpi, decoded_frame);
2341 #endif /* CONFIG_DVDNAV */
2343 /* Modify video timing to match the audio timeline. There are two main
2344 * reasons this is needed. First, video and audio can start from different
2345 * positions at beginning of file or after a seek (MPlayer starts both
2346 * immediately even if they have different pts). Second, the file can have
2347 * audio timestamps that are inconsistent with the duration of the audio
2348 * packets, for example two consecutive timestamp values differing by
2349 * one second but only a packet with enough samples for half a second
2350 * of playback between them.
2352 static void adjust_sync(struct MPContext *mpctx, double frame_time)
2354 current_module = "av_sync";
2356 if (!mpctx->sh_audio || mpctx->syncing_audio)
2357 return;
2359 double a_pts = written_audio_pts(mpctx) - mpctx->delay;
2360 double v_pts = mpctx->sh_video->pts;
2361 double av_delay = a_pts - v_pts;
2362 // Try to sync vo_flip() so it will *finish* at given time
2363 av_delay += mpctx->last_vo_flip_duration;
2364 av_delay -= audio_delay; // This much pts difference is desired
2366 double change = av_delay * 0.1;
2367 double max_change = default_max_pts_correction >= 0 ?
2368 default_max_pts_correction : frame_time * 0.1;
2369 if (change < -max_change)
2370 change = -max_change;
2371 else if (change > max_change)
2372 change = max_change;
2373 mpctx->delay += change;
2374 mpctx->total_avsync_change += change;
2377 static int write_to_ao(struct MPContext *mpctx, void *data, int len, int flags,
2378 double pts)
2380 if (mpctx->paused)
2381 return 0;
2382 struct ao *ao = mpctx->ao;
2383 double bps = ao->bps / mpctx->opts.playback_speed;
2384 ao->pts = pts;
2385 // hack used by some mpeg-writing AOs
2386 ao->brokenpts = ((mpctx->sh_video ? mpctx->sh_video->timer : 0) +
2387 mpctx->delay) * 90000.0;
2388 int played = ao_play(mpctx->ao, data, len, flags);
2389 if (played > 0) {
2390 mpctx->delay += played / bps;
2391 // Keep correct pts for remaining data - could be used to flush
2392 // remaining buffer when closing ao.
2393 ao->pts += played / bps;
2395 return played;
2398 #define ASYNC_PLAY_DONE -3
2399 static int audio_start_sync(struct MPContext *mpctx, int playsize)
2401 struct ao *ao = mpctx->ao;
2402 struct MPOpts *opts = &mpctx->opts;
2403 sh_audio_t * const sh_audio = mpctx->sh_audio;
2404 int res;
2406 // Timing info may not be set without
2407 res = decode_audio(sh_audio, &ao->buffer, 1);
2408 if (res < 0)
2409 return res;
2411 int bytes;
2412 bool did_retry = false;
2413 double written_pts;
2414 double bps = ao->bps / opts->playback_speed;
2415 bool hrseek = mpctx->hrseek_active; // audio only hrseek
2416 mpctx->hrseek_active = false;
2417 while (1) {
2418 written_pts = written_audio_pts(mpctx);
2419 double ptsdiff;
2420 if (hrseek)
2421 ptsdiff = written_pts - mpctx->hrseek_pts;
2422 else
2423 ptsdiff = written_pts - mpctx->sh_video->pts - mpctx->delay
2424 - audio_delay;
2425 bytes = ptsdiff * bps;
2426 bytes -= bytes % (ao->channels * af_fmt2bits(ao->format) / 8);
2428 // ogg demuxers give packets without timing
2429 if (written_pts <= 1 && sh_audio->pts == MP_NOPTS_VALUE) {
2430 if (!did_retry) {
2431 // Try to read more data to see packets that have pts
2432 int res = decode_audio(sh_audio, &ao->buffer, ao->bps);
2433 if (res < 0)
2434 return res;
2435 did_retry = true;
2436 continue;
2438 bytes = 0;
2441 if (fabs(ptsdiff) > 300) // pts reset or just broken?
2442 bytes = 0;
2444 if (bytes > 0)
2445 break;
2447 mpctx->syncing_audio = false;
2448 int a = FFMIN(-bytes, FFMAX(playsize, 20000));
2449 int res = decode_audio(sh_audio, &ao->buffer, a);
2450 bytes += ao->buffer.len;
2451 if (bytes >= 0) {
2452 memmove(ao->buffer.start,
2453 ao->buffer.start + ao->buffer.len - bytes, bytes);
2454 ao->buffer.len = bytes;
2455 if (res < 0)
2456 return res;
2457 return decode_audio(sh_audio, &ao->buffer, playsize);
2459 ao->buffer.len = 0;
2460 if (res < 0)
2461 return res;
2463 if (hrseek)
2464 // Don't add silence in audio-only case even if position is too late
2465 return 0;
2466 int fillbyte = 0;
2467 if ((ao->format & AF_FORMAT_SIGN_MASK) == AF_FORMAT_US)
2468 fillbyte = 0x80;
2469 if (bytes >= playsize) {
2470 /* This case could fall back to the one below with
2471 * bytes = playsize, but then silence would keep accumulating
2472 * in a_out_buffer if the AO accepts less data than it asks for
2473 * in playsize. */
2474 char *p = malloc(playsize);
2475 memset(p, fillbyte, playsize);
2476 write_to_ao(mpctx, p, playsize, 0, written_pts - bytes / bps);
2477 free(p);
2478 return ASYNC_PLAY_DONE;
2480 mpctx->syncing_audio = false;
2481 decode_audio_prepend_bytes(&ao->buffer, bytes, fillbyte);
2482 return decode_audio(sh_audio, &ao->buffer, playsize);
2485 static int fill_audio_out_buffers(struct MPContext *mpctx, double endpts)
2487 struct MPOpts *opts = &mpctx->opts;
2488 struct ao *ao = mpctx->ao;
2489 unsigned int t;
2490 double tt;
2491 int playsize;
2492 int playflags = 0;
2493 bool audio_eof = false;
2494 bool partial_fill = false;
2495 sh_audio_t * const sh_audio = mpctx->sh_audio;
2496 bool modifiable_audio_format = !(ao->format & AF_FORMAT_SPECIAL_MASK);
2497 int unitsize = ao->channels * af_fmt2bits(ao->format) / 8;
2499 current_module = "play_audio";
2501 // hack used by some mpeg-writing AOs
2502 ao->brokenpts = ((mpctx->sh_video ? mpctx->sh_video->timer : 0) +
2503 mpctx->delay) * 90000.0;
2505 if (mpctx->paused)
2506 playsize = 1; // just initialize things (audio pts at least)
2507 else
2508 playsize = ao_get_space(ao);
2510 // Fill buffer if needed:
2511 current_module = "decode_audio";
2512 t = GetTimer();
2514 // Coming here with hrseek_active still set means audio-only
2515 if (!mpctx->sh_video)
2516 mpctx->syncing_audio = false;
2517 if (!opts->initial_audio_sync || !modifiable_audio_format) {
2518 mpctx->syncing_audio = false;
2519 mpctx->hrseek_active = false;
2522 int res;
2523 if (mpctx->syncing_audio || mpctx->hrseek_active)
2524 res = audio_start_sync(mpctx, playsize);
2525 else
2526 res = decode_audio(sh_audio, &ao->buffer, playsize);
2527 if (res < 0) { // EOF, error or format change
2528 if (res == -2) {
2529 /* The format change isn't handled too gracefully. A more precise
2530 * implementation would require draining buffered old-format audio
2531 * while displaying video, then doing the output format switch.
2533 uninit_player(mpctx, INITIALIZED_AO);
2534 reinit_audio_chain(mpctx);
2535 return -1;
2536 } else if (res == ASYNC_PLAY_DONE)
2537 return 0;
2538 else if (mpctx->d_audio->eof)
2539 audio_eof = true;
2541 t = GetTimer() - t;
2542 tt = t * 0.000001f;
2543 audio_time_usage += tt;
2544 if (endpts != MP_NOPTS_VALUE && modifiable_audio_format) {
2545 double bytes = (endpts - written_audio_pts(mpctx) + audio_delay)
2546 * ao->bps / opts->playback_speed;
2547 if (playsize > bytes) {
2548 playsize = FFMAX(bytes, 0);
2549 playflags |= AOPLAY_FINAL_CHUNK;
2550 audio_eof = true;
2551 partial_fill = true;
2555 assert(ao->buffer.len % unitsize == 0);
2556 if (playsize > ao->buffer.len) {
2557 partial_fill = true;
2558 playsize = ao->buffer.len;
2559 if (audio_eof)
2560 playflags |= AOPLAY_FINAL_CHUNK;
2562 playsize -= playsize % unitsize;
2563 if (!playsize)
2564 return partial_fill && audio_eof ? -2 : -partial_fill;
2566 // play audio:
2567 current_module = "play_audio";
2569 int played = write_to_ao(mpctx, ao->buffer.start, playsize, playflags,
2570 written_audio_pts(mpctx));
2571 assert(played % unitsize == 0);
2572 ao->buffer_playable_size = playsize - played;
2574 if (played > 0) {
2575 ao->buffer.len -= played;
2576 memmove(ao->buffer.start, ao->buffer.start + played, ao->buffer.len);
2577 } else if (!mpctx->paused && audio_eof && ao_get_delay(ao) < .04) {
2578 // Sanity check to avoid hanging in case current ao doesn't output
2579 // partial chunks and doesn't check for AOPLAY_FINAL_CHUNK
2580 return -2;
2583 return -partial_fill;
2586 int reinit_video_chain(struct MPContext *mpctx)
2588 struct MPOpts *opts = &mpctx->opts;
2589 sh_video_t * const sh_video = mpctx->sh_video;
2590 if (!sh_video) {
2591 uninit_player(mpctx, INITIALIZED_VO);
2592 return 0;
2594 double ar = -1.0;
2595 //================== Init VIDEO (codec & libvo) ==========================
2596 if (!opts->fixed_vo || !(mpctx->initialized_flags & INITIALIZED_VO)) {
2597 current_module = "preinit_libvo";
2599 //shouldn't we set dvideo->id=-2 when we fail?
2600 //if((mpctx->video_out->preinit(vo_subdevice))!=0){
2601 if (!(mpctx->video_out = init_best_video_out(opts, mpctx->key_fifo,
2602 mpctx->input))) {
2603 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "Error opening/initializing "
2604 "the selected video_out (-vo) device.\n");
2605 goto err_out;
2607 mpctx->initialized_flags |= INITIALIZED_VO;
2610 if (stream_control(mpctx->demuxer->stream, STREAM_CTRL_GET_ASPECT_RATIO,
2611 &ar) != STREAM_UNSUPPORTED)
2612 mpctx->sh_video->stream_aspect = ar;
2613 current_module = "init_video_filters";
2615 char *vf_arg[] = {
2616 "_oldargs_", (char *)mpctx->video_out, NULL
2618 sh_video->vfilter = vf_open_filter(opts, NULL, "vo", vf_arg);
2621 #ifdef CONFIG_ASS
2622 if (opts->ass_enabled) {
2623 int i;
2624 int insert = 1;
2625 if (opts->vf_settings)
2626 for (i = 0; opts->vf_settings[i].name; ++i)
2627 if (strcmp(opts->vf_settings[i].name, "ass") == 0) {
2628 insert = 0;
2629 break;
2631 if (insert) {
2632 extern vf_info_t vf_info_ass;
2633 const vf_info_t *libass_vfs[] = {
2634 &vf_info_ass, NULL
2636 char *vf_arg[] = {
2637 "auto", "1", NULL
2639 int retcode = 0;
2640 struct vf_instance *vf_ass = vf_open_plugin_noerr(opts, libass_vfs,
2641 sh_video->vfilter,
2642 "ass", vf_arg,
2643 &retcode);
2644 if (vf_ass)
2645 sh_video->vfilter = vf_ass;
2646 else if (retcode == -1) // vf_ass open() returns -1 VO has EOSD
2647 mp_msg(MSGT_CPLAYER, MSGL_V, "[ass] vf_ass not needed\n");
2648 else
2649 mp_msg(MSGT_CPLAYER, MSGL_ERR,
2650 "ASS: cannot add video filter\n");
2653 #endif
2655 sh_video->vfilter = append_filters(sh_video->vfilter, opts->vf_settings);
2657 if (opts->ass_enabled)
2658 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_INIT_EOSD,
2659 mpctx->ass_library);
2661 current_module = "init_video_codec";
2663 init_best_video_codec(sh_video, video_codec_list, video_fm_list);
2665 if (!sh_video->initialized) {
2666 if (!opts->fixed_vo)
2667 uninit_player(mpctx, INITIALIZED_VO);
2668 goto err_out;
2671 mpctx->initialized_flags |= INITIALIZED_VCODEC;
2673 if (sh_video->codec)
2674 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
2675 "ID_VIDEO_CODEC=%s\n", sh_video->codec->name);
2677 sh_video->last_pts = MP_NOPTS_VALUE;
2678 sh_video->num_buffered_pts = 0;
2679 sh_video->next_frame_time = 0;
2680 mpctx->restart_playback = true;
2681 mpctx->delay = 0;
2683 if (opts->auto_quality > 0) {
2684 // Auto quality option enabled
2685 output_quality = get_video_quality_max(sh_video);
2686 if (opts->auto_quality > output_quality)
2687 opts->auto_quality = output_quality;
2688 else
2689 output_quality = opts->auto_quality;
2690 mp_msg(MSGT_CPLAYER, MSGL_V,
2691 "AutoQ: setting quality to %d.\n", output_quality);
2692 set_video_quality(sh_video, output_quality);
2695 // ========== Init display (sh_video->disp_w*sh_video->disp_h/out_fmt) ============
2697 current_module = "init_vo";
2699 return 1;
2701 err_out:
2702 mpctx->sh_video = mpctx->d_video->sh = NULL;
2703 return 0;
2706 static double update_video_nocorrect_pts(struct MPContext *mpctx)
2708 struct sh_video *sh_video = mpctx->sh_video;
2709 double frame_time = 0;
2710 struct vo *video_out = mpctx->video_out;
2711 while (1) {
2712 current_module = "filter_video";
2713 // In nocorrect-pts mode there is no way to properly time these frames
2714 if (vo_get_buffered_frame(video_out, 0) >= 0)
2715 break;
2716 if (vf_output_queued_frame(sh_video->vfilter))
2717 break;
2718 unsigned char *packet = NULL;
2719 frame_time = sh_video->next_frame_time;
2720 if (mpctx->restart_playback)
2721 frame_time = 0;
2722 int in_size = 0;
2723 while (!in_size)
2724 in_size = video_read_frame(sh_video, &sh_video->next_frame_time,
2725 &packet, force_fps);
2726 if (in_size < 0) {
2727 #ifdef CONFIG_DVDNAV
2728 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
2729 if (mp_dvdnav_is_eof(mpctx->stream))
2730 return -1;
2731 if (mpctx->d_video)
2732 mpctx->d_video->eof = 0;
2733 if (mpctx->d_audio)
2734 mpctx->d_audio->eof = 0;
2735 mpctx->stream->eof = 0;
2736 } else
2737 #endif
2738 return -1;
2740 if (in_size > max_framesize)
2741 max_framesize = in_size;
2742 sh_video->timer += frame_time;
2743 if (mpctx->sh_audio)
2744 mpctx->delay -= frame_time;
2745 // video_read_frame can change fps (e.g. for ASF video)
2746 vo_fps = sh_video->fps;
2747 int framedrop_type = check_framedrop(mpctx, frame_time);
2748 current_module = "decode video";
2750 void *decoded_frame;
2751 #ifdef CONFIG_DVDNAV
2752 decoded_frame = mp_dvdnav_restore_smpi(mpctx, &in_size, &packet, NULL);
2753 if (in_size >= 0 && !decoded_frame)
2754 #endif
2755 decoded_frame = decode_video(sh_video, sh_video->ds->current, packet,
2756 in_size, framedrop_type, sh_video->pts);
2757 #ifdef CONFIG_DVDNAV
2758 // Save last still frame for future display
2759 mp_dvdnav_save_smpi(mpctx, in_size, packet, decoded_frame);
2760 #endif
2761 if (decoded_frame) {
2762 current_module = "filter video";
2763 filter_video(sh_video, decoded_frame, sh_video->pts);
2765 break;
2767 return frame_time;
2770 static void determine_frame_pts(struct MPContext *mpctx)
2772 struct sh_video *sh_video = mpctx->sh_video;
2773 struct MPOpts *opts = &mpctx->opts;
2775 if (opts->user_pts_assoc_mode)
2776 sh_video->pts_assoc_mode = opts->user_pts_assoc_mode;
2777 else if (sh_video->pts_assoc_mode == 0) {
2778 if (mpctx->d_video->demuxer->timestamp_type == TIMESTAMP_TYPE_PTS
2779 && sh_video->codec_reordered_pts != MP_NOPTS_VALUE)
2780 sh_video->pts_assoc_mode = 1;
2781 else
2782 sh_video->pts_assoc_mode = 2;
2783 } else {
2784 int probcount1 = sh_video->num_reordered_pts_problems;
2785 int probcount2 = sh_video->num_sorted_pts_problems;
2786 if (sh_video->pts_assoc_mode == 2) {
2787 int tmp = probcount1;
2788 probcount1 = probcount2;
2789 probcount2 = tmp;
2791 if (probcount1 >= probcount2 * 1.5 + 2) {
2792 sh_video->pts_assoc_mode = 3 - sh_video->pts_assoc_mode;
2793 mp_msg(MSGT_CPLAYER, MSGL_V, "Switching to pts association mode "
2794 "%d.\n", sh_video->pts_assoc_mode);
2797 sh_video->pts = sh_video->pts_assoc_mode == 1 ?
2798 sh_video->codec_reordered_pts : sh_video->sorted_pts;
2801 static double update_video(struct MPContext *mpctx)
2803 struct sh_video *sh_video = mpctx->sh_video;
2804 struct vo *video_out = mpctx->video_out;
2805 sh_video->vfilter->control(sh_video->vfilter, VFCTRL_SET_OSD_OBJ,
2806 mpctx->osd); // hack for vf_expand
2807 if (!mpctx->opts.correct_pts)
2808 return update_video_nocorrect_pts(mpctx);
2810 double pts;
2812 while (1) {
2813 current_module = "filter_video";
2814 if (vo_get_buffered_frame(video_out, false) >= 0)
2815 break;
2816 // XXX Time used in this call is not counted in any performance
2817 // timer now
2818 if (vf_output_queued_frame(sh_video->vfilter))
2819 break;
2820 int in_size = 0;
2821 unsigned char *buf = NULL;
2822 pts = MP_NOPTS_VALUE;
2823 struct demux_packet *pkt;
2824 while (1) {
2825 pkt = ds_get_packet2(mpctx->d_video, false);
2826 if (!pkt || pkt->len)
2827 break;
2828 /* Packets with size 0 are assumed to not correspond to frames,
2829 * but to indicate the absence of a frame in formats like AVI
2830 * that must have packets at fixed timecode intervals. */
2832 if (pkt) {
2833 in_size = pkt->len;
2834 buf = pkt->buffer;
2835 pts = pkt->pts;
2837 if (pts != MP_NOPTS_VALUE)
2838 pts += mpctx->video_offset;
2839 if (in_size > max_framesize)
2840 max_framesize = in_size;
2841 current_module = "decode video";
2842 if (pts >= mpctx->hrseek_pts - .005)
2843 mpctx->hrseek_framedrop = false;
2844 int framedrop_type = mpctx->hrseek_framedrop ? 1 :
2845 check_framedrop(mpctx, sh_video->frametime);
2846 void *decoded_frame = decode_video(sh_video, pkt, buf, in_size,
2847 framedrop_type, pts);
2848 if (decoded_frame) {
2849 determine_frame_pts(mpctx);
2850 current_module = "filter video";
2851 filter_video(sh_video, decoded_frame, sh_video->pts);
2852 } else if (!pkt) {
2853 if (vo_get_buffered_frame(video_out, true) < 0)
2854 return -1;
2856 break;
2859 if (!video_out->frame_loaded)
2860 return 0;
2862 pts = video_out->next_pts;
2863 if (pts == MP_NOPTS_VALUE) {
2864 mp_msg(MSGT_CPLAYER, MSGL_ERR, "Video pts after filters MISSING\n");
2865 // Try to use decoder pts from before filters
2866 pts = sh_video->pts;
2867 if (pts == MP_NOPTS_VALUE)
2868 pts = sh_video->last_pts;
2870 if (mpctx->hrseek_active && pts < mpctx->hrseek_pts - .005) {
2871 vo_skip_frame(video_out);
2872 return 0;
2874 mpctx->hrseek_active = false;
2875 sh_video->pts = pts;
2876 if (sh_video->last_pts == MP_NOPTS_VALUE)
2877 sh_video->last_pts = sh_video->pts;
2878 else if (sh_video->last_pts > sh_video->pts) {
2879 mp_msg(MSGT_CPLAYER, MSGL_INFO, "Decreasing video pts: %f < %f\n",
2880 sh_video->pts, sh_video->last_pts);
2881 /* If the difference in pts is small treat it as jitter around the
2882 * right value (possibly caused by incorrect timestamp ordering) and
2883 * just show this frame immediately after the last one.
2884 * Treat bigger differences as timestamp resets and start counting
2885 * timing of later frames from the position of this one. */
2886 if (sh_video->last_pts - sh_video->pts > 0.5)
2887 sh_video->last_pts = sh_video->pts;
2888 else
2889 sh_video->pts = sh_video->last_pts;
2891 double frame_time = sh_video->pts - sh_video->last_pts;
2892 sh_video->last_pts = sh_video->pts;
2893 sh_video->timer += frame_time;
2894 if (mpctx->sh_audio)
2895 mpctx->delay -= frame_time;
2896 return frame_time;
2899 static int get_cache_fill(struct MPContext *mpctx)
2901 #ifdef CONFIG_STREAM_CACHE
2902 if (mpctx->stream && mpctx->stream->cached)
2903 return cache_fill_status(mpctx->stream);
2904 #endif
2905 return -1;
2908 static void update_pause_message(struct MPContext *mpctx)
2910 struct MPOpts *opts = &mpctx->opts;
2912 if (opts->quiet)
2913 return;
2915 int cache_fill = get_cache_fill(mpctx);
2916 bool cache_changed = cache_fill != mpctx->paused_cache_fill;
2918 if (!mpctx->status_printed && !cache_changed)
2919 return;
2921 char *msg = mp_gtext(" ===== PAUSE =====");
2922 char *tmpmem = NULL;
2923 if (cache_fill >= 0)
2924 msg = tmpmem = talloc_asprintf(NULL, "%s %d%%", msg, cache_fill);
2926 if (opts->term_osd && !mpctx->sh_video) {
2927 set_osd_msg(OSD_MSG_PAUSE, 1, 0, "%s", msg);
2928 update_osd_msg(mpctx);
2929 } else {
2930 if (mpctx->status_printed)
2931 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "\n");
2932 mp_msg(MSGT_STATUSLINE, MSGL_STATUS, "%s\r", msg);
2935 mpctx->paused_cache_fill = cache_fill;
2936 mpctx->status_printed = false;
2938 talloc_free(tmpmem);
2941 void pause_player(struct MPContext *mpctx)
2943 if (mpctx->paused)
2944 return;
2945 mpctx->paused = 1;
2946 mpctx->step_frames = 0;
2947 mpctx->time_frame -= get_relative_time(mpctx);
2948 mpctx->osd_function = OSD_PAUSE;
2950 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
2951 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
2953 if (mpctx->ao && mpctx->sh_audio)
2954 ao_pause(mpctx->ao); // pause audio, keep data if possible
2956 mpctx->paused_cache_fill = get_cache_fill(mpctx);
2957 mpctx->status_printed = true;
2958 update_pause_message(mpctx);
2960 if (!mpctx->opts.quiet)
2961 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_PAUSED\n");
2964 void unpause_player(struct MPContext *mpctx)
2966 if (!mpctx->paused)
2967 return;
2968 mpctx->paused = 0;
2969 if (!mpctx->step_frames)
2970 mpctx->osd_function = OSD_PLAY;
2972 if (mpctx->ao && mpctx->sh_audio)
2973 ao_resume(mpctx->ao);
2974 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok
2975 && !mpctx->step_frames)
2976 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL); // resume video
2977 (void)get_relative_time(mpctx); // ignore time that passed during pause
2980 static int redraw_osd(struct MPContext *mpctx)
2982 struct MPOpts *opts = &mpctx->opts;
2983 struct sh_video *sh_video = mpctx->sh_video;
2984 struct vf_instance *vf = sh_video->vfilter;
2985 if (sh_video->output_flags & VFCAP_OSD_FILTER)
2986 return -1;
2987 if (vo_redraw_frame(mpctx->video_out) < 0)
2988 return -1;
2989 mpctx->osd->sub_pts = mpctx->video_pts;
2990 if (mpctx->osd->sub_pts != MP_NOPTS_VALUE)
2991 mpctx->osd->sub_pts += opts->sub_delay - mpctx->osd->sub_offset;
2993 if (!(sh_video->output_flags & VFCAP_EOSD_FILTER))
2994 vf->control(vf, VFCTRL_DRAW_EOSD, mpctx->osd);
2995 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
2996 vo_flip_page(mpctx->video_out, 0, -1);
2997 return 0;
3000 void add_step_frame(struct MPContext *mpctx)
3002 mpctx->step_frames++;
3003 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
3004 vo_control(mpctx->video_out, VOCTRL_PAUSE, NULL);
3005 unpause_player(mpctx);
3008 static void seek_reset(struct MPContext *mpctx, bool reset_ao, bool reset_ac)
3010 if (mpctx->sh_video) {
3011 current_module = "seek_video_reset";
3012 resync_video_stream(mpctx->sh_video);
3013 mpctx->sh_video->timer = 0;
3014 vo_seek_reset(mpctx->video_out);
3015 mpctx->sh_video->timer = 0;
3016 mpctx->sh_video->num_buffered_pts = 0;
3017 mpctx->sh_video->last_pts = MP_NOPTS_VALUE;
3018 mpctx->delay = 0;
3019 mpctx->time_frame = 0;
3020 // Not all demuxers set d_video->pts during seek, so this value
3021 // (which is used by at least vobsub code below) may be completely
3022 // wrong (probably 0).
3023 mpctx->sh_video->pts = mpctx->d_video->pts + mpctx->video_offset;
3024 mpctx->video_pts = mpctx->sh_video->pts;
3025 update_subtitles(mpctx, mpctx->sh_video->pts, true);
3026 update_teletext(mpctx->sh_video, mpctx->demuxer, 1);
3029 if (mpctx->sh_audio && reset_ac) {
3030 current_module = "seek_audio_reset";
3031 resync_audio_stream(mpctx->sh_audio);
3032 if (reset_ao)
3033 ao_reset(mpctx->ao);
3034 mpctx->ao->buffer.len = mpctx->ao->buffer_playable_size;
3035 mpctx->sh_audio->a_buffer_len = 0;
3036 if (!mpctx->sh_video)
3037 update_subtitles(mpctx, mpctx->sh_audio->pts, true);
3040 if (vo_vobsub && mpctx->sh_video) {
3041 current_module = "seek_vobsub_reset";
3042 vobsub_seek(vo_vobsub, mpctx->sh_video->pts);
3045 mpctx->restart_playback = true;
3046 mpctx->hrseek_active = false;
3047 mpctx->hrseek_framedrop = false;
3048 mpctx->total_avsync_change = 0;
3049 audio_time_usage = 0;
3050 video_time_usage = 0;
3051 vout_time_usage = 0;
3052 drop_frame_cnt = 0;
3054 current_module = NULL;
3057 static bool timeline_set_part(struct MPContext *mpctx, int i)
3059 struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
3060 struct timeline_part *n = mpctx->timeline + i;
3061 mpctx->timeline_part = i;
3062 mpctx->video_offset = n->start - n->source_start;
3063 if (n->source == p->source)
3064 return false;
3065 enum stop_play_reason orig_stop_play = mpctx->stop_play;
3066 if (!mpctx->sh_video && mpctx->stop_play == KEEP_PLAYING)
3067 mpctx->stop_play = AT_END_OF_FILE; // let audio uninit drain data
3068 uninit_player(mpctx, INITIALIZED_VCODEC | (mpctx->opts.fixed_vo ? 0 : INITIALIZED_VO) | (mpctx->opts.gapless_audio ? 0 : INITIALIZED_AO) | INITIALIZED_ACODEC | INITIALIZED_SUB);
3069 mpctx->stop_play = orig_stop_play;
3070 mpctx->demuxer = n->source->demuxer;
3071 mpctx->d_video = mpctx->demuxer->video;
3072 mpctx->d_audio = mpctx->demuxer->audio;
3073 mpctx->d_sub = mpctx->demuxer->sub;
3074 mpctx->sh_video = mpctx->d_video->sh;
3075 mpctx->sh_audio = mpctx->d_audio->sh;
3076 return true;
3079 // Given pts, switch playback to the corresponding part.
3080 // Return offset within that part.
3081 static double timeline_set_from_time(struct MPContext *mpctx, double pts,
3082 bool *need_reset)
3084 if (pts < 0)
3085 pts = 0;
3086 for (int i = 0; i < mpctx->num_timeline_parts; i++) {
3087 struct timeline_part *p = mpctx->timeline + i;
3088 if (pts < (p + 1)->start) {
3089 *need_reset = timeline_set_part(mpctx, i);
3090 return pts - p->start + p->source_start;
3093 return -1;
3097 // return -1 if seek failed (non-seekable stream?), 0 otherwise
3098 static int seek(MPContext *mpctx, struct seek_params seek,
3099 bool timeline_fallthrough)
3101 struct MPOpts *opts = &mpctx->opts;
3103 current_module = "seek";
3104 if (mpctx->stop_play == AT_END_OF_FILE)
3105 mpctx->stop_play = KEEP_PLAYING;
3106 bool hr_seek = mpctx->demuxer->accurate_seek && opts->correct_pts;
3107 hr_seek &= seek.exact >= 0 && seek.type != MPSEEK_FACTOR;
3108 hr_seek &= opts->hr_seek == 0 && seek.type == MPSEEK_ABSOLUTE
3109 || opts->hr_seek > 0 || seek.exact > 0;
3110 if (seek.type == MPSEEK_FACTOR
3111 || seek.type == MPSEEK_ABSOLUTE
3112 && seek.amount < mpctx->last_chapter_pts
3113 || seek.amount < 0)
3114 mpctx->last_chapter_seek = -2;
3115 if (mpctx->timeline && seek.type == MPSEEK_FACTOR) {
3116 seek.amount *= mpctx->timeline[mpctx->num_timeline_parts].start;
3117 seek.type = MPSEEK_ABSOLUTE;
3119 if ((mpctx->demuxer->accurate_seek || mpctx->timeline)
3120 && seek.type == MPSEEK_RELATIVE) {
3121 seek.type = MPSEEK_ABSOLUTE;
3122 seek.direction = seek.amount > 0 ? 1 : -1;
3123 seek.amount += get_current_time(mpctx);
3126 /* At least the liba52 decoder wants to read from the input stream
3127 * during initialization, so reinit must be done after the demux_seek()
3128 * call that clears possible stream EOF. */
3129 bool need_reset = false;
3130 double demuxer_amount = seek.amount;
3131 if (mpctx->timeline) {
3132 demuxer_amount = timeline_set_from_time(mpctx, seek.amount,
3133 &need_reset);
3134 if (demuxer_amount == -1) {
3135 mpctx->stop_play = AT_END_OF_FILE;
3136 // Clear audio from current position
3137 if (mpctx->sh_audio && !timeline_fallthrough) {
3138 ao_reset(mpctx->ao);
3139 mpctx->sh_audio->a_buffer_len = 0;
3141 return -1;
3144 if (need_reset) {
3145 reinit_video_chain(mpctx);
3146 mp_property_do("sub", M_PROPERTY_SET, &(int){mpctx->global_sub_pos},
3147 mpctx);
3150 int demuxer_style = 0;
3151 switch (seek.type) {
3152 case MPSEEK_FACTOR:
3153 demuxer_style |= SEEK_FACTOR; // fallthrough
3154 case MPSEEK_ABSOLUTE:
3155 demuxer_style |= SEEK_ABSOLUTE;
3157 if (hr_seek || seek.direction < 0)
3158 demuxer_style |= SEEK_BACKWARD;
3159 else if (seek.direction > 0)
3160 demuxer_style |= SEEK_FORWARD;
3162 if (hr_seek)
3163 demuxer_amount -= opts->hr_seek_demuxer_offset;
3164 int seekresult = demux_seek(mpctx->demuxer, demuxer_amount, audio_delay,
3165 demuxer_style);
3166 if (seekresult == 0) {
3167 if (need_reset) {
3168 reinit_audio_chain(mpctx);
3169 seek_reset(mpctx, !timeline_fallthrough, false);
3171 return -1;
3174 if (need_reset)
3175 reinit_audio_chain(mpctx);
3176 /* If we just reinitialized audio it doesn't need to be reset,
3177 * and resetting could lose audio some decoders produce during init. */
3178 seek_reset(mpctx, !timeline_fallthrough, !need_reset);
3180 /* Use the target time as "current position" for further relative
3181 * seeks etc until a new video frame has been decoded */
3182 if (seek.type == MPSEEK_ABSOLUTE) {
3183 mpctx->video_pts = seek.amount;
3184 mpctx->last_seek_pts = seek.amount;
3185 } else
3186 mpctx->last_seek_pts = MP_NOPTS_VALUE;
3188 if (hr_seek || mpctx->timeline) {
3189 mpctx->hrseek_active = true;
3190 mpctx->hrseek_framedrop = true;
3191 mpctx->hrseek_pts = hr_seek ? seek.amount
3192 : mpctx->timeline[mpctx->timeline_part].start;
3195 mpctx->start_timestamp = GetTimerMS();
3197 return 0;
3200 void queue_seek(struct MPContext *mpctx, enum seek_type type, double amount,
3201 int exact)
3203 struct seek_params *seek = &mpctx->seek;
3204 switch (type) {
3205 case MPSEEK_RELATIVE:
3206 if (seek->type == MPSEEK_FACTOR)
3207 return; // Well... not common enough to bother doing better
3208 seek->amount += amount;
3209 seek->exact = FFMAX(seek->exact, exact);
3210 if (seek->type == MPSEEK_NONE)
3211 seek->exact = exact;
3212 if (seek->type == MPSEEK_ABSOLUTE)
3213 return;
3214 if (seek->amount == 0) {
3215 *seek = (struct seek_params){ 0 };
3216 return;
3218 seek->type = MPSEEK_RELATIVE;
3219 return;
3220 case MPSEEK_ABSOLUTE:
3221 case MPSEEK_FACTOR:
3222 *seek = (struct seek_params) {
3223 .type = type,
3224 .amount = amount,
3225 .exact = exact,
3227 return;
3228 case MPSEEK_NONE:
3229 *seek = (struct seek_params){ 0 };
3230 return;
3232 abort();
3236 double get_time_length(struct MPContext *mpctx)
3238 if (mpctx->timeline)
3239 return mpctx->timeline[mpctx->num_timeline_parts].start;
3241 struct demuxer *demuxer = mpctx->demuxer;
3242 double get_time_ans;
3243 // <= 0 means DEMUXER_CTRL_NOTIMPL or DEMUXER_CTRL_DONTKNOW
3244 if (demux_control(demuxer, DEMUXER_CTRL_GET_TIME_LENGTH,
3245 (void *) &get_time_ans) > 0)
3246 return get_time_ans;
3248 struct sh_video *sh_video = mpctx->d_video->sh;
3249 struct sh_audio *sh_audio = mpctx->d_audio->sh;
3250 if (sh_video && sh_video->i_bps && sh_audio && sh_audio->i_bps)
3251 return (double) (demuxer->movi_end - demuxer->movi_start) /
3252 (sh_video->i_bps + sh_audio->i_bps);
3253 if (sh_video && sh_video->i_bps)
3254 return (double) (demuxer->movi_end - demuxer->movi_start) /
3255 sh_video->i_bps;
3256 if (sh_audio && sh_audio->i_bps)
3257 return (double) (demuxer->movi_end - demuxer->movi_start) /
3258 sh_audio->i_bps;
3259 return 0;
3262 /* If there are timestamps from stream level then use those (for example
3263 * DVDs can have consistent times there while the MPEG-level timestamps
3264 * reset). */
3265 double get_current_time(struct MPContext *mpctx)
3267 struct demuxer *demuxer = mpctx->demuxer;
3268 if (demuxer->stream_pts != MP_NOPTS_VALUE)
3269 return demuxer->stream_pts;
3270 if (mpctx->sh_video) {
3271 double pts = mpctx->video_pts;
3272 if (pts != MP_NOPTS_VALUE)
3273 return pts;
3275 double apts = playing_audio_pts(mpctx);
3276 if (apts != MP_NOPTS_VALUE)
3277 return apts;
3278 return mpctx->last_seek_pts;
3281 int get_percent_pos(struct MPContext *mpctx)
3283 struct demuxer *demuxer = mpctx->demuxer;
3284 int ans = 0;
3285 if (mpctx->timeline)
3286 ans = get_current_time(mpctx) * 100 /
3287 mpctx->timeline[mpctx->num_timeline_parts].start;
3288 else if (demux_control(demuxer, DEMUXER_CTRL_GET_PERCENT_POS, &ans) > 0)
3290 else {
3291 int len = (demuxer->movi_end - demuxer->movi_start) / 100;
3292 off_t pos = demuxer->filepos > 0 ?
3293 demuxer->filepos : stream_tell(demuxer->stream);
3294 if (len > 0)
3295 ans = (pos - demuxer->movi_start) / len;
3296 else
3297 ans = 0;
3299 if (ans < 0)
3300 ans = 0;
3301 if (ans > 100)
3302 ans = 100;
3303 return ans;
3306 // -2 is no chapters, -1 is before first chapter
3307 int get_current_chapter(struct MPContext *mpctx)
3309 double current_pts = get_current_time(mpctx);
3310 if (!mpctx->chapters)
3311 return FFMAX(mpctx->last_chapter_seek,
3312 demuxer_get_current_chapter(mpctx->demuxer, current_pts));
3314 int i;
3315 for (i = 1; i < mpctx->num_chapters; i++)
3316 if (current_pts < mpctx->chapters[i].start)
3317 break;
3318 return FFMAX(mpctx->last_chapter_seek, i - 1);
3321 char *chapter_display_name(struct MPContext *mpctx, int chapter)
3323 char *name = chapter_name(mpctx, chapter);
3324 if (name) {
3325 name = talloc_asprintf(name, "(%d) %s", chapter + 1, name);
3326 } else {
3327 int chapter_count = get_chapter_count(mpctx);
3328 if (chapter_count <= 0)
3329 name = talloc_asprintf(NULL, "(%d)", chapter + 1);
3330 else
3331 name = talloc_asprintf(NULL, "(%d) of %d", chapter + 1,
3332 chapter_count);
3334 return name;
3337 // returns NULL if chapter name unavailable
3338 char *chapter_name(struct MPContext *mpctx, int chapter)
3340 if (!mpctx->chapters)
3341 return demuxer_chapter_name(mpctx->demuxer, chapter);
3342 return talloc_strdup(NULL, mpctx->chapters[chapter].name);
3345 // returns the start of the chapter in seconds
3346 double chapter_start_time(struct MPContext *mpctx, int chapter)
3348 if (!mpctx->chapters)
3349 return demuxer_chapter_time(mpctx->demuxer, chapter, NULL);
3350 return mpctx->chapters[chapter].start;
3353 int get_chapter_count(struct MPContext *mpctx)
3355 if (!mpctx->chapters)
3356 return demuxer_chapter_count(mpctx->demuxer);
3357 return mpctx->num_chapters;
3360 int seek_chapter(struct MPContext *mpctx, int chapter, double *seek_pts)
3362 mpctx->last_chapter_seek = -2;
3363 if (!mpctx->chapters) {
3364 int res = demuxer_seek_chapter(mpctx->demuxer, chapter, seek_pts);
3365 if (res >= 0) {
3366 if (*seek_pts == -1)
3367 seek_reset(mpctx, true, true);
3368 else {
3369 mpctx->last_chapter_seek = res;
3370 mpctx->last_chapter_pts = *seek_pts;
3373 return res;
3376 if (chapter >= mpctx->num_chapters)
3377 return -1;
3378 if (chapter < 0)
3379 chapter = 0;
3380 *seek_pts = mpctx->chapters[chapter].start;
3381 mpctx->last_chapter_seek = chapter;
3382 mpctx->last_chapter_pts = *seek_pts;
3383 return chapter;
3387 static void run_playloop(struct MPContext *mpctx)
3389 struct MPOpts *opts = &mpctx->opts;
3390 bool full_audio_buffers = false;
3391 bool audio_left = false, video_left = false;
3392 double endpts = end_at.type == END_AT_TIME ? end_at.pos : MP_NOPTS_VALUE;
3393 bool end_is_chapter = false;
3394 double sleeptime = WAKEUP_PERIOD;
3395 bool was_restart = mpctx->restart_playback;
3397 if (mpctx->timeline) {
3398 double end = mpctx->timeline[mpctx->timeline_part + 1].start;
3399 if (endpts == MP_NOPTS_VALUE || end < endpts) {
3400 endpts = end;
3401 end_is_chapter = true;
3405 if (opts->chapterrange[1] > 0) {
3406 int cur_chapter = get_current_chapter(mpctx);
3407 if (cur_chapter != -1 && cur_chapter + 1 > opts->chapterrange[1])
3408 mpctx->stop_play = PT_NEXT_ENTRY;
3411 if (!mpctx->sh_audio && mpctx->d_audio->sh) {
3412 mpctx->sh_audio = mpctx->d_audio->sh;
3413 mpctx->sh_audio->ds = mpctx->d_audio;
3414 reinit_audio_chain(mpctx);
3417 if (mpctx->step_frames && !mpctx->sh_video) {
3418 mpctx->step_frames = 0;
3419 pause_player(mpctx);
3422 if (mpctx->sh_audio && !mpctx->restart_playback && !mpctx->ao->untimed) {
3423 int status = fill_audio_out_buffers(mpctx, endpts);
3424 full_audio_buffers = status >= 0;
3425 // Not at audio stream EOF yet
3426 audio_left = status > -2;
3429 double buffered_audio = -1;
3430 while (mpctx->sh_video) { // never loops, for "break;" only
3431 struct vo *vo = mpctx->video_out;
3432 vo_pts = mpctx->sh_video->timer * 90000.0;
3433 vo_fps = mpctx->sh_video->fps;
3435 video_left = vo->hasframe || vo->frame_loaded;
3436 if (!vo->frame_loaded && (!mpctx->paused || mpctx->restart_playback)) {
3437 double frame_time = update_video(mpctx);
3438 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "*** ftime=%5.3f ***\n", frame_time);
3439 if (mpctx->sh_video->vf_initialized < 0) {
3440 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
3441 "\nFATAL: Could not initialize video filters (-vf) "
3442 "or video output (-vo).\n");
3443 mpctx->stop_play = PT_NEXT_ENTRY;
3444 return;
3446 video_left = frame_time >= 0;
3447 if (video_left && !mpctx->restart_playback) {
3448 mpctx->time_frame += frame_time / opts->playback_speed;
3449 adjust_sync(mpctx, frame_time);
3453 if (endpts != MP_NOPTS_VALUE)
3454 video_left &= mpctx->sh_video->pts < endpts;
3456 // ================================================================
3458 current_module = "vo_check_events";
3459 vo_check_events(vo);
3461 #ifdef CONFIG_X11
3462 if (stop_xscreensaver && vo->x11)
3463 xscreensaver_heartbeat(vo->x11);
3464 #endif
3465 if (heartbeat_cmd) {
3466 static unsigned last_heartbeat;
3467 unsigned now = GetTimerMS();
3468 if (now - last_heartbeat > 30000) {
3469 last_heartbeat = now;
3470 system(heartbeat_cmd);
3474 if (!video_left || (mpctx->paused && !mpctx->restart_playback))
3475 break;
3476 if (!vo->frame_loaded) {
3477 sleeptime = 0;
3478 break;
3481 mpctx->time_frame -= get_relative_time(mpctx);
3482 if (full_audio_buffers && !mpctx->restart_playback) {
3483 buffered_audio = ao_get_delay(mpctx->ao);
3484 mp_dbg(MSGT_AVSYNC, MSGL_DBG2, "delay=%f\n", buffered_audio);
3486 if (opts->autosync) {
3487 /* Smooth reported playback position from AO by averaging
3488 * it with the value expected based on previus value and
3489 * time elapsed since then. May help smooth video timing
3490 * with audio output that have inaccurate position reporting.
3491 * This is badly implemented; the behavior of the smoothing
3492 * now undesirably depends on how often this code runs
3493 * (mainly depends on video frame rate). */
3494 float predicted = (mpctx->delay / opts->playback_speed +
3495 mpctx->time_frame);
3496 float difference = buffered_audio - predicted;
3497 buffered_audio = predicted + difference / opts->autosync;
3500 mpctx->time_frame = (buffered_audio -
3501 mpctx->delay / opts->playback_speed);
3502 } else {
3503 /* If we're more than 200 ms behind the right playback
3504 * position, don't try to speed up display of following
3505 * frames to catch up; continue with default speed from
3506 * the current frame instead.
3507 * If benchmark is set always output frames immediately
3508 * without sleeping.
3510 if (mpctx->time_frame < -0.2 || opts->benchmark)
3511 mpctx->time_frame = 0;
3514 double vsleep = mpctx->time_frame - vo->flip_queue_offset;
3515 if (vsleep > 0.050) {
3516 sleeptime = FFMIN(sleeptime, vsleep - 0.040);
3517 break;
3519 sleeptime = 0;
3521 //=================== FLIP PAGE (VIDEO BLT): ======================
3523 current_module = "flip_page";
3524 vo_new_frame_imminent(vo);
3525 struct sh_video *sh_video = mpctx->sh_video;
3526 mpctx->video_pts = sh_video->pts;
3527 update_subtitles(mpctx, sh_video->pts, false);
3528 update_teletext(sh_video, mpctx->demuxer, 0);
3529 update_osd_msg(mpctx);
3530 struct vf_instance *vf = sh_video->vfilter;
3531 mpctx->osd->sub_pts = mpctx->video_pts;
3532 if (mpctx->osd->sub_pts != MP_NOPTS_VALUE)
3533 mpctx->osd->sub_pts += opts->sub_delay - mpctx->osd->sub_offset;
3534 vf->control(vf, VFCTRL_DRAW_EOSD, mpctx->osd);
3535 vf->control(vf, VFCTRL_DRAW_OSD, mpctx->osd);
3536 vo_osd_changed(0);
3538 mpctx->time_frame -= get_relative_time(mpctx);
3539 mpctx->time_frame -= vo->flip_queue_offset;
3540 float aq_sleep_time = mpctx->time_frame;
3541 if (mpctx->time_frame > 0.001
3542 && !(mpctx->sh_video->output_flags & VFCAP_TIMER))
3543 mpctx->time_frame = timing_sleep(mpctx, mpctx->time_frame);
3544 mpctx->time_frame += vo->flip_queue_offset;
3546 unsigned int t2 = GetTimer();
3547 /* Playing with playback speed it's possible to get pathological
3548 * cases with mpctx->time_frame negative enough to cause an
3549 * overflow in pts_us calculation, thus the FFMAX. */
3550 double time_frame = FFMAX(mpctx->time_frame, -1);
3551 unsigned int pts_us = mpctx->last_time + time_frame * 1e6;
3552 int duration = -1;
3553 double pts2 = vo->next_pts2;
3554 if (pts2 != MP_NOPTS_VALUE && opts->correct_pts &&
3555 !mpctx->restart_playback) {
3556 // expected A/V sync correction is ignored
3557 double diff = (pts2 - mpctx->video_pts);
3558 diff /= opts->playback_speed;
3559 if (mpctx->time_frame < 0)
3560 diff += mpctx->time_frame;
3561 if (diff < 0)
3562 diff = 0;
3563 if (diff > 10)
3564 diff = 10;
3565 duration = diff * 1e6;
3567 vo_flip_page(vo, pts_us | 1, duration);
3569 mpctx->last_vo_flip_duration = (GetTimer() - t2) * 0.000001;
3570 vout_time_usage += mpctx->last_vo_flip_duration;
3571 if (vo->driver->flip_page_timed) {
3572 // No need to adjust sync based on flip speed
3573 mpctx->last_vo_flip_duration = 0;
3574 // For print_status - VO call finishing early is OK for sync
3575 mpctx->time_frame -= get_relative_time(mpctx);
3577 if (mpctx->restart_playback) {
3578 mpctx->syncing_audio = true;
3579 if (mpctx->sh_audio)
3580 fill_audio_out_buffers(mpctx, endpts);
3581 mpctx->restart_playback = false;
3582 mpctx->time_frame = 0;
3583 get_relative_time(mpctx);
3585 print_status(mpctx, MP_NOPTS_VALUE, true);
3586 screenshot_flip(mpctx);
3588 if (opts->auto_quality > 0) {
3589 current_module = "autoq";
3590 if (output_quality < opts->auto_quality && aq_sleep_time > 0)
3591 ++output_quality;
3592 else if (output_quality > 1 && aq_sleep_time < 0)
3593 --output_quality;
3594 else if (output_quality > 0 && aq_sleep_time < -0.050f) // 50ms
3595 output_quality = 0;
3596 set_video_quality(mpctx->sh_video, output_quality);
3599 if (play_n_frames >= 0) {
3600 --play_n_frames;
3601 if (play_n_frames <= 0)
3602 mpctx->stop_play = PT_NEXT_ENTRY;
3604 if (mpctx->step_frames > 0) {
3605 mpctx->step_frames--;
3606 if (mpctx->step_frames == 0)
3607 pause_player(mpctx);
3609 break;
3610 } // video
3612 #ifdef CONFIG_DVDNAV
3613 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
3614 nav_highlight_t hl;
3615 mp_dvdnav_get_highlight(mpctx->stream, &hl);
3616 if (!vo_spudec || !spudec_apply_palette_crop(vo_spudec, hl.palette, hl.sx, hl.sy, hl.ex, hl.ey)) {
3617 osd_set_nav_box(hl.sx, hl.sy, hl.ex, hl.ey);
3618 vo_osd_changed(OSDTYPE_DVDNAV);
3619 } else {
3620 osd_set_nav_box(0, 0, 0, 0);
3621 vo_osd_changed(OSDTYPE_DVDNAV);
3622 vo_osd_changed(OSDTYPE_SPU);
3625 if (mp_dvdnav_stream_has_changed(mpctx->stream)) {
3626 double ar = -1.0;
3627 if (mpctx->sh_video &&
3628 stream_control(mpctx->demuxer->stream,
3629 STREAM_CTRL_GET_ASPECT_RATIO, &ar)
3630 != STREAM_UNSUPPORTED)
3631 mpctx->sh_video->stream_aspect = ar;
3634 #endif
3636 if (mpctx->sh_audio && (mpctx->restart_playback ? !video_left :
3637 mpctx->ao->untimed && (mpctx->delay <= 0 ||
3638 !video_left))) {
3639 int status = fill_audio_out_buffers(mpctx, endpts);
3640 full_audio_buffers = status >= 0 && !mpctx->ao->untimed;
3641 // Not at audio stream EOF yet
3642 audio_left = status > -2;
3644 if (!video_left)
3645 mpctx->restart_playback = false;
3646 if (mpctx->sh_audio && buffered_audio == -1)
3647 buffered_audio = mpctx->paused ? 0 : ao_get_delay(mpctx->ao);
3649 update_osd_msg(mpctx);
3650 if (mpctx->paused)
3651 update_pause_message(mpctx);
3652 if (!video_left && (!mpctx->paused || was_restart)) {
3653 double a_pos = 0;
3654 if (mpctx->sh_audio) {
3655 a_pos = (written_audio_pts(mpctx) -
3656 mpctx->opts.playback_speed * buffered_audio);
3658 print_status(mpctx, a_pos, false);
3660 if (!mpctx->sh_video)
3661 update_subtitles(mpctx, a_pos, false);
3664 /* It's possible for the user to simultaneously switch both audio
3665 * and video streams to "disabled" at runtime. Handle this by waiting
3666 * rather than immediately stopping playback due to EOF.
3668 * When all audio has been written to output driver, stay in the
3669 * main loop handling commands until it has been mostly consumed,
3670 * except in the gapless case, where the next file will be started
3671 * while audio from the current one still remains to be played.
3673 * We want this check to trigger if we seeked to this position,
3674 * but not if we paused at it with audio possibly still buffered in
3675 * the AO. There's currently no working way to check buffered audio
3676 * inside AO while paused. Thus the "was_restart" check below, which
3677 * should trigger after seek only, when we know there's no audio
3678 * buffered.
3680 if ((mpctx->sh_audio || mpctx->sh_video) && !audio_left && !video_left
3681 && (opts->gapless_audio || buffered_audio < 0.05)
3682 && (!mpctx->paused || was_restart)) {
3683 if (end_is_chapter) {
3684 seek(mpctx, (struct seek_params){
3685 .type = MPSEEK_ABSOLUTE,
3686 .amount = mpctx->timeline[mpctx->timeline_part+1].start
3687 }, true);
3688 } else
3689 mpctx->stop_play = AT_END_OF_FILE;
3690 } else if (!mpctx->stop_play) {
3691 double audio_sleep = 9;
3692 if (mpctx->sh_audio && !mpctx->paused) {
3693 if (mpctx->ao->untimed) {
3694 if (!video_left)
3695 audio_sleep = 0;
3696 } else if (full_audio_buffers) {
3697 audio_sleep = buffered_audio - 0.050;
3698 // Keep extra safety margin if the buffers are large
3699 if (audio_sleep > 0.100)
3700 audio_sleep = FFMAX(audio_sleep - 0.200, 0.100);
3701 else
3702 audio_sleep = FFMAX(audio_sleep, 0.020);
3703 } else
3704 audio_sleep = 0.020;
3706 sleeptime = FFMIN(sleeptime, audio_sleep);
3707 if (sleeptime > 0) {
3708 if (!mpctx->sh_video)
3709 goto novideo;
3710 int hack = vo_osd_changed(0);
3711 vo_osd_changed(hack);
3712 if (hack || mpctx->video_out->want_redraw) {
3713 if (redraw_osd(mpctx) < 0) {
3714 if (mpctx->paused && video_left)
3715 add_step_frame(mpctx);
3716 else
3717 goto novideo;
3718 } else
3719 vo_osd_changed(0);
3720 } else {
3721 novideo:
3722 mp_input_get_cmd(mpctx->input, sleeptime * 1000, true);
3727 //================= Keyboard events, SEEKing ====================
3729 current_module = "key_events";
3731 mp_cmd_t *cmd;
3732 while ((cmd = mp_input_get_cmd(mpctx->input, 0, 1)) != NULL) {
3733 /* Allow running consecutive seek commands to combine them,
3734 * but execute the seek before running other commands.
3735 * If the user seeks continuously (keeps arrow key down)
3736 * try to finish showing a frame from one location before doing
3737 * another seek (which could lead to unchanging display). */
3738 if (mpctx->seek.type && cmd->id != MP_CMD_SEEK
3739 || mpctx->restart_playback && cmd->id == MP_CMD_SEEK
3740 && GetTimerMS() - mpctx->start_timestamp < 300)
3741 break;
3742 cmd = mp_input_get_cmd(mpctx->input, 0, 0);
3743 run_command(mpctx, cmd);
3744 mp_cmd_free(cmd);
3745 if (mpctx->stop_play)
3746 break;
3749 // handle -sstep
3750 if (step_sec > 0 && !mpctx->paused && !mpctx->restart_playback) {
3751 mpctx->osd_function = OSD_FFW;
3752 queue_seek(mpctx, MPSEEK_RELATIVE, step_sec, 0);
3755 /* Looping. */
3756 if (opts->loop_times >= 0 && (mpctx->stop_play == AT_END_OF_FILE ||
3757 mpctx->stop_play == PT_NEXT_ENTRY)) {
3758 mp_msg(MSGT_CPLAYER, MSGL_V, "loop_times = %d\n", opts->loop_times);
3760 if (opts->loop_times > 1)
3761 opts->loop_times--;
3762 else if (opts->loop_times == 1)
3763 opts->loop_times = -1;
3764 play_n_frames = play_n_frames_mf;
3765 mpctx->stop_play = 0;
3766 queue_seek(mpctx, MPSEEK_ABSOLUTE, opts->seek_to_sec, 0);
3769 if (mpctx->seek.type) {
3770 seek(mpctx, mpctx->seek, false);
3771 mpctx->seek = (struct seek_params){ 0 };
3776 static int read_keys(void *ctx, int fd)
3778 if (getch2(ctx))
3779 return MP_INPUT_NOTHING;
3780 return MP_INPUT_DEAD;
3783 static bool attachment_is_font(struct demux_attachment *att)
3785 if (!att->name || !att->type || !att->data || !att->data_size)
3786 return false;
3787 // match against MIME types
3788 if (strcmp(att->type, "application/x-truetype-font") == 0
3789 || strcmp(att->type, "application/x-font") == 0)
3790 return true;
3791 // fallback: match against file extension
3792 if (strlen(att->name) > 4) {
3793 char *ext = att->name + strlen(att->name) - 4;
3794 if (strcasecmp(ext, ".ttf") == 0 || strcasecmp(ext, ".ttc") == 0
3795 || strcasecmp(ext, ".otf") == 0)
3796 return true;
3798 return false;
3801 static int select_audio(demuxer_t *demuxer, int audio_id, char **audio_lang)
3803 if (audio_id == -1)
3804 audio_id = demuxer_audio_track_by_lang_and_default(demuxer, audio_lang);
3805 if (audio_id != -1) // -1 (automatic) is the default behaviour of demuxers
3806 demuxer_switch_audio(demuxer, audio_id);
3807 if (audio_id == -2) { // some demuxers don't yet know how to switch to no sound
3808 demuxer->audio->id = -2;
3809 demuxer->audio->sh = NULL;
3811 return demuxer->audio->id;
3814 static void print_version(const char *name)
3816 mp_msg(MSGT_CPLAYER, MSGL_INFO, MP_TITLE, name);
3818 /* Test for CPU capabilities (and corresponding OS support) for optimizing */
3819 GetCpuCaps(&gCpuCaps);
3820 #if ARCH_X86
3821 mp_msg(MSGT_CPLAYER, MSGL_V,
3822 "CPUflags: MMX: %d MMX2: %d 3DNow: %d 3DNowExt: %d SSE: %d SSE2: %d SSSE3: %d\n",
3823 gCpuCaps.hasMMX, gCpuCaps.hasMMX2,
3824 gCpuCaps.has3DNow, gCpuCaps.has3DNowExt,
3825 gCpuCaps.hasSSE, gCpuCaps.hasSSE2, gCpuCaps.hasSSSE3);
3826 #if CONFIG_RUNTIME_CPUDETECT
3827 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Compiled with runtime CPU detection.\n");
3828 #else
3829 mp_tmsg(MSGT_CPLAYER, MSGL_V, "Compiled for x86 CPU with extensions:");
3830 if (HAVE_MMX)
3831 mp_msg(MSGT_CPLAYER, MSGL_V, " MMX");
3832 if (HAVE_MMX2)
3833 mp_msg(MSGT_CPLAYER, MSGL_V, " MMX2");
3834 if (HAVE_AMD3DNOW)
3835 mp_msg(MSGT_CPLAYER, MSGL_V, " 3DNow");
3836 if (HAVE_AMD3DNOWEXT)
3837 mp_msg(MSGT_CPLAYER, MSGL_V, " 3DNowExt");
3838 if (HAVE_SSE)
3839 mp_msg(MSGT_CPLAYER, MSGL_V, " SSE");
3840 if (HAVE_SSE2)
3841 mp_msg(MSGT_CPLAYER, MSGL_V, " SSE2");
3842 if (HAVE_SSSE3)
3843 mp_msg(MSGT_CPLAYER, MSGL_V, " SSSE3");
3844 if (HAVE_CMOV)
3845 mp_msg(MSGT_CPLAYER, MSGL_V, " CMOV");
3846 mp_msg(MSGT_CPLAYER, MSGL_V, "\n");
3847 #endif /* CONFIG_RUNTIME_CPUDETECT */
3848 #endif /* ARCH_X86 */
3849 print_libav_versions();
3852 #ifdef PTW32_STATIC_LIB
3853 static void detach_ptw32(void)
3855 pthread_win32_thread_detach_np();
3856 pthread_win32_process_detach_np();
3858 #endif
3860 /* This preprocessor directive is a hack to generate a mplayer-nomain.o object
3861 * file for some tools to link against. */
3862 #ifndef DISABLE_MAIN
3863 int main(int argc, char *argv[])
3865 #ifdef PTW32_STATIC_LIB
3866 pthread_win32_process_attach_np();
3867 pthread_win32_thread_attach_np();
3868 atexit(detach_ptw32);
3869 #endif
3870 if (argc > 1 && (!strcmp(argv[1], "-leak-report")
3871 || !strcmp(argv[1], "--leak-report")))
3872 talloc_enable_leak_report();
3874 #ifdef __MINGW32__
3875 mp_get_converted_argv(&argc, &argv);
3876 #endif
3878 char *mem_ptr;
3880 // movie info:
3882 /* Flag indicating whether MPlayer should exit without playing anything. */
3883 int opt_exit = 0;
3884 int i;
3886 struct MPContext *mpctx = talloc(NULL, MPContext);
3887 *mpctx = (struct MPContext){
3888 .osd_function = OSD_PLAY,
3889 .begin_skip = MP_NOPTS_VALUE,
3890 .play_tree_step = 1,
3891 .global_sub_pos = -1,
3892 .set_of_sub_pos = -1,
3893 .file_format = DEMUXER_TYPE_UNKNOWN,
3894 .last_dvb_step = 1,
3895 .paused_cache_fill = -1,
3898 InitTimer();
3899 srand(GetTimerMS());
3901 mp_msg_init();
3902 init_libav();
3904 struct MPOpts *opts = &mpctx->opts;
3905 set_default_mplayer_options(opts);
3906 // Create the config context and register the options
3907 mpctx->mconfig = m_config_new(opts, cfg_include);
3908 m_config_register_options(mpctx->mconfig, mplayer_opts);
3909 m_config_register_options(mpctx->mconfig, common_opts);
3910 mp_input_register_options(mpctx->mconfig);
3911 m_config_initialize(mpctx->mconfig, opts);
3913 // Preparse the command line
3914 m_config_preparse_command_line(mpctx->mconfig, argc, argv, &verbose);
3916 #if (defined(__MINGW32__) || defined(__CYGWIN__)) && defined(CONFIG_WIN32DLL)
3917 set_path_env();
3918 #endif
3920 #ifdef CONFIG_TV
3921 stream_tv_defaults.immediate = 1;
3922 #endif
3924 parse_cfgfiles(mpctx, mpctx->mconfig);
3926 mpctx->playtree = m_config_parse_mp_command_line(mpctx->mconfig, argc, argv);
3927 if (mpctx->playtree == NULL)
3928 opt_exit = 1;
3929 else {
3930 mpctx->playtree = play_tree_cleanup(mpctx->playtree);
3931 if (mpctx->playtree) {
3932 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,
3933 mpctx->mconfig);
3934 if (mpctx->playtree_iter) {
3935 if (play_tree_iter_step(mpctx->playtree_iter, 0, 0) !=
3936 PLAY_TREE_ITER_ENTRY) {
3937 play_tree_iter_free(mpctx->playtree_iter);
3938 mpctx->playtree_iter = NULL;
3940 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,
3946 print_version("MPlayer2");
3948 #if defined(__MINGW32__) || defined(__CYGWIN__)
3950 HMODULE kernel32 = GetModuleHandle("Kernel32.dll");
3951 BOOL WINAPI (*setDEP)(DWORD) = NULL;
3952 BOOL WINAPI (*setDllDir)(LPCTSTR) = NULL;
3953 if (kernel32) {
3954 setDEP = GetProcAddress(kernel32, "SetProcessDEPPolicy");
3955 setDllDir = GetProcAddress(kernel32, "SetDllDirectoryA");
3957 if (setDEP)
3958 setDEP(3);
3959 if (setDllDir)
3960 setDllDir("");
3962 // stop Windows from showing all kinds of annoying error dialogs
3963 SetErrorMode(0x8003);
3964 // request 1ms timer resolution
3965 timeBeginPeriod(1);
3966 #endif
3968 #ifdef CONFIG_PRIORITY
3969 set_priority();
3970 #endif
3972 if (opts->video_driver_list &&
3973 strcmp(opts->video_driver_list[0], "help") == 0) {
3974 list_video_out();
3975 opt_exit = 1;
3978 if (opts->audio_driver_list &&
3979 strcmp(opts->audio_driver_list[0], "help") == 0) {
3980 list_audio_out();
3981 opt_exit = 1;
3984 /* Check codecs.conf. */
3985 if (!codecs_file || !parse_codec_cfg(codecs_file, opts)) {
3986 if (!parse_codec_cfg(mem_ptr = get_path("codecs.conf"), opts)) {
3987 if (!parse_codec_cfg(MPLAYER_CONFDIR "/codecs.conf", opts)) {
3988 if (!parse_codec_cfg(NULL, opts))
3989 exit_player_with_rc(mpctx, EXIT_NONE, 0);
3990 mp_tmsg(MSGT_CPLAYER, MSGL_V,
3991 "Using built-in default codecs.conf.\n");
3994 free(mem_ptr); // release the buffer created by get_path()
3997 if (audio_codec_list && strcmp(audio_codec_list[0], "help") == 0) {
3998 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available audio codecs:\n");
3999 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AUDIO_CODECS\n");
4000 list_codecs(1);
4001 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4002 opt_exit = 1;
4004 if (video_codec_list && strcmp(video_codec_list[0], "help") == 0) {
4005 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Available video codecs:\n");
4006 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_CODECS\n");
4007 list_codecs(0);
4008 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4009 opt_exit = 1;
4011 if (video_fm_list && strcmp(video_fm_list[0], "help") == 0) {
4012 vfm_help();
4013 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4014 opt_exit = 1;
4016 if (audio_fm_list && strcmp(audio_fm_list[0], "help") == 0) {
4017 afm_help();
4018 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4019 opt_exit = 1;
4021 if (af_cfg.list && strcmp(af_cfg.list[0], "help") == 0) {
4022 af_help();
4023 printf("\n");
4024 opt_exit = 1;
4026 #ifdef CONFIG_X11
4027 if (vo_fstype_list && strcmp(vo_fstype_list[0], "help") == 0) {
4028 fstype_help();
4029 mp_msg(MSGT_FIXME, MSGL_FIXME, "\n");
4030 opt_exit = 1;
4032 #endif
4033 if ((opts->demuxer_name && strcmp(opts->demuxer_name, "help") == 0) ||
4034 (opts->audio_demuxer_name && strcmp(opts->audio_demuxer_name, "help") == 0) ||
4035 (opts->sub_demuxer_name && strcmp(opts->sub_demuxer_name, "help") == 0)) {
4036 demuxer_help();
4037 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
4038 opt_exit = 1;
4040 if (opts->list_properties) {
4041 property_print_help();
4042 opt_exit = 1;
4045 if (opt_exit)
4046 exit_player(mpctx, EXIT_NONE);
4048 if (!mpctx->filename && !opts->player_idle_mode) {
4049 // no file/vcd/dvd -> show HELP:
4050 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", mp_gtext(help_text));
4051 exit_player_with_rc(mpctx, EXIT_NONE, 0);
4054 /* Display what configure line was used */
4055 mp_msg(MSGT_CPLAYER, MSGL_V, "Configuration: " CONFIGURATION "\n");
4057 // Many users forget to include command line in bugreports...
4058 if (mp_msg_test(MSGT_CPLAYER, MSGL_V)) {
4059 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "CommandLine:");
4060 for (i = 1; i < argc; i++)
4061 mp_msg(MSGT_CPLAYER, MSGL_INFO, " '%s'", argv[i]);
4062 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
4065 //------ load global data first ------
4067 #ifdef CONFIG_ASS
4068 mpctx->ass_library = mp_ass_init(opts);
4069 #endif
4071 mpctx->osd = osd_create(opts, mpctx->ass_library);
4073 #ifdef HAVE_RTC
4074 if (opts->rtc) {
4075 char *rtc_device = opts->rtc_device;
4076 // seteuid(0); /* Can't hurt to try to get root here */
4077 if ((rtc_fd = open(rtc_device ? rtc_device : "/dev/rtc", O_RDONLY)) < 0)
4078 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Failed to open %s: %s "
4079 "(it should be readable by the user.)\n",
4080 rtc_device ? rtc_device : "/dev/rtc", strerror(errno));
4081 else {
4082 unsigned long irqp = 1024; /* 512 seemed OK. 128 is jerky. */
4084 if (ioctl(rtc_fd, RTC_IRQP_SET, irqp) < 0) {
4085 mp_tmsg(MSGT_CPLAYER, MSGL_WARN, "Linux RTC init error in "
4086 "ioctl (rtc_irqp_set %lu): %s\n",
4087 irqp, strerror(errno));
4088 mp_tmsg(MSGT_CPLAYER, MSGL_HINT, "Try adding \"echo %lu > /proc/sys/dev/rtc/max-user-freq\" to your system startup scripts.\n", irqp);
4089 close(rtc_fd);
4090 rtc_fd = -1;
4091 } else if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
4092 /* variable only by the root */
4093 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Linux RTC init error in "
4094 "ioctl (rtc_pie_on): %s\n", strerror(errno));
4095 close(rtc_fd);
4096 rtc_fd = -1;
4097 } else
4098 mp_tmsg(MSGT_CPLAYER, MSGL_V,
4099 "Using Linux hardware RTC timing (%ldHz).\n", irqp);
4102 if (rtc_fd < 0)
4103 #endif /* HAVE_RTC */
4104 mp_msg(MSGT_CPLAYER, MSGL_V, "Using %s timing\n",
4105 opts->softsleep ? "software" : timer_name);
4107 #ifdef HAVE_TERMCAP
4108 load_termcap(NULL); // load key-codes
4109 #endif
4111 // ========== Init keyboard FIFO (connection to libvo) ============
4113 // Init input system
4114 current_module = "init_input";
4115 mpctx->input = mp_input_init(opts);
4116 mpctx->key_fifo = mp_fifo_create(mpctx->input, opts);
4117 if (slave_mode)
4118 mp_input_add_cmd_fd(mpctx->input, 0, USE_FD0_CMD_SELECT, MP_INPUT_SLAVE_CMD_FUNC, NULL);
4119 else if (opts->consolecontrols)
4120 mp_input_add_key_fd(mpctx->input, 0, 1, read_keys, NULL, mpctx->key_fifo);
4121 // Set the libstream interrupt callback
4122 stream_set_interrupt_callback(mp_input_check_interrupt, mpctx->input);
4124 current_module = NULL;
4126 /// Catch signals
4127 #ifndef __MINGW32__
4128 signal(SIGCHLD, child_sighandler);
4129 #endif
4131 #ifdef CONFIG_CRASH_DEBUG
4132 prog_path = argv[0];
4133 #endif
4134 //========= Catch terminate signals: ================
4135 // terminate requests:
4136 signal(SIGTERM, exit_sighandler); // kill
4137 signal(SIGHUP, exit_sighandler); // kill -HUP / xterm closed
4139 signal(SIGINT, exit_sighandler); // Interrupt from keyboard
4141 signal(SIGQUIT, exit_sighandler); // Quit from keyboard
4142 signal(SIGPIPE, exit_sighandler); // Some window managers cause this
4143 #ifdef CONFIG_SIGHANDLER
4144 // fatal errors:
4145 signal(SIGBUS, exit_sighandler); // bus error
4146 signal(SIGSEGV, exit_sighandler); // segfault
4147 signal(SIGILL, exit_sighandler); // illegal instruction
4148 signal(SIGFPE, exit_sighandler); // floating point exc.
4149 signal(SIGABRT, exit_sighandler); // abort()
4150 #ifdef CONFIG_CRASH_DEBUG
4151 if (crash_debug)
4152 signal(SIGTRAP, exit_sighandler);
4153 #endif
4154 #endif
4156 // ***************** Now, let's see the per-file stuff ******************
4158 play_next_file:
4160 // init global sub numbers
4161 mpctx->global_sub_size = 0;
4162 memset(mpctx->sub_counts, 0, sizeof(mpctx->sub_counts));
4164 if (mpctx->filename) {
4165 load_per_protocol_config(mpctx->mconfig, mpctx->filename);
4166 load_per_extension_config(mpctx->mconfig, mpctx->filename);
4167 load_per_file_config(mpctx->mconfig, mpctx->filename);
4170 if (opts->video_driver_list)
4171 load_per_output_config(mpctx->mconfig, PROFILE_CFG_VO,
4172 opts->video_driver_list[0]);
4173 if (opts->audio_driver_list)
4174 load_per_output_config(mpctx->mconfig, PROFILE_CFG_AO,
4175 opts->audio_driver_list[0]);
4177 // We must enable getch2 here to be able to interrupt network connection
4178 // or cache filling
4179 if (opts->consolecontrols && !slave_mode) {
4180 if (mpctx->initialized_flags & INITIALIZED_GETCH2)
4181 mp_tmsg(MSGT_CPLAYER, MSGL_WARN,
4182 "WARNING: getch2_init called twice!\n");
4183 else
4184 getch2_enable(); // prepare stdin for hotkeys...
4185 mpctx->initialized_flags |= INITIALIZED_GETCH2;
4186 mp_msg(MSGT_CPLAYER, MSGL_DBG2, "\n[[[init getch2]]]\n");
4189 // ================= idle loop (STOP state) =========================
4190 while (opts->player_idle_mode && !mpctx->filename) {
4191 uninit_player(mpctx, INITIALIZED_AO | INITIALIZED_VO);
4192 play_tree_t *entry = NULL;
4193 mp_cmd_t *cmd;
4194 while (!(cmd = mp_input_get_cmd(mpctx->input, WAKEUP_PERIOD * 1000,
4195 false)));
4196 switch (cmd->id) {
4197 case MP_CMD_LOADFILE:
4198 // prepare a tree entry with the new filename
4199 entry = play_tree_new();
4200 play_tree_add_file(entry, cmd->args[0].v.s);
4201 // The entry is added to the main playtree after the switch().
4202 break;
4203 case MP_CMD_LOADLIST:
4204 entry = parse_playlist_file(&mpctx->opts, bstr(cmd->args[0].v.s));
4205 break;
4206 case MP_CMD_QUIT:
4207 exit_player_with_rc(mpctx, EXIT_QUIT,
4208 (cmd->nargs > 0) ? cmd->args[0].v.i : 0);
4209 break;
4210 case MP_CMD_VO_FULLSCREEN:
4211 case MP_CMD_GET_PROPERTY:
4212 case MP_CMD_SET_PROPERTY:
4213 case MP_CMD_STEP_PROPERTY:
4214 run_command(mpctx, cmd);
4215 break;
4218 mp_cmd_free(cmd);
4220 if (entry) { // user entered a command that gave a valid entry
4221 if (mpctx->playtree)
4222 // the playtree is always a node with one child. let's clear it
4223 play_tree_free_list(mpctx->playtree->child, 1);
4224 else
4225 // .. or make a brand new playtree
4226 mpctx->playtree = play_tree_new();
4228 if (!mpctx->playtree)
4229 continue; // couldn't make playtree! wait for next command
4231 play_tree_set_child(mpctx->playtree, entry);
4233 /* Make iterator start at the top the of tree. */
4234 mpctx->playtree_iter = play_tree_iter_new(mpctx->playtree,
4235 mpctx->mconfig);
4236 if (!mpctx->playtree_iter)
4237 continue;
4239 // find the first real item in the tree
4240 if (play_tree_iter_step(mpctx->playtree_iter, 0, 0) !=
4241 PLAY_TREE_ITER_ENTRY) {
4242 // no items!
4243 play_tree_iter_free(mpctx->playtree_iter);
4244 mpctx->playtree_iter = NULL;
4245 continue; // wait for next command
4247 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter, 1);
4251 #ifdef CONFIG_ASS
4252 ass_set_style_overrides(mpctx->ass_library, opts->ass_force_style_list);
4253 #endif
4254 if (mpctx->video_out && mpctx->sh_video && mpctx->video_out->config_ok)
4255 vo_control(mpctx->video_out, VOCTRL_RESUME, NULL);
4257 if (mpctx->filename) {
4258 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "\nPlaying %s.\n",
4259 filename_recode(mpctx->filename));
4260 if (use_filename_title && opts->vo_wintitle == NULL)
4261 opts->vo_wintitle = talloc_strdup(NULL,
4262 mp_basename(mpctx->filename));
4265 if (edl_output_filename) {
4266 if (edl_fd)
4267 fclose(edl_fd);
4268 if ((edl_fd = fopen(edl_output_filename, "w")) == NULL) {
4269 mp_tmsg(MSGT_CPLAYER, MSGL_ERR,
4270 "Can't open EDL file [%s] for writing.\n",
4271 filename_recode(edl_output_filename));
4275 //==================== Open VOB-Sub ============================
4277 current_module = "vobsub";
4278 if (opts->vobsub_name) {
4279 vo_vobsub = vobsub_open(opts->vobsub_name, spudec_ifo, 1, &vo_spudec);
4280 if (vo_vobsub == NULL)
4281 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Cannot load subtitles: %s\n",
4282 filename_recode(opts->vobsub_name));
4283 } else if (opts->sub_auto && mpctx->filename) {
4284 char **vob = find_vob_subtitles(opts, mpctx->filename);
4285 for (int i = 0; i < MP_TALLOC_ELEMS(vob); i++) {
4286 vo_vobsub = vobsub_open(vob[i], spudec_ifo, 0, &vo_spudec);
4287 if (vo_vobsub)
4288 break;
4290 talloc_free(vob);
4292 if (vo_vobsub) {
4293 mpctx->initialized_flags |= INITIALIZED_VOBSUB;
4294 vobsub_set_from_lang(vo_vobsub, opts->sub_lang);
4295 mp_property_do("sub_forced_only", M_PROPERTY_SET, &forced_subs_only,
4296 mpctx);
4298 // setup global sub numbering
4299 mpctx->sub_counts[SUB_SOURCE_VOBSUB] =
4300 vobsub_get_indexes_count(vo_vobsub);
4303 //============ Open & Sync STREAM --- fork cache2 ====================
4305 mpctx->stream = NULL;
4306 mpctx->demuxer = NULL;
4307 mpctx->d_audio = NULL;
4308 mpctx->d_video = NULL;
4309 mpctx->d_sub = NULL;
4310 mpctx->sh_audio = NULL;
4311 mpctx->sh_video = NULL;
4313 current_module = "open_stream";
4314 char *stream_filename = mpctx->filename;
4315 #ifdef CONFIG_LIBQUVI
4316 mpctx->resolve_result = mp_resolve_quvi(stream_filename, opts);
4317 #endif
4318 if (mpctx->resolve_result)
4319 stream_filename = mpctx->resolve_result->url;
4320 mpctx->stream = open_stream(stream_filename, opts, &mpctx->file_format);
4321 if (!mpctx->stream) { // error...
4322 mpctx->stop_play = libmpdemux_was_interrupted(mpctx, PT_NEXT_ENTRY);
4323 goto goto_next_file;
4325 mpctx->initialized_flags |= INITIALIZED_STREAM;
4327 if (mpctx->file_format == DEMUXER_TYPE_PLAYLIST) {
4328 mp_msg(MSGT_CPLAYER, MSGL_ERR, "\nThis looks like a playlist, but "
4329 "playlist support will not be used automatically.\n"
4330 "MPlayer's playlist code is unsafe and should only be used with "
4331 "trusted sources.\nPlayback will probably fail.\n\n");
4332 #if 0
4333 play_tree_t *entry;
4334 // Handle playlist
4335 current_module = "handle_playlist";
4336 mp_msg(MSGT_CPLAYER, MSGL_V, "Parsing playlist %s...\n",
4337 filename_recode(mpctx->filename));
4338 entry = parse_playtree(mpctx->stream, mpctx->mconfig, 0);
4339 mpctx->eof = playtree_add_playlist(mpctx, entry);
4340 goto goto_next_file;
4341 #endif
4343 mpctx->stream->start_pos += seek_to_byte;
4345 if (stream_dump_type == 5) {
4346 unsigned char buf[4096];
4347 int len;
4348 FILE *f;
4349 current_module = "dumpstream";
4350 stream_reset(mpctx->stream);
4351 stream_seek(mpctx->stream, mpctx->stream->start_pos);
4352 f = fopen(opts->stream_dump_name, "wb");
4353 if (!f) {
4354 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "Cannot open dump file.\n");
4355 exit_player(mpctx, EXIT_ERROR);
4357 if (opts->chapterrange[0] > 1) {
4358 int chapter = opts->chapterrange[0] - 1;
4359 stream_control(mpctx->stream, STREAM_CTRL_SEEK_TO_CHAPTER, &chapter);
4361 struct stream_dump_progress info;
4362 stream_dump_progress_start(&info);
4363 while (!mpctx->stream->eof && !async_quit_request) {
4364 len = stream_read(mpctx->stream, buf, 4096);
4365 if (len > 0) {
4366 if (fwrite(buf, len, 1, f) != 1) {
4367 mp_tmsg(MSGT_GLOBAL, MSGL_FATAL, "%s: Error writing file.\n", opts->stream_dump_name);
4368 exit_player(mpctx, EXIT_ERROR);
4371 stream_dump_progress(&info, len, mpctx->stream);
4372 if (opts->chapterrange[1] > 0) {
4373 int chapter = -1;
4374 if (stream_control(mpctx->stream,
4375 STREAM_CTRL_GET_CURRENT_CHAPTER, &chapter) == STREAM_OK
4376 && chapter + 1 > opts->chapterrange[1])
4377 break;
4380 if (fclose(f)) {
4381 mp_tmsg(MSGT_GLOBAL, MSGL_FATAL, "%s: Error writing file.\n",
4382 opts->stream_dump_name);
4383 exit_player(mpctx, EXIT_ERROR);
4385 stream_dump_progress_end(&info, opts->stream_dump_name);
4386 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Stream dump complete.\n");
4387 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4390 #ifdef CONFIG_DVDREAD
4391 if (mpctx->stream->type == STREAMTYPE_DVD) {
4392 current_module = "dvd lang->id";
4393 if (opts->audio_lang && opts->audio_id == -1)
4394 opts->audio_id = dvd_aid_from_lang(mpctx->stream, opts->audio_lang);
4395 if (opts->sub_lang && opts->sub_id == -1)
4396 opts->sub_id = dvd_sid_from_lang(mpctx->stream, opts->sub_lang);
4397 // setup global sub numbering
4398 mpctx->sub_counts[SUB_SOURCE_DEMUX] = dvd_number_of_subs(mpctx->stream);
4399 current_module = NULL;
4401 #endif
4403 #ifdef CONFIG_DVDNAV
4404 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4405 current_module = "dvdnav lang->id";
4406 if (opts->audio_lang && opts->audio_id == -1)
4407 opts->audio_id = mp_dvdnav_aid_from_lang(mpctx->stream,
4408 opts->audio_lang);
4409 dvdsub_lang_id = -3;
4410 if (opts->sub_lang && opts->sub_id == -1)
4411 dvdsub_lang_id = opts->sub_id = mp_dvdnav_sid_from_lang(
4412 mpctx->stream, opts->sub_lang);
4413 // setup global sub numbering
4414 mpctx->sub_counts[SUB_SOURCE_DEMUX] = mp_dvdnav_number_of_subs(
4415 mpctx->stream);
4416 current_module = NULL;
4418 #endif
4420 // CACHE2: initial prefill: 20% later: 5% (should be set by -cacheopts)
4421 goto_enable_cache:
4422 current_module = "enable_cache";
4423 int res = stream_enable_cache_percent(mpctx->stream,
4424 opts->stream_cache_size,
4425 opts->stream_cache_min_percent,
4426 opts->stream_cache_seek_min_percent);
4427 if (res == 0)
4428 if ((mpctx->stop_play = libmpdemux_was_interrupted(mpctx,
4429 PT_NEXT_ENTRY)))
4430 goto goto_next_file;
4433 //============ Open DEMUXERS --- DETECT file type =======================
4434 current_module = "demux_open";
4436 mpctx->demuxer = demux_open(opts, mpctx->stream, mpctx->file_format,
4437 opts->audio_id, opts->video_id, opts->sub_id,
4438 mpctx->filename);
4440 // HACK to get MOV Reference Files working
4442 if (mpctx->demuxer && mpctx->demuxer->type == DEMUXER_TYPE_PLAYLIST) {
4443 unsigned char *playlist_entry;
4444 play_tree_t *list = NULL, *entry = NULL;
4446 current_module = "handle_demux_playlist";
4447 while (ds_get_packet(mpctx->demuxer->video, &playlist_entry) > 0) {
4448 char *temp;
4449 const char *bname;
4451 mp_msg(MSGT_CPLAYER, MSGL_V, "Adding file %s to element entry.\n",
4452 filename_recode(playlist_entry));
4454 bname = mp_basename(playlist_entry);
4455 if ((strlen(bname) > 10) && !strncmp(bname, "qt", 2) &&
4456 !strncmp(bname + 3, "gateQT", 6))
4457 continue;
4459 if (!strcmp(playlist_entry, mpctx->filename)) // self-reference
4460 continue;
4462 entry = play_tree_new();
4464 if (mpctx->filename && !strcmp(mp_basename(playlist_entry),
4465 playlist_entry)) { // add reference path of current file
4466 temp = malloc((strlen(mpctx->filename) - strlen(mp_basename(
4467 mpctx->filename)) + strlen(playlist_entry) + 1));
4468 if (temp) {
4469 strncpy(temp, mpctx->filename, strlen(mpctx->filename) -
4470 strlen(mp_basename(mpctx->filename)));
4471 temp[strlen(mpctx->filename) - strlen(mp_basename(
4472 mpctx->filename))] = '\0';
4473 strcat(temp, playlist_entry);
4474 if (!strcmp(temp, mpctx->filename)) {
4475 free(temp);
4476 continue;
4478 play_tree_add_file(entry, temp);
4479 mp_msg(MSGT_CPLAYER, MSGL_V,
4480 "Resolving reference to %s.\n", temp);
4481 free(temp);
4483 } else
4484 play_tree_add_file(entry, playlist_entry);
4486 if (!list)
4487 list = entry;
4488 else
4489 play_tree_append_entry(list, entry);
4491 free_demuxer(mpctx->demuxer);
4492 mpctx->demuxer = NULL;
4494 if (list) {
4495 entry = play_tree_new();
4496 play_tree_set_child(entry, list);
4497 mpctx->stop_play = playtree_add_playlist(mpctx, entry);
4498 goto goto_next_file;
4502 if (!mpctx->demuxer) {
4503 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Failed to recognize file format.\n");
4504 goto goto_next_file;
4507 if (mpctx->demuxer->matroska_data.ordered_chapters)
4508 build_ordered_chapter_timeline(mpctx);
4510 if (mpctx->demuxer->type == DEMUXER_TYPE_EDL)
4511 build_edl_timeline(mpctx);
4513 if (mpctx->timeline) {
4514 mpctx->timeline_part = 0;
4515 mpctx->demuxer = mpctx->timeline[0].source->demuxer;
4517 int part_count = mpctx->num_timeline_parts;
4518 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline contains %d parts from %d "
4519 "sources. Total length %.3f seconds.\n", part_count,
4520 mpctx->num_sources, mpctx->timeline[part_count].start);
4521 mp_msg(MSGT_CPLAYER, MSGL_V, "Source files:\n");
4522 for (int i = 0; i < mpctx->num_sources; i++)
4523 mp_msg(MSGT_CPLAYER, MSGL_V, "%d: %s\n", i,
4524 filename_recode(mpctx->sources[i].demuxer->filename));
4525 mp_msg(MSGT_CPLAYER, MSGL_V, "Timeline parts: (number, start, "
4526 "source_start, source):\n");
4527 for (int i = 0; i < part_count; i++) {
4528 struct timeline_part *p = mpctx->timeline + i;
4529 mp_msg(MSGT_CPLAYER, MSGL_V, "%3d %9.3f %9.3f %3td\n", i, p->start,
4530 p->source_start, p->source - mpctx->sources);
4532 mp_msg(MSGT_CPLAYER, MSGL_V, "END %9.3f\n",
4533 mpctx->timeline[part_count].start);
4536 if (!mpctx->sources) {
4537 mpctx->sources = talloc_ptrtype(NULL, mpctx->sources);
4538 *mpctx->sources = (struct content_source){
4539 .stream = mpctx->stream,
4540 .demuxer = mpctx->demuxer
4542 mpctx->num_sources = 1;
4545 mpctx->initialized_flags |= INITIALIZED_DEMUXER;
4547 #ifdef CONFIG_ASS
4548 if (opts->ass_enabled) {
4549 for (int j = 0; j < mpctx->num_sources; j++) {
4550 struct demuxer *d = mpctx->sources[j].demuxer;
4551 for (int i = 0; i < d->num_attachments; i++) {
4552 struct demux_attachment *att = d->attachments + i;
4553 if (opts->use_embedded_fonts && attachment_is_font(att))
4554 ass_add_font(mpctx->ass_library, att->name, att->data,
4555 att->data_size);
4559 /* libass seems to misbehave if fonts are changed while a renderer
4560 * exists, so we (re)create the renderer after fonts are set.
4562 assert(!mpctx->osd->ass_renderer);
4563 mpctx->osd->ass_renderer = ass_renderer_init(mpctx->osd->ass_library);
4564 if (!mpctx->osd->ass_renderer) {
4565 mp_msg(MSGT_OSD, MSGL_FATAL, "Failed to create libass renderer\n");
4566 exit_player(mpctx, EXIT_ERROR);
4568 mp_ass_configure_fonts(mpctx->osd->ass_renderer);
4569 #endif
4571 current_module = "demux_open2";
4573 mpctx->d_audio = mpctx->demuxer->audio;
4574 mpctx->d_video = mpctx->demuxer->video;
4575 mpctx->d_sub = mpctx->demuxer->sub;
4577 if (ts_prog) {
4578 int tmp = ts_prog;
4579 mp_property_do("switch_program", M_PROPERTY_SET, &tmp, mpctx);
4581 // select audio stream
4582 for (int i = 0; i < mpctx->num_sources; i++)
4583 select_audio(mpctx->sources[i].demuxer->audio->demuxer, opts->audio_id,
4584 opts->audio_lang);
4586 // DUMP STREAMS:
4587 if ((stream_dump_type) && (stream_dump_type < 4)) {
4588 FILE *f;
4589 demux_stream_t *ds = NULL;
4590 current_module = "dump";
4591 // select stream to dump
4592 switch (stream_dump_type) {
4593 case 1: ds = mpctx->d_audio;
4594 break;
4595 case 2: ds = mpctx->d_video;
4596 break;
4597 case 3: ds = mpctx->d_sub;
4598 break;
4600 if (!ds) {
4601 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL,
4602 "dump: FATAL: Selected stream missing!\n");
4603 exit_player(mpctx, EXIT_ERROR);
4605 // disable other streams:
4606 if (mpctx->d_audio && mpctx->d_audio != ds) {
4607 ds_free_packs(mpctx->d_audio);
4608 mpctx->d_audio->id = -2;
4610 if (mpctx->d_video && mpctx->d_video != ds) {
4611 ds_free_packs(mpctx->d_video);
4612 mpctx->d_video->id = -2;
4614 if (mpctx->d_sub && mpctx->d_sub != ds) {
4615 ds_free_packs(mpctx->d_sub);
4616 mpctx->d_sub->id = -2;
4618 // let's dump it!
4619 f = fopen(opts->stream_dump_name, "wb");
4620 if (!f) {
4621 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "Cannot open dump file.\n");
4622 exit_player(mpctx, EXIT_ERROR);
4624 struct stream_dump_progress info;
4625 stream_dump_progress_start(&info);
4626 while (!ds->eof) {
4627 unsigned char *start;
4628 int in_size = ds_get_packet(ds, &start);
4629 if ((mpctx->demuxer->file_format == DEMUXER_TYPE_AVI || mpctx->demuxer->file_format == DEMUXER_TYPE_ASF || mpctx->demuxer->file_format == DEMUXER_TYPE_MOV)
4630 && stream_dump_type == 2)
4631 fwrite(&in_size, 1, 4, f);
4632 if (in_size > 0) {
4633 fwrite(start, in_size, 1, f);
4634 stream_dump_progress(&info, in_size, mpctx->stream);
4636 if (opts->chapterrange[1] > 0) {
4637 int cur_chapter = demuxer_get_current_chapter(mpctx->demuxer, 0);
4638 if (cur_chapter != -1 && cur_chapter + 1 > opts->chapterrange[1])
4639 break;
4642 fclose(f);
4643 stream_dump_progress_end(&info, opts->stream_dump_name);
4644 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Stream dump complete.\n");
4645 exit_player_with_rc(mpctx, EXIT_EOF, 0);
4648 mpctx->sh_audio = mpctx->d_audio->sh;
4649 mpctx->sh_video = mpctx->d_video->sh;
4651 if (mpctx->sh_video) {
4652 current_module = "video_read_properties";
4653 if (!video_read_properties(mpctx->sh_video)) {
4654 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "Video: Cannot read properties.\n");
4655 mpctx->sh_video = mpctx->d_video->sh = NULL;
4656 } else {
4657 mp_tmsg(MSGT_CPLAYER, MSGL_V, "[V] filefmt:%d fourcc:0x%X "
4658 "size:%dx%d fps:%5.3f ftime:=%6.4f\n",
4659 mpctx->demuxer->file_format, mpctx->sh_video->format,
4660 mpctx->sh_video->disp_w, mpctx->sh_video->disp_h,
4661 mpctx->sh_video->fps, mpctx->sh_video->frametime);
4662 if (force_fps) {
4663 mpctx->sh_video->fps = force_fps;
4664 mpctx->sh_video->frametime = 1.0f / mpctx->sh_video->fps;
4666 vo_fps = mpctx->sh_video->fps;
4668 if (!mpctx->sh_video->fps && !force_fps && !opts->correct_pts) {
4669 mp_tmsg(MSGT_CPLAYER, MSGL_ERR, "FPS not specified in the "
4670 "header or invalid, use the -fps option.\n");
4676 if (!mpctx->sh_video && !mpctx->sh_audio) {
4677 mp_tmsg(MSGT_CPLAYER, MSGL_FATAL, "No stream found.\n");
4678 #ifdef CONFIG_DVBIN
4679 if (mpctx->stream->type == STREAMTYPE_DVB) {
4680 int dir;
4681 int v = mpctx->last_dvb_step;
4682 if (v > 0)
4683 dir = DVB_CHANNEL_HIGHER;
4684 else
4685 dir = DVB_CHANNEL_LOWER;
4687 if (dvb_step_channel(mpctx->stream, dir)) {
4688 mpctx->stop_play = PT_NEXT_ENTRY;
4689 mpctx->dvbin_reopen = 1;
4692 #endif
4693 goto goto_next_file; // exit_player(_("Fatal error"));
4696 /* display clip info */
4697 demux_info_print(mpctx->demuxer);
4699 //================= Read SUBTITLES (DVD & TEXT) =========================
4700 if (vo_spudec == NULL && (mpctx->stream->type == STREAMTYPE_DVD
4701 || mpctx->stream->type == STREAMTYPE_DVDNAV))
4702 init_vo_spudec(mpctx);
4704 // after reading video params we should load subtitles because
4705 // we know fps so now we can adjust subtitle time to ~6 seconds AST
4706 // check .sub
4707 current_module = "read_subtitles_file";
4708 double sub_fps = mpctx->sh_video ? mpctx->sh_video->fps : 25;
4709 if (opts->sub_name) {
4710 for (i = 0; opts->sub_name[i] != NULL; ++i)
4711 add_subtitles(mpctx, opts->sub_name[i], sub_fps, 0);
4713 if (opts->sub_auto) { // auto load sub file ...
4714 char **tmp = find_text_subtitles(opts, mpctx->filename);
4715 int nsub = MP_TALLOC_ELEMS(tmp);
4716 for (int i = 0; i < nsub; i++)
4717 add_subtitles(mpctx, tmp[i], sub_fps, 1);
4718 talloc_free(tmp);
4720 if (mpctx->set_of_sub_size > 0)
4721 mpctx->sub_counts[SUB_SOURCE_SUBS] = mpctx->set_of_sub_size;
4723 if (select_subtitle(mpctx)) {
4724 if (mpctx->subdata)
4725 switch (stream_dump_type) {
4726 case 3: list_sub_file(mpctx->subdata);
4727 break;
4728 case 4: dump_mpsub(mpctx->subdata, mpctx->sh_video->fps);
4729 break;
4730 case 6: dump_srt(mpctx->subdata, mpctx->sh_video->fps);
4731 break;
4732 case 7: dump_microdvd(mpctx->subdata, mpctx->sh_video->fps);
4733 break;
4734 case 8: dump_jacosub(mpctx->subdata, mpctx->sh_video->fps);
4735 break;
4736 case 9: dump_sami(mpctx->subdata, mpctx->sh_video->fps);
4737 break;
4741 print_file_properties(mpctx, mpctx->filename);
4743 reinit_video_chain(mpctx);
4744 if (!mpctx->sh_video && !mpctx->sh_audio)
4745 goto goto_next_file;
4747 //================== MAIN: ==========================
4748 current_module = "main";
4750 if (opts->playing_msg) {
4751 char *msg = property_expand_string(mpctx, opts->playing_msg);
4752 mp_msg(MSGT_CPLAYER, MSGL_INFO, "%s", msg);
4753 free(msg);
4757 // Disable the term OSD in verbose mode
4758 if (verbose)
4759 opts->term_osd = 0;
4761 // Make sure old OSD does not stay around
4762 clear_osd_msgs();
4764 //================ SETUP AUDIO ==========================
4766 if (mpctx->sh_audio) {
4767 reinit_audio_chain(mpctx);
4768 if (mpctx->sh_audio && mpctx->sh_audio->codec)
4769 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
4770 "ID_AUDIO_CODEC=%s\n", mpctx->sh_audio->codec->name);
4773 current_module = "av_init";
4775 if (mpctx->sh_video) {
4776 mpctx->sh_video->timer = 0;
4777 if (!ignore_start)
4778 audio_delay += mpctx->sh_video->stream_delay;
4780 if (mpctx->sh_audio) {
4781 if (start_volume >= 0)
4782 mixer_setvolume(&mpctx->mixer, start_volume, start_volume);
4783 if (!ignore_start)
4784 audio_delay -= mpctx->sh_audio->stream_delay;
4787 if (!mpctx->sh_audio) {
4788 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Audio: no sound\n");
4789 mp_msg(MSGT_CPLAYER, MSGL_V, "Freeing %d unused audio chunks.\n",
4790 mpctx->d_audio->packs);
4791 ds_free_packs(mpctx->d_audio); // free buffered chunks
4793 if (!mpctx->sh_video) {
4794 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Video: no video\n");
4795 mp_msg(MSGT_CPLAYER, MSGL_V, "Freeing %d unused video chunks.\n",
4796 mpctx->d_video->packs);
4797 ds_free_packs(mpctx->d_video);
4798 mpctx->d_video->id = -2;
4801 if (!mpctx->sh_video && !mpctx->sh_audio)
4802 goto goto_next_file;
4804 if (force_fps && mpctx->sh_video) {
4805 vo_fps = mpctx->sh_video->fps = force_fps;
4806 mpctx->sh_video->frametime = 1.0f / mpctx->sh_video->fps;
4807 mp_tmsg(MSGT_CPLAYER, MSGL_INFO,
4808 "FPS forced to be %5.3f (ftime: %5.3f).\n",
4809 mpctx->sh_video->fps, mpctx->sh_video->frametime);
4812 mp_input_set_section(mpctx->input, NULL);
4813 //TODO: add desired (stream-based) sections here
4814 if (mpctx->stream->type == STREAMTYPE_TV)
4815 mp_input_set_section(mpctx->input, "tv");
4816 if (mpctx->stream->type == STREAMTYPE_DVDNAV)
4817 mp_input_set_section(mpctx->input, "dvdnav");
4819 //==================== START PLAYING =======================
4821 if (opts->loop_times > 1)
4822 opts->loop_times--;
4823 else if (opts->loop_times == 1)
4824 opts->loop_times = -1;
4826 mp_tmsg(MSGT_CPLAYER, MSGL_INFO, "Starting playback...\n");
4828 total_time_usage_start = GetTimer();
4829 audio_time_usage = 0;
4830 video_time_usage = 0;
4831 vout_time_usage = 0;
4832 total_frame_cnt = 0;
4833 drop_frame_cnt = 0; // fix for multifile fps benchmark
4834 play_n_frames = play_n_frames_mf;
4836 if (play_n_frames == 0) {
4837 mpctx->stop_play = PT_NEXT_ENTRY;
4838 goto goto_next_file;
4841 mpctx->time_frame = 0;
4842 mpctx->drop_message_shown = 0;
4843 mpctx->restart_playback = true;
4844 mpctx->video_pts = 0;
4845 mpctx->last_seek_pts = 0;
4846 mpctx->hrseek_active = false;
4847 mpctx->hrseek_framedrop = false;
4848 mpctx->step_frames = 0;
4849 mpctx->total_avsync_change = 0;
4850 mpctx->last_chapter_seek = -2;
4852 // If there's a timeline force an absolute seek to initialize state
4853 if (opts->seek_to_sec || mpctx->timeline) {
4854 queue_seek(mpctx, MPSEEK_ABSOLUTE, opts->seek_to_sec, 0);
4855 seek(mpctx, mpctx->seek, false);
4856 end_at.pos += opts->seek_to_sec;
4858 if (opts->chapterrange[0] > 0) {
4859 double pts;
4860 if (seek_chapter(mpctx, opts->chapterrange[0] - 1, &pts) >= 0
4861 && pts > -1.0) {
4862 queue_seek(mpctx, MPSEEK_ABSOLUTE, pts, 0);
4863 seek(mpctx, mpctx->seek, false);
4867 if (end_at.type == END_AT_SIZE) {
4868 mp_tmsg(MSGT_CPLAYER, MSGL_WARN,
4869 "Option -endpos in MPlayer does not yet support size units.\n");
4870 end_at.type = END_AT_NONE;
4873 #ifdef CONFIG_DVDNAV
4874 mp_dvdnav_context_free(mpctx);
4875 if (mpctx->stream->type == STREAMTYPE_DVDNAV) {
4876 mp_dvdnav_read_wait(mpctx->stream, 0, 1);
4877 mp_dvdnav_cell_has_changed(mpctx->stream, 1);
4879 #endif
4881 mpctx->seek = (struct seek_params){ 0 };
4882 get_relative_time(mpctx); // reset current delta
4883 // Make sure VO knows current pause state
4884 if (mpctx->sh_video)
4885 vo_control(mpctx->video_out,
4886 mpctx->paused ? VOCTRL_PAUSE : VOCTRL_RESUME, NULL);
4888 while (!mpctx->stop_play)
4889 run_playloop(mpctx);
4891 mp_msg(MSGT_GLOBAL, MSGL_V, "EOF code: %d \n", mpctx->stop_play);
4893 #ifdef CONFIG_DVBIN
4894 if (mpctx->dvbin_reopen) {
4895 mpctx->stop_play = 0;
4896 uninit_player(mpctx, INITIALIZED_ALL - (INITIALIZED_STREAM | INITIALIZED_GETCH2 | (opts->fixed_vo ? INITIALIZED_VO : 0)));
4897 cache_uninit(mpctx->stream);
4898 mpctx->dvbin_reopen = 0;
4899 goto goto_enable_cache;
4901 #endif
4903 goto_next_file: // don't jump here after ao/vo/getch initialization!
4905 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\n");
4907 if (opts->benchmark) {
4908 double tot = video_time_usage + vout_time_usage + audio_time_usage;
4909 double total_time_usage;
4910 total_time_usage_start = GetTimer() - total_time_usage_start;
4911 total_time_usage = (float)total_time_usage_start * 0.000001;
4912 mp_msg(MSGT_CPLAYER, MSGL_INFO, "\nBENCHMARKs: VC:%8.3fs VO:%8.3fs "
4913 "A:%8.3fs Sys:%8.3fs = %8.3fs\n",
4914 video_time_usage, vout_time_usage, audio_time_usage,
4915 total_time_usage - tot, total_time_usage);
4916 if (total_time_usage > 0.0)
4917 mp_msg(MSGT_CPLAYER, MSGL_INFO, "BENCHMARK%%: VC:%8.4f%% "
4918 "VO:%8.4f%% A:%8.4f%% Sys:%8.4f%% = %8.4f%%\n",
4919 100.0 * video_time_usage / total_time_usage,
4920 100.0 * vout_time_usage / total_time_usage,
4921 100.0 * audio_time_usage / total_time_usage,
4922 100.0 * (total_time_usage - tot) / total_time_usage,
4923 100.0);
4924 if (total_frame_cnt && frame_dropping)
4925 mp_msg(MSGT_CPLAYER, MSGL_INFO, "BENCHMARKn: disp: %d (%3.2f fps)"
4926 " drop: %d (%d%%) total: %d (%3.2f fps)\n",
4927 total_frame_cnt - drop_frame_cnt,
4928 (total_time_usage > 0.5) ? ((total_frame_cnt -
4929 drop_frame_cnt) / total_time_usage) : 0,
4930 drop_frame_cnt,
4931 100 * drop_frame_cnt / total_frame_cnt,
4932 total_frame_cnt,
4933 (total_time_usage > 0.5) ?
4934 (total_frame_cnt / total_time_usage) : 0);
4937 // time to uninit all, except global stuff:
4938 int uninitialize_parts = INITIALIZED_ALL;
4939 if (opts->fixed_vo)
4940 uninitialize_parts -= INITIALIZED_VO;
4941 if (opts->gapless_audio && mpctx->stop_play == AT_END_OF_FILE)
4942 uninitialize_parts -= INITIALIZED_AO;
4943 uninit_player(mpctx, uninitialize_parts);
4945 mpctx->file_format = DEMUXER_TYPE_UNKNOWN;
4946 talloc_free(mpctx->resolve_result);
4947 mpctx->resolve_result = NULL;
4949 if (mpctx->set_of_sub_size > 0) {
4950 current_module = "sub_free";
4951 for (i = 0; i < mpctx->set_of_sub_size; ++i) {
4952 sub_free(mpctx->set_of_subtitles[i]);
4953 if (mpctx->set_of_ass_tracks[i])
4954 sub_uninit(mpctx->set_of_ass_tracks[i]);
4955 talloc_free(mpctx->set_of_ass_tracks[i]);
4957 mpctx->set_of_sub_size = 0;
4959 mpctx->vo_sub_last = vo_sub = NULL;
4960 mpctx->subdata = NULL;
4961 #ifdef CONFIG_ASS
4962 if (mpctx->osd->ass_renderer)
4963 ass_renderer_done(mpctx->osd->ass_renderer);
4964 mpctx->osd->ass_renderer = NULL;
4965 ass_clear_fonts(mpctx->ass_library);
4966 #endif
4968 if (!mpctx->stop_play) // In case some goto jumped here...
4969 mpctx->stop_play = PT_NEXT_ENTRY;
4971 int playtree_direction = 1;
4973 if (mpctx->stop_play == PT_NEXT_ENTRY
4974 || mpctx->stop_play == PT_PREV_ENTRY) {
4975 if (play_tree_iter_step(mpctx->playtree_iter, mpctx->play_tree_step, 0)
4976 != PLAY_TREE_ITER_ENTRY) {
4977 play_tree_iter_free(mpctx->playtree_iter);
4978 mpctx->playtree_iter = NULL;
4980 mpctx->play_tree_step = 1;
4981 } else if (mpctx->stop_play == PT_UP_NEXT ||
4982 mpctx->stop_play == PT_UP_PREV) {
4983 int direction = mpctx->stop_play == PT_UP_NEXT ? 1 : -1;
4984 if (mpctx->playtree_iter) {
4985 if (play_tree_iter_up_step(mpctx->playtree_iter, direction, 0) !=
4986 PLAY_TREE_ITER_ENTRY) {
4987 play_tree_iter_free(mpctx->playtree_iter);
4988 mpctx->playtree_iter = NULL;
4991 } else if (mpctx->stop_play == PT_STOP) {
4992 play_tree_iter_free(mpctx->playtree_iter);
4993 mpctx->playtree_iter = NULL;
4994 } else // NEXT PREV SRC
4995 playtree_direction = mpctx->stop_play == PT_PREV_SRC ? -1 : 1;
4997 while (mpctx->playtree_iter != NULL) {
4998 mpctx->filename = play_tree_iter_get_file(mpctx->playtree_iter,
4999 playtree_direction);
5000 if (mpctx->filename == NULL) {
5001 if (play_tree_iter_step(mpctx->playtree_iter, playtree_direction,
5002 0) != PLAY_TREE_ITER_ENTRY) {
5003 play_tree_iter_free(mpctx->playtree_iter);
5004 mpctx->playtree_iter = NULL;
5007 } else
5008 break;
5011 if (mpctx->playtree_iter != NULL || opts->player_idle_mode) {
5012 if (!mpctx->playtree_iter)
5013 mpctx->filename = NULL;
5014 mpctx->stop_play = 0;
5015 goto play_next_file;
5018 exit_player_with_rc(mpctx, EXIT_EOF, 0);
5020 return 1;
5022 #endif /* DISABLE_MAIN */