Update to MPlayer SVN rev 34180.
[vaapi:miks-mplayer.git] / .svn / text-base / mpcommon.c.svn-base
1 /*
2  * This file is part of MPlayer.
3  *
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.
8  *
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.
13  *
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.
17  */
18
19 #if defined(__MINGW32__) || defined(__CYGWIN__)
20 #include <windows.h>
21 #endif
22 #include <stdlib.h>
23 #include "stream/stream.h"
24 #ifdef CONFIG_DVDREAD
25 #include "stream/stream_dvd.h"
26 #endif
27 #ifdef CONFIG_DVDNAV
28 #include "stream/stream_dvdnav.h"
29 #endif
30 #include "libmpdemux/demuxer.h"
31 #include "libmpdemux/stheader.h"
32 #include "codec-cfg.h"
33 #include "osdep/timer.h"
34 #include "osdep/priority.h"
35 #include "path.h"
36 #include "mplayer.h"
37 #include "sub/font_load.h"
38 #include "sub/sub.h"
39 #include "libvo/video_out.h"
40 #include "cpudetect.h"
41 #include "help_mp.h"
42 #include "mp_msg.h"
43 #include "parser-cfg.h"
44 #include "sub/spudec.h"
45 #include "version.h"
46 #include "sub/ass_mp.h"
47 #include "sub/vobsub.h"
48 #include "sub/av_sub.h"
49 #include "libmpcodecs/dec_teletext.h"
50 #include "libavutil/intreadwrite.h"
51 #include "m_option.h"
52 #include "mpcommon.h"
53
54 double sub_last_pts = -303;
55
56 #ifdef CONFIG_ASS
57 ASS_Track* ass_track = 0; // current track to render
58 #endif
59
60 sub_data* subdata = NULL;
61 subtitle* vo_sub_last = NULL;
62 char *spudec_ifo;
63 int forced_subs_only;
64
65 const char *mencoder_version = "MEncoder " VERSION;
66 const char *mplayer_version  = "MPlayer "  VERSION;
67
68 void print_version(const char* name)
69 {
70     mp_msg(MSGT_CPLAYER, MSGL_INFO, MP_TITLE, name);
71
72     /* Test for CPU capabilities (and corresponding OS support) for optimizing */
73     GetCpuCaps(&gCpuCaps);
74 #if ARCH_X86
75     mp_msg(MSGT_CPLAYER, MSGL_V,
76            "CPUflags:  MMX: %d MMX2: %d 3DNow: %d 3DNowExt: %d SSE: %d SSE2: %d SSSE3: %d\n",
77            gCpuCaps.hasMMX, gCpuCaps.hasMMX2,
78            gCpuCaps.has3DNow, gCpuCaps.has3DNowExt,
79            gCpuCaps.hasSSE, gCpuCaps.hasSSE2, gCpuCaps.hasSSSE3);
80 #if CONFIG_RUNTIME_CPUDETECT
81     mp_msg(MSGT_CPLAYER, MSGL_V, "Compiled with runtime CPU detection.\n");
82 #else
83     mp_msg(MSGT_CPLAYER, MSGL_V, "Compiled for x86 CPU with extensions:");
84 if (HAVE_MMX)
85     mp_msg(MSGT_CPLAYER,MSGL_V," MMX");
86 if (HAVE_MMX2)
87     mp_msg(MSGT_CPLAYER,MSGL_V," MMX2");
88 if (HAVE_AMD3DNOW)
89     mp_msg(MSGT_CPLAYER,MSGL_V," 3DNow");
90 if (HAVE_AMD3DNOWEXT)
91     mp_msg(MSGT_CPLAYER,MSGL_V," 3DNowExt");
92 if (HAVE_SSE)
93     mp_msg(MSGT_CPLAYER,MSGL_V," SSE");
94 if (HAVE_SSE2)
95     mp_msg(MSGT_CPLAYER,MSGL_V," SSE2");
96 if (HAVE_SSSE3)
97     mp_msg(MSGT_CPLAYER,MSGL_V," SSSE3");
98 if (HAVE_CMOV)
99     mp_msg(MSGT_CPLAYER,MSGL_V," CMOV");
100     mp_msg(MSGT_CPLAYER,MSGL_V,"\n");
101 #endif /* CONFIG_RUNTIME_CPUDETECT */
102 #endif /* ARCH_X86 */
103 }
104
105 void init_vo_spudec(struct stream *stream, struct sh_video *sh_video, struct sh_sub *sh_sub)
106 {
107     unsigned width, height;
108     spudec_free(vo_spudec);
109     vo_spudec = NULL;
110
111     // we currently can't work without video stream
112     if (!sh_video)
113         return;
114
115     if (spudec_ifo) {
116         unsigned int palette[16];
117         current_module = "spudec_init_vobsub";
118         if (vobsub_parse_ifo(NULL, spudec_ifo, palette, &width, &height, 1, -1, NULL) >= 0)
119             vo_spudec = spudec_new_scaled(palette, width, height, NULL, 0);
120     }
121
122     width  = sh_video->disp_w;
123     height = sh_video->disp_h;
124
125 #ifdef CONFIG_DVDREAD
126     if (vo_spudec == NULL && stream->type == STREAMTYPE_DVD) {
127         current_module = "spudec_init_dvdread";
128         vo_spudec      = spudec_new_scaled(((dvd_priv_t *)(stream->priv))->cur_pgc->palette,
129                                            width, height,
130                                            NULL, 0);
131     }
132 #endif
133
134 #ifdef CONFIG_DVDNAV
135     if (vo_spudec == NULL && stream->type == STREAMTYPE_DVDNAV) {
136         unsigned int *palette = mp_dvdnav_get_spu_clut(stream);
137         current_module = "spudec_init_dvdnav";
138         vo_spudec      = spudec_new_scaled(palette, width, height, NULL, 0);
139     }
140 #endif
141
142     if (vo_spudec == NULL) {
143         current_module = "spudec_init_normal";
144         vo_spudec      = spudec_new_scaled(NULL, width, height,
145                                            sh_sub ? sh_sub->extradata : NULL,
146                                            sh_sub ? sh_sub->extradata_len : 0);
147         spudec_set_font_factor(vo_spudec, font_factor);
148     }
149
150     if (vo_spudec)
151         spudec_set_forced_subs_only(vo_spudec, forced_subs_only);
152 }
153
154 static int is_text_sub(int type)
155 {
156     return type == 't' || type == 'm' || type == 'a';
157 }
158
159 static int is_av_sub(int type)
160 {
161     return type == 'b' || type == 'p' || type == 'x';
162 }
163
164 void update_subtitles(sh_video_t *sh_video, double refpts, demux_stream_t *d_dvdsub, int reset)
165 {
166     double curpts = refpts - sub_delay;
167     unsigned char *packet=NULL;
168     int len;
169     int type = d_dvdsub->sh ? ((sh_sub_t *)d_dvdsub->sh)->type : 'v';
170     static subtitle subs;
171     if (reset) {
172         sub_clear_text(&subs, MP_NOPTS_VALUE);
173         if (vo_sub) {
174             set_osd_subtitle(NULL);
175         }
176         if (vo_spudec) {
177             spudec_reset(vo_spudec);
178             vo_osd_changed(OSDTYPE_SPU);
179         }
180 #ifdef CONFIG_FFMPEG
181         if (is_av_sub(type))
182             reset_avsub(d_dvdsub->sh);
183 #endif
184     }
185     // find sub
186     if (subdata) {
187         if (sub_fps==0) sub_fps = sh_video ? sh_video->fps : 25;
188         current_module = "find_sub";
189         if (refpts > sub_last_pts || refpts < sub_last_pts-1.0) {
190             find_sub(subdata, curpts *
191                      (subdata->sub_uses_time ? 100. : sub_fps));
192             if (vo_sub) vo_sub_last = vo_sub;
193             // FIXME! frame counter...
194             sub_last_pts = refpts;
195         }
196     }
197
198     // DVD sub:
199     if (vo_config_count &&
200         (vobsub_id >= 0 || type == 'v')) {
201         int timestamp;
202         current_module = "spudec";
203         /* Get a sub packet from the DVD or a vobsub */
204         while(1) {
205             // Vobsub
206             len = 0;
207             if (vo_vobsub) {
208                 if (curpts >= 0) {
209                     len = vobsub_get_packet(vo_vobsub, curpts,
210                                             (void**)&packet, &timestamp);
211                     if (len > 0) {
212                         mp_dbg(MSGT_CPLAYER,MSGL_V,"\rVOB sub: len=%d v_pts=%5.3f v_timer=%5.3f sub=%5.3f ts=%d \n",len,refpts,sh_video->timer,timestamp / 90000.0,timestamp);
213                     }
214                 }
215             } else {
216                 // DVD sub
217                 len = ds_get_packet_sub(d_dvdsub, (unsigned char**)&packet, NULL, NULL);
218                 if (len > 0) {
219                     // XXX This is wrong, sh_video->pts can be arbitrarily
220                     // much behind demuxing position. Unfortunately using
221                     // d_video->pts which would have been the simplest
222                     // improvement doesn't work because mpeg specific hacks
223                     // in video.c set d_video->pts to 0.
224                     float x = d_dvdsub->pts - refpts;
225                     if (x > -20 && x < 20) // prevent missing subs on pts reset
226                         timestamp = 90000*d_dvdsub->pts;
227                     else timestamp = 90000*curpts;
228                     mp_dbg(MSGT_CPLAYER, MSGL_V, "\rDVD sub: len=%d  "
229                            "v_pts=%5.3f  s_pts=%5.3f  ts=%d \n", len,
230                            refpts, d_dvdsub->pts, timestamp);
231                 }
232             }
233             if (len<=0 || !packet) break;
234             // create it only here, since with some broken demuxers we might
235             // type = v but no DVD sub and we currently do not change the
236             // "original frame size" ever after init, leading to wrong-sized
237             // PGS subtitles.
238             if (!vo_spudec)
239                 vo_spudec = spudec_new(NULL);
240             if (vo_vobsub || timestamp >= 0)
241                 spudec_assemble(vo_spudec, packet, len, timestamp);
242         }
243     } else if (is_text_sub(type) || is_av_sub(type) || type == 'd') {
244         int orig_type = type;
245         double endpts;
246         if (type == 'd' && !d_dvdsub->demuxer->teletext) {
247             tt_stream_props tsp = {0};
248             void *ptr = &tsp;
249             if (teletext_control(NULL, TV_VBI_CONTROL_START, &ptr) == VBI_CONTROL_TRUE)
250                 d_dvdsub->demuxer->teletext = ptr;
251         }
252         if (d_dvdsub->non_interleaved)
253             ds_get_next_pts(d_dvdsub);
254         while (1) {
255             double subpts = curpts;
256             type = orig_type;
257             len = ds_get_packet_sub(d_dvdsub, &packet, &subpts, &endpts);
258             if (len < 0)
259                 break;
260             if (is_av_sub(type)) {
261 #ifdef CONFIG_FFMPEG
262                 type = decode_avsub(d_dvdsub->sh, &packet, &len, &subpts, &endpts);
263                 if (type < 0)
264                     mp_msg(MSGT_SPUDEC, MSGL_WARN, "lavc failed decoding subtitle\n");
265                 if (type <= 0)
266 #endif
267                     continue;
268             }
269             if (type == 'm') {
270                 if (len < 2) continue;
271                 len = FFMIN(len - 2, AV_RB16(packet));
272                 packet += 2;
273             }
274             if (type == 'd') {
275                 if (d_dvdsub->demuxer->teletext) {
276                     uint8_t *p = packet;
277                     p++;
278                     len--;
279                     while (len >= 46) {
280                         int sublen = p[1];
281                         if (p[0] == 2 || p[0] == 3)
282                             teletext_control(d_dvdsub->demuxer->teletext,
283                                 TV_VBI_CONTROL_DECODE_DVB, p + 2);
284                         p   += sublen + 2;
285                         len -= sublen + 2;
286                     }
287                 }
288                 continue;
289             }
290 #ifdef CONFIG_ASS
291             if (ass_enabled) {
292                 sh_sub_t* sh = d_dvdsub->sh;
293                 ass_track = sh ? sh->ass_track : NULL;
294                 if (!ass_track) continue;
295                 if (type == 'a') { // ssa/ass subs with libass
296                     if (len > 10 && memcmp(packet, "Dialogue: ", 10) == 0)
297                         ass_process_data(ass_track, packet, len);
298                     else
299                         ass_process_chunk(ass_track, packet, len,
300                                           (long long)(subpts*1000 + 0.5),
301                                           (long long)((endpts-subpts)*1000 + 0.5));
302                 } else { // plaintext subs with libass
303                     if (subpts != MP_NOPTS_VALUE) {
304                         subtitle tmp_subs = {0};
305                         if (endpts == MP_NOPTS_VALUE) endpts = subpts + 3;
306                         sub_add_text(&tmp_subs, packet, len, endpts, 0);
307                         tmp_subs.start = subpts * 100;
308                         tmp_subs.end = endpts * 100;
309                         ass_process_subtitle(ass_track, &tmp_subs);
310                         sub_clear_text(&tmp_subs, MP_NOPTS_VALUE);
311                     }
312                 }
313                 continue;
314             }
315 #endif
316             if (subpts != MP_NOPTS_VALUE) {
317                 if (endpts == MP_NOPTS_VALUE)
318                     sub_clear_text(&subs, MP_NOPTS_VALUE);
319                 if (type == 'a') { // ssa/ass subs without libass => convert to plaintext
320                     int i;
321                     unsigned char* p = packet;
322                     int skip_commas = 8;
323                     if (len > 10 && memcmp(packet, "Dialogue: ", 10) == 0)
324                         skip_commas = 9;
325                     for (i=0; i < skip_commas && *p != '\0'; p++)
326                         if (*p == ',')
327                             i++;
328                     if (*p == '\0')  /* Broken line? */
329                         continue;
330                     len -= p - packet;
331                     packet = p;
332                 }
333                 if (endpts == MP_NOPTS_VALUE) endpts = subpts + 4;
334                 sub_add_text(&subs, packet, len, endpts, 1);
335                 set_osd_subtitle(&subs);
336             }
337             if (d_dvdsub->non_interleaved)
338                 ds_get_next_pts(d_dvdsub);
339         }
340         if (sub_clear_text(&subs, curpts))
341             set_osd_subtitle(&subs);
342     }
343     if (vo_spudec) {
344         spudec_heartbeat(vo_spudec, 90000*curpts);
345         if (spudec_changed(vo_spudec))
346             vo_osd_changed(OSDTYPE_SPU);
347     }
348
349     current_module=NULL;
350 }
351
352 void update_teletext(sh_video_t *sh_video, demuxer_t *demuxer, int reset)
353 {
354     int page_changed;
355
356     if (!demuxer->teletext)
357         return;
358
359     //Also forcing page update when such ioctl is not supported or call error occured
360     if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_IS_CHANGED,&page_changed)!=VBI_CONTROL_TRUE)
361         page_changed=1;
362
363     if(!page_changed)
364         return;
365
366     if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_GET_VBIPAGE,&vo_osd_teletext_page)!=VBI_CONTROL_TRUE)
367         vo_osd_teletext_page=NULL;
368     if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_GET_HALF_PAGE,&vo_osd_teletext_half)!=VBI_CONTROL_TRUE)
369         vo_osd_teletext_half=0;
370     if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_GET_MODE,&vo_osd_teletext_mode)!=VBI_CONTROL_TRUE)
371         vo_osd_teletext_mode=0;
372     if(teletext_control(demuxer->teletext,TV_VBI_CONTROL_GET_FORMAT,&vo_osd_teletext_format)!=VBI_CONTROL_TRUE)
373         vo_osd_teletext_format=0;
374     vo_osd_changed(OSDTYPE_TELETEXT);
375
376     teletext_control(demuxer->teletext,TV_VBI_CONTROL_MARK_UNCHANGED,NULL);
377 }
378
379 int select_audio(demuxer_t* demuxer, int audio_id, char* audio_lang)
380 {
381     if (audio_id == -1 && audio_lang)
382         audio_id = demuxer_audio_track_by_lang(demuxer, audio_lang);
383     if (audio_id == -1)
384         audio_id = demuxer_default_audio_track(demuxer);
385     if (audio_id != -1) // -1 (automatic) is the default behaviour of demuxers
386         demuxer_switch_audio(demuxer, audio_id);
387     if (audio_id == -2) { // some demuxers don't yet know how to switch to no sound
388         demuxer->audio->id = -2;
389         demuxer->audio->sh = NULL;
390     }
391     return demuxer->audio->id;
392 }
393
394 /* Parse -noconfig common to both programs */
395 int disable_system_conf=0;
396 int disable_user_conf=0;
397 #ifdef CONFIG_GUI
398 int disable_gui_conf=0;
399 #endif /* CONFIG_GUI */
400
401 /* Disable all configuration files */
402 static void noconfig_all(void)
403 {
404     disable_system_conf = 1;
405     disable_user_conf = 1;
406 #ifdef CONFIG_GUI
407     disable_gui_conf = 1;
408 #endif /* CONFIG_GUI */
409 }
410
411 m_config_t *mconfig;
412
413 int cfg_inc_verbose(m_option_t *conf)
414 {
415     ++verbose;
416     return 0;
417 }
418
419 int cfg_include(m_option_t *conf, const char *filename)
420 {
421     return m_config_parse_config_file(mconfig, filename);
422 }
423
424 const m_option_t noconfig_opts[] = {
425     {"all", noconfig_all, CONF_TYPE_FUNC, CONF_GLOBAL|CONF_NOCFG|CONF_PRE_PARSE, 0, 0, NULL},
426     {"system", &disable_system_conf, CONF_TYPE_FLAG, CONF_GLOBAL|CONF_NOCFG|CONF_PRE_PARSE, 0, 1, NULL},
427     {"user", &disable_user_conf, CONF_TYPE_FLAG, CONF_GLOBAL|CONF_NOCFG|CONF_PRE_PARSE, 0, 1, NULL},
428 #ifdef CONFIG_GUI
429     {"gui", &disable_gui_conf, CONF_TYPE_FLAG, CONF_GLOBAL|CONF_NOCFG|CONF_PRE_PARSE, 0, 1, NULL},
430 #endif /* CONFIG_GUI */
431     {NULL, NULL, 0, 0, 0, 0, NULL}
432 };
433
434 /**
435  * Initialization code to be run at the very start, must not depend
436  * on option values.
437  */
438 void common_preinit(void)
439 {
440     InitTimer();
441     srand(GetTimerMS());
442
443     mp_msg_init();
444 }
445
446 /**
447  * Code to fix any kind of insane defaults some OS might have.
448  * Currently mostly fixes for insecure-by-default Windows.
449  */
450 static void sanitize_os(void)
451 {
452 #if defined(__MINGW32__) || defined(__CYGWIN__)
453     HMODULE kernel32 = GetModuleHandle("Kernel32.dll");
454     BOOL WINAPI (*setDEP)(DWORD) = NULL;
455     BOOL WINAPI (*setDllDir)(LPCTSTR) = NULL;
456     if (kernel32) {
457         setDEP = GetProcAddress(kernel32, "SetProcessDEPPolicy");
458         setDllDir = GetProcAddress(kernel32, "SetDllDirectoryA");
459     }
460     if (setDEP) setDEP(3);
461     if (setDllDir) setDllDir("");
462     // stop Windows from showing all kinds of annoying error dialogs
463     SetErrorMode(0x8003);
464     // request 1ms timer resolution
465     timeBeginPeriod(1);
466 #endif
467 }
468
469 /**
470  * Initialization code to be run after command-line parsing.
471  */
472 int common_init(void)
473 {
474 #if (defined(__MINGW32__) || defined(__CYGWIN__)) && defined(CONFIG_WIN32DLL)
475     set_path_env();
476 #endif
477     sanitize_os();
478
479 #ifdef CONFIG_PRIORITY
480     set_priority();
481 #endif
482
483     if (codec_path)
484         set_codec_path(codec_path);
485
486     /* Check codecs.conf. */
487     if (!codecs_file || !parse_codec_cfg(codecs_file)) {
488         char *conf_path = get_path("codecs.conf");
489         if (!parse_codec_cfg(conf_path)) {
490             if (!parse_codec_cfg(MPLAYER_CONFDIR "/codecs.conf")) {
491                 if (!parse_codec_cfg(NULL)) {
492                     free(conf_path);
493                     return 0;
494                 }
495                 mp_msg(MSGT_CPLAYER, MSGL_V, "Using built-in default codecs.conf.\n");
496             }
497         }
498         free(conf_path);
499     }
500
501     // check font
502 #ifdef CONFIG_FREETYPE
503     init_freetype();
504 #endif
505 #ifdef CONFIG_FONTCONFIG
506     if (font_fontconfig <= 0)
507 #endif
508     {
509 #ifdef CONFIG_BITMAP_FONT
510         if (font_name) {
511             vo_font = read_font_desc(font_name, font_factor, verbose>1);
512             if (!vo_font)
513                 mp_msg(MSGT_CPLAYER,MSGL_ERR,MSGTR_CantLoadFont,
514                        filename_recode(font_name));
515         } else {
516             // try default:
517             char *desc_path = get_path("font/font.desc");
518             vo_font = read_font_desc(desc_path, font_factor, verbose>1);
519             free(desc_path);
520             if (!vo_font)
521                 vo_font = read_font_desc(MPLAYER_DATADIR "/font/font.desc", font_factor, verbose>1);
522         }
523         if (sub_font_name)
524             sub_font = read_font_desc(sub_font_name, font_factor, verbose>1);
525         else
526             sub_font = vo_font;
527 #endif
528     }
529
530     vo_init_osd();
531
532 #ifdef CONFIG_ASS
533     ass_library = ass_init();
534 #endif
535     return 1;
536 }
537
538 /// Returns a_pts
539 double calc_a_pts(sh_audio_t *sh_audio, demux_stream_t *d_audio)
540 {
541     double a_pts;
542     if(!sh_audio || !d_audio)
543         return MP_NOPTS_VALUE;
544     // first calculate the end pts of audio that has been output by decoder
545     a_pts = sh_audio->pts;
546     // If we cannot get any useful information at all from the demuxer layer
547     // just count the decoded bytes. This is still better than constantly
548     // resetting to 0.
549     if (sh_audio->pts_bytes && a_pts == MP_NOPTS_VALUE &&
550         !d_audio->pts && !sh_audio->i_bps)
551         a_pts = 0;
552     if (a_pts != MP_NOPTS_VALUE)
553         // Good, decoder supports new way of calculating audio pts.
554         // sh_audio->pts is the timestamp of the latest input packet with
555         // known pts that the decoder has decoded. sh_audio->pts_bytes is
556         // the amount of bytes the decoder has written after that timestamp.
557         a_pts += sh_audio->pts_bytes / (double) sh_audio->o_bps;
558     else {
559         // Decoder doesn't support new way of calculating pts (or we're
560         // being called before it has decoded anything with known timestamp).
561         // Use the old method of audio pts calculation: take the timestamp
562         // of last packet with known pts the decoder has read data from,
563         // and add amount of bytes read after the beginning of that packet
564         // divided by input bps. This will be inaccurate if the input/output
565         // ratio is not constant for every audio packet or if it is constant
566         // but not accurately known in sh_audio->i_bps.
567
568         a_pts = d_audio->pts;
569         // ds_tell_pts returns bytes read after last timestamp from
570         // demuxing layer, decoder might use sh_audio->a_in_buffer for bytes
571         // it has read but not decoded
572         if (sh_audio->i_bps)
573             a_pts += (ds_tell_pts(d_audio) - sh_audio->a_in_buffer_len) /
574                      (double)sh_audio->i_bps;
575     }
576     return a_pts;
577 }