]> git.sesse.net Git - vlc/blob - modules/codec/kate.c
7def25f54889f7a2d3e9a1c22613a0620cc9a0bc
[vlc] / modules / codec / kate.c
1 /*****************************************************************************
2  * kate.c : a decoder for the kate bitstream format
3  *****************************************************************************
4  * Copyright (C) 2000-2008 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Vincent Penquerc'h <ogg.k.ogg.k@googlemail.com>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22  *****************************************************************************/
23
24 /*****************************************************************************
25  * Preamble
26  *****************************************************************************/
27 #ifdef HAVE_CONFIG_H
28 # include "config.h"
29 #endif
30
31 #include <vlc_common.h>
32 #include <vlc_plugin.h>
33 #include <vlc_input.h>
34 #include <vlc_codec.h>
35 #include <vlc_osd.h>
36 #include "../demux/xiph.h"
37
38 #include <kate/kate.h>
39 #ifdef HAVE_TIGER
40 # include <tiger/tiger.h>
41 #endif
42
43 /* #define ENABLE_PACKETIZER */
44 /* #define ENABLE_PROFILE */
45
46 #ifdef ENABLE_PROFILE
47 # define PROFILE_START(name) int64_t profile_start_##name = mdate()
48 # define PROFILE_STOP(name) fprintf( stderr, #name ": %f ms\n", (mdate() - profile_start_##name)/1000.0f )
49 #else
50 # define PROFILE_START(name) ((void)0)
51 # define PROFILE_STOP(name) ((void)0)
52 #endif
53
54 #define CHECK_TIGER_RET( statement )                                   \
55     do                                                                 \
56     {                                                                  \
57         int i_ret = (statement);                                       \
58         if( i_ret < 0 )                                                \
59         {                                                              \
60             msg_Dbg( p_dec, "Error in " #statement ": %d", i_ret );    \
61         }                                                              \
62     } while( 0 )
63
64 /*****************************************************************************
65  * decoder_sys_t : decoder descriptor
66  *****************************************************************************/
67 struct decoder_sys_t
68 {
69 #ifdef ENABLE_PACKETIZER
70     /* Module mode */
71     bool b_packetizer;
72 #endif
73
74     /*
75      * Input properties
76      */
77     bool b_has_headers;
78
79     /*
80      * Kate properties
81      */
82     bool           b_ready;
83     kate_info      ki;
84     kate_comment   kc;
85     kate_state     k;
86
87     /*
88      * Common properties
89      */
90     mtime_t i_pts;
91     mtime_t i_max_stop;
92
93     /* decoder_sys_t is shared between decoder and spu units */
94     vlc_mutex_t lock;
95     int         i_refcount;
96
97 #ifdef HAVE_TIGER
98     /*
99      * Tiger properties
100      */
101     tiger_renderer    *p_tr;
102     bool               b_dirty;
103
104     uint32_t           i_tiger_default_font_color;
105     uint32_t           i_tiger_default_background_color;
106     tiger_font_effect  e_tiger_default_font_effect;
107     double             f_tiger_default_font_effect_strength;
108     char              *psz_tiger_default_font_desc;
109     double             f_tiger_quality;
110 #endif
111
112     /*
113      * Options
114      */
115     bool   b_formatted;
116     bool   b_use_tiger;
117 };
118
119 struct subpicture_sys_t
120 {
121     decoder_sys_t *p_dec_sys;
122     mtime_t        i_start;
123 };
124
125
126 /*
127  * This is a global list of existing decoders.
128  * The reason for this list is that:
129  *  - I want to be able to reconfigure Tiger when user prefs change
130  *  - User prefs are variables which are not specific to a decoder (eg, if
131  *    there are several decoders, there will still be one set of variables)
132  *  - A callback set on those will not be passed a pointer to the decoder
133  *    (as the decoder isn't known, and there could be multiple ones)
134  *  - Creating variables in the decoder will create different ones, with
135  *    values copied from the relevant user pref, so a callback on those
136  *    won't be called when the user pref is changed
137  * Therefore, each decoder will register/unregister itself with this list,
138  * callbacks will be set for the user prefs, and these will in turn walk
139  * through this list and tell each decoder to update the relevant variable.
140  * HOWEVER.
141  * VLC's variable system is still in my way as I can't get the value of
142  * the user pref variables at decoder start *unless* I create my own vars
143  * which inherit from the user ones, but those are utterly useless after
144  * that first use, since they'll be detached from the ones the user can
145  * change. So, I create them, read their values, and then destroy them.
146  */
147 static vlc_mutex_t kate_decoder_list_mutex = VLC_STATIC_MUTEX;
148 static size_t kate_decoder_list_size = 0;
149 static decoder_t **kate_decoder_list = NULL;
150
151 /*****************************************************************************
152  * Local prototypes
153  *****************************************************************************/
154 static int  OpenDecoder   ( vlc_object_t * );
155 static void CloseDecoder  ( vlc_object_t * );
156 #ifdef ENABLE_PACKETIZER
157 static int OpenPacketizer( vlc_object_t *p_this );
158 #endif
159
160 static subpicture_t *DecodeBlock( decoder_t *p_dec, block_t **pp_block );
161 static int ProcessHeaders( decoder_t *p_dec );
162 static subpicture_t *ProcessPacket( decoder_t *p_dec, kate_packet *p_kp,
163                             block_t **pp_block );
164 static subpicture_t *DecodePacket( decoder_t *p_dec, kate_packet *p_kp,
165                             block_t *p_block );
166 static void ParseKateComments( decoder_t * );
167 static subpicture_t *SetupSimpleKateSPU( decoder_t *p_dec, subpicture_t *p_spu,
168                             const kate_event *ev );
169 static void DecSysRelease( decoder_sys_t *p_sys );
170 static void DecSysHold( decoder_sys_t *p_sys );
171 #ifdef HAVE_TIGER
172 static uint32_t GetTigerColor( decoder_t *p_dec, const char *psz_prefix );
173 static char *GetTigerString( decoder_t *p_dec, const char *psz_name );
174 static int GetTigerInteger( decoder_t *p_dec, const char *psz_name );
175 static double GetTigerFloat( decoder_t *p_dec, const char *psz_name );
176 static void UpdateTigerFontColor( decoder_t *p_dec );
177 static void UpdateTigerBackgroundColor( decoder_t *p_dec );
178 static void UpdateTigerFontEffect( decoder_t *p_dec );
179 static void UpdateTigerQuality( decoder_t *p_dec );
180 static void UpdateTigerFontDesc( decoder_t *p_dec );
181 static int TigerConfigurationCallback( vlc_object_t *p_this, const char *psz_var,
182                                        vlc_value_t oldvar, vlc_value_t newval,
183                                        void *p_data );
184 static int OnConfigurationChanged( decoder_t *p_dec, const char *psz_var,
185                                    vlc_value_t oldval, vlc_value_t newval);
186 #endif
187
188 #define DEFAULT_NAME "Default"
189 #define MAX_LINE 8192
190
191 /*****************************************************************************
192  * Module descriptor.
193  *****************************************************************************/
194
195 #define FORMAT_TEXT N_("Formatted Subtitles")
196 #define FORMAT_LONGTEXT N_("Kate streams allow for text formatting. " \
197  "VLC partly implements this, but you can choose to disable all formatting." \
198  "Note that this has no effect is rendering via Tiger is enabled.")
199
200 #ifdef HAVE_TIGER
201
202 static const tiger_font_effect pi_font_effects[] = { tiger_font_plain, tiger_font_shadow, tiger_font_outline };
203 static const char * const ppsz_font_effect_names[] = { N_("None"), N_("Shadow"), N_("Outline") };
204
205 /* nicked off freetype.c */
206 static const int pi_color_values[] = {
207   0x00000000, 0x00808080, 0x00C0C0C0, 0x00FFFFFF, 0x00800000,
208   0x00FF0000, 0x00FF00FF, 0x00FFFF00, 0x00808000, 0x00008000, 0x00008080,
209   0x0000FF00, 0x00800080, 0x00000080, 0x000000FF, 0x0000FFFF };
210 static const char *const ppsz_color_descriptions[] = {
211   N_("Black"), N_("Gray"), N_("Silver"), N_("White"), N_("Maroon"),
212   N_("Red"), N_("Fuchsia"), N_("Yellow"), N_("Olive"), N_("Green"), N_("Teal"),
213   N_("Lime"), N_("Purple"), N_("Navy"), N_("Blue"), N_("Aqua") };
214
215 #define TIGER_TEXT N_("Use Tiger for rendering")
216 #define TIGER_LONGTEXT N_("Kate streams can be rendered using the Tiger library. " \
217  "Disabling this will only render static text and bitmap based streams.")
218
219 #define TIGER_QUALITY_DEFAULT 1.0
220 #define TIGER_QUALITY_TEXT N_("Rendering quality")
221 #define TIGER_QUALITY_LONGTEXT N_("Select rendering quality, at the expense of speed. " \
222  "0 is fastest, 1 is highest quality.")
223
224 #define TIGER_DEFAULT_FONT_EFFECT_DEFAULT 0
225 #define TIGER_DEFAULT_FONT_EFFECT_TEXT N_("Default font effect")
226 #define TIGER_DEFAULT_FONT_EFFECT_LONGTEXT N_("Add a font effect to text to improve readability " \
227  "against different backgrounds.")
228
229 #define TIGER_DEFAULT_FONT_EFFECT_STRENGTH_DEFAULT 0.5
230 #define TIGER_DEFAULT_FONT_EFFECT_STRENGTH_TEXT N_("Default font effect strength")
231 #define TIGER_DEFAULT_FONT_EFFECT_STRENGTH_LONGTEXT N_("How pronounced to make the chosen font effect " \
232  "(effect dependent).")
233
234 #define TIGER_DEFAULT_FONT_DESC_DEFAULT ""
235 #define TIGER_DEFAULT_FONT_DESC_TEXT N_("Default font description")
236 #define TIGER_DEFAULT_FONT_DESC_LONGTEXT N_("Which font description to use if the Kate stream " \
237  "does not specify particular font parameters (name, size, etc) to use. " \
238  "A blank name will let Tiger choose font parameters where appropriate.")
239
240 #define TIGER_DEFAULT_FONT_COLOR_DEFAULT 0x00ffffff
241 #define TIGER_DEFAULT_FONT_COLOR_TEXT N_("Default font color")
242 #define TIGER_DEFAULT_FONT_COLOR_LONGTEXT N_("Default font color to use if the Kate stream " \
243  "does not specify a particular font color to use.")
244
245 #define TIGER_DEFAULT_FONT_ALPHA_DEFAULT 0xff
246 #define TIGER_DEFAULT_FONT_ALPHA_TEXT N_("Default font alpha")
247 #define TIGER_DEFAULT_FONT_ALPHA_LONGTEXT N_("Transparency of the default font color if the Kate stream " \
248  "does not specify a particular font color to use.")
249
250 #define TIGER_DEFAULT_BACKGROUND_COLOR_DEFAULT 0x00ffffff
251 #define TIGER_DEFAULT_BACKGROUND_COLOR_TEXT N_("Default background color")
252 #define TIGER_DEFAULT_BACKGROUND_COLOR_LONGTEXT N_("Default background color if the Kate stream " \
253  "does not specify a background color to use.")
254
255 #define TIGER_DEFAULT_BACKGROUND_ALPHA_DEFAULT 0
256 #define TIGER_DEFAULT_BACKGROUND_ALPHA_TEXT N_("Default background alpha")
257 #define TIGER_DEFAULT_BACKGROUND_ALPHA_LONGTEXT N_("Transparency of the default background color if the Kate stream " \
258  "does not specify a particular background color to use.")
259
260 #endif
261
262 #define HELP_TEXT N_( \
263     "Kate is a codec for text and image based overlays.\n" \
264     "The Tiger rendering library is needed to render complex Kate streams, " \
265     "but VLC can still render static text and image based subtitles if " \
266     "it is not available.\n" \
267     "Note that changing settings below will not take effect until a new stream is played. " \
268     "This will hopefully be fixed soon." \
269     )
270
271 vlc_module_begin ()
272     set_shortname( N_("Kate"))
273     set_description( N_("Kate overlay decoder") )
274     set_help( HELP_TEXT )
275     set_capability( "decoder", 50 )
276     set_callbacks( OpenDecoder, CloseDecoder )
277     set_category( CAT_INPUT )
278     set_subcategory( SUBCAT_INPUT_SCODEC )
279     add_shortcut( "kate" )
280
281     add_bool( "kate-formatted", true, NULL, FORMAT_TEXT, FORMAT_LONGTEXT,
282               true )
283
284 #ifdef HAVE_TIGER
285     add_bool( "kate-use-tiger", true, NULL, TIGER_TEXT, TIGER_LONGTEXT,
286               true )
287     add_float_with_range( "kate-tiger-quality",
288                           TIGER_QUALITY_DEFAULT, 0.0f, 1.0f, TigerConfigurationCallback,
289                           TIGER_QUALITY_TEXT, TIGER_QUALITY_LONGTEXT,
290                           true )
291
292     set_section( N_("Tiger rendering defaults"), NULL );
293     add_string( "kate-tiger-default-font-desc",
294                 TIGER_DEFAULT_FONT_DESC_DEFAULT, TigerConfigurationCallback,
295                 TIGER_DEFAULT_FONT_DESC_TEXT, TIGER_DEFAULT_FONT_DESC_LONGTEXT, true);
296     add_integer_with_range( "kate-tiger-default-font-effect",
297                             TIGER_DEFAULT_FONT_EFFECT_DEFAULT,
298                             0, sizeof(pi_font_effects)/sizeof(pi_font_effects[0])-1, TigerConfigurationCallback,
299                             TIGER_DEFAULT_FONT_EFFECT_TEXT, TIGER_DEFAULT_FONT_EFFECT_LONGTEXT,
300                             true )
301     change_integer_list( pi_font_effects, ppsz_font_effect_names, NULL );
302     add_float_with_range( "kate-tiger-default-font-effect-strength",
303               TIGER_DEFAULT_FONT_EFFECT_STRENGTH_DEFAULT, 0.0f, 1.0f, TigerConfigurationCallback,
304               TIGER_DEFAULT_FONT_EFFECT_STRENGTH_TEXT, TIGER_DEFAULT_FONT_EFFECT_STRENGTH_LONGTEXT,
305               true )
306     add_integer_with_range( "kate-tiger-default-font-color",
307                             TIGER_DEFAULT_FONT_COLOR_DEFAULT, 0, 0x00ffffff, TigerConfigurationCallback,
308                             TIGER_DEFAULT_FONT_COLOR_TEXT, TIGER_DEFAULT_FONT_COLOR_LONGTEXT,
309                             true);
310     change_integer_list( pi_color_values, ppsz_color_descriptions, NULL );
311     add_integer_with_range( "kate-tiger-default-font-alpha",
312                             TIGER_DEFAULT_FONT_ALPHA_DEFAULT, 0, 255, TigerConfigurationCallback,
313                             TIGER_DEFAULT_FONT_ALPHA_TEXT, TIGER_DEFAULT_FONT_ALPHA_LONGTEXT,
314                             true);
315     add_integer_with_range( "kate-tiger-default-background-color",
316                             TIGER_DEFAULT_BACKGROUND_COLOR_DEFAULT, 0, 0x00ffffff, TigerConfigurationCallback,
317                             TIGER_DEFAULT_BACKGROUND_COLOR_TEXT, TIGER_DEFAULT_BACKGROUND_COLOR_LONGTEXT,
318                             true);
319     change_integer_list( pi_color_values, ppsz_color_descriptions, NULL );
320     add_integer_with_range( "kate-tiger-default-background-alpha",
321                             TIGER_DEFAULT_BACKGROUND_ALPHA_DEFAULT, 0, 255, TigerConfigurationCallback,
322                             TIGER_DEFAULT_BACKGROUND_ALPHA_TEXT, TIGER_DEFAULT_BACKGROUND_ALPHA_LONGTEXT,
323                             true);
324 #endif
325
326 #ifdef ENABLE_PACKETIZER
327     add_submodule ()
328     set_description( N_("Kate text subtitles packetizer") )
329     set_capability( "packetizer", 100 )
330     set_callbacks( OpenPacketizer, CloseDecoder )
331     add_shortcut( "kate" )
332 #endif
333
334 vlc_module_end ()
335
336 /*****************************************************************************
337  * OpenDecoder: probe the decoder and return score
338  *****************************************************************************
339  * Tries to launch a decoder and return score so that the interface is able
340  * to chose.
341  *****************************************************************************/
342 static int OpenDecoder( vlc_object_t *p_this )
343 {
344     decoder_t     *p_dec = (decoder_t*)p_this;
345     decoder_sys_t *p_sys;
346
347     if( p_dec->fmt_in.i_codec != VLC_CODEC_KATE )
348     {
349         return VLC_EGENERIC;
350     }
351
352     msg_Dbg( p_dec, "kate: OpenDecoder");
353
354     /* Set callbacks */
355     p_dec->pf_decode_sub = (subpicture_t *(*)(decoder_t *, block_t **))
356         DecodeBlock;
357     p_dec->pf_packetize    = (block_t *(*)(decoder_t *, block_t **))
358         DecodeBlock;
359
360     /* Allocate the memory needed to store the decoder's structure */
361     if( ( p_dec->p_sys = p_sys = malloc(sizeof(*p_sys)) ) == NULL )
362         return VLC_ENOMEM;
363
364     vlc_mutex_init( &p_sys->lock );
365     p_sys->i_refcount = 0;
366     DecSysHold( p_sys );
367
368     /* init of p_sys */
369 #ifdef ENABLE_PACKETIZER
370     p_sys->b_packetizer = false;
371 #endif
372     p_sys->b_ready = false;
373     p_sys->i_pts =
374     p_sys->i_max_stop = VLC_TS_INVALID;
375
376     kate_comment_init( &p_sys->kc );
377     kate_info_init( &p_sys->ki );
378
379     p_sys->b_has_headers = false;
380
381     /* retrieve options */
382     p_sys->b_formatted = var_CreateGetBool( p_dec, "kate-formatted" );
383
384     vlc_mutex_lock( &kate_decoder_list_mutex );
385
386 #ifdef HAVE_TIGER
387
388     p_sys->b_use_tiger = var_CreateGetBool( p_dec, "kate-use-tiger" );
389
390     p_sys->p_tr = NULL;
391
392     /* get initial value of configuration */
393     p_sys->i_tiger_default_font_color = GetTigerColor( p_dec, "kate-tiger-default-font" );
394     p_sys->i_tiger_default_background_color = GetTigerColor( p_dec, "kate-tiger-default-background" );
395     p_sys->e_tiger_default_font_effect = GetTigerInteger( p_dec, "kate-tiger-default-font-effect" );
396     p_sys->f_tiger_default_font_effect_strength = GetTigerFloat( p_dec, "kate-tiger-default-font-effect-strength" );
397     p_sys->psz_tiger_default_font_desc = GetTigerString( p_dec, "kate-tiger-default-font-desc" );
398     p_sys->f_tiger_quality = GetTigerFloat( p_dec, "kate-tiger-quality" );
399
400     if( p_sys->b_use_tiger )
401     {
402         int i_ret = tiger_renderer_create( &p_sys->p_tr );
403         if( i_ret < 0 )
404         {
405             msg_Warn ( p_dec, "Failed to create Tiger renderer, falling back to basic rendering" );
406             p_sys->p_tr = NULL;
407             p_sys->b_use_tiger = false;
408         }
409
410         CHECK_TIGER_RET( tiger_renderer_set_surface_clear_color( p_sys->p_tr, 1, 0, 0, 0, 0 ) );
411
412         UpdateTigerFontEffect( p_dec );
413         UpdateTigerFontColor( p_dec );
414         UpdateTigerBackgroundColor( p_dec );
415         UpdateTigerQuality( p_dec );
416         UpdateTigerFontDesc( p_dec );
417     }
418
419 #else
420
421     p_sys->b_use_tiger = false;
422
423 #endif
424
425     es_format_Init( &p_dec->fmt_out, SPU_ES, 0 );
426
427     /* add the decoder to the global list */
428     decoder_t **list = realloc( kate_decoder_list, (kate_decoder_list_size+1) * sizeof( *list ));
429     if( list )
430     {
431         list[ kate_decoder_list_size++ ] = p_dec;
432         kate_decoder_list = list;
433     }
434
435     vlc_mutex_unlock( &kate_decoder_list_mutex );
436
437     return VLC_SUCCESS;
438 }
439
440 #ifdef ENABLE_PACKETIZER
441 static int OpenPacketizer( vlc_object_t *p_this )
442 {
443     decoder_t *p_dec = (decoder_t*)p_this;
444
445     int i_ret = OpenDecoder( p_this );
446
447     if( i_ret == VLC_SUCCESS )
448     {
449         p_dec->p_sys->b_packetizer = true;
450         p_dec->fmt_out.i_codec = VLC_CODEC_KATE;
451     }
452
453     return i_ret;
454 }
455 #endif
456
457 /****************************************************************************
458  * DecodeBlock: the whole thing
459  ****************************************************************************
460  * This function must be fed with kate packets.
461  ****************************************************************************/
462 static subpicture_t *DecodeBlock( decoder_t *p_dec, block_t **pp_block )
463 {
464     decoder_sys_t *p_sys = p_dec->p_sys;
465     block_t *p_block;
466     kate_packet kp;
467
468     if( !pp_block || !*pp_block )
469         return NULL;
470
471     p_block = *pp_block;
472
473     if( p_block->i_flags & (BLOCK_FLAG_DISCONTINUITY|BLOCK_FLAG_CORRUPTED) )
474     {
475 #ifdef HAVE_TIGER
476         if( p_block->i_flags & BLOCK_FLAG_DISCONTINUITY)
477         {
478             /* Hmm, should we wait before flushing the renderer ? I think not, but not certain... */
479             vlc_mutex_lock( &p_sys->lock );
480             tiger_renderer_seek( p_sys->p_tr, 0 );
481             vlc_mutex_unlock( &p_sys->lock );
482         }
483 #endif
484         p_sys->i_max_stop = VLC_TS_INVALID;
485         block_Release( p_block );
486         return NULL;
487     }
488
489     /* Block to Kate packet */
490     kate_packet_wrap(&kp, p_block->i_buffer, p_block->p_buffer);
491
492     if( !p_sys->b_has_headers )
493     {
494         if( ProcessHeaders( p_dec ) )
495         {
496             block_Release( *pp_block );
497             return NULL;
498         }
499         p_sys->b_has_headers = true;
500     }
501
502     return ProcessPacket( p_dec, &kp, pp_block );
503 }
504
505 /*****************************************************************************
506  * ProcessHeaders: process Kate headers.
507  *****************************************************************************/
508 static int ProcessHeaders( decoder_t *p_dec )
509 {
510     decoder_sys_t *p_sys = p_dec->p_sys;
511     kate_packet kp;
512
513     unsigned pi_size[XIPH_MAX_HEADER_COUNT];
514     void     *pp_data[XIPH_MAX_HEADER_COUNT];
515     unsigned i_count;
516     if( xiph_SplitHeaders( pi_size, pp_data, &i_count,
517                            p_dec->fmt_in.i_extra, p_dec->fmt_in.p_extra) )
518         return VLC_EGENERIC;
519     int i_ret = VLC_SUCCESS;
520     if( i_count < 1 )
521     {
522         i_ret = VLC_EGENERIC;
523         goto end;
524     }
525
526     /* Take care of the initial Kate header */
527     kp.nbytes = pi_size[0];
528     kp.data   = pp_data[0];
529     i_ret = kate_decode_headerin( &p_sys->ki, &p_sys->kc, &kp );
530     if( i_ret < 0 )
531     {
532         msg_Err( p_dec, "this bitstream does not contain Kate data (%d)", i_ret );
533         goto end;
534     }
535
536     msg_Dbg( p_dec, "%s %s text, granule rate %f, granule shift %d",
537              p_sys->ki.language, p_sys->ki.category,
538              (double)p_sys->ki.gps_numerator/p_sys->ki.gps_denominator,
539              p_sys->ki.granule_shift);
540
541     /* parse all remaining header packets */
542     for( unsigned i_headeridx = 1; i_headeridx < i_count; i_headeridx++ )
543     {
544         kp.nbytes = pi_size[i_headeridx];
545         kp.data   = pp_data[i_headeridx];
546         i_ret = kate_decode_headerin( &p_sys->ki, &p_sys->kc, &kp );
547         if( i_ret < 0 )
548         {
549             msg_Err( p_dec, "Kate header %d is corrupted: %d", i_headeridx, i_ret );
550             goto end;
551         }
552
553         /* header 1 is comments */
554         if( i_headeridx == 1 )
555         {
556             ParseKateComments( p_dec );
557         }
558     }
559
560 #ifdef ENABLE_PACKETIZER
561     if( !p_sys->b_packetizer )
562 #endif
563     {
564         /* We have all the headers, initialize decoder */
565         msg_Dbg( p_dec, "we have all headers, initialize libkate for decoding" );
566         i_ret = kate_decode_init( &p_sys->k, &p_sys->ki );
567         if (i_ret < 0)
568         {
569             msg_Err( p_dec, "Kate failed to initialize for decoding: %d", i_ret );
570             return VLC_EGENERIC;
571         }
572         p_sys->b_ready = true;
573     }
574 #ifdef ENABLE_PACKETIZER
575     else
576     {
577         p_dec->fmt_out.i_extra = p_dec->fmt_in.i_extra;
578         p_dec->fmt_out.p_extra = xrealloc( p_dec->fmt_out.p_extra,
579                                                   p_dec->fmt_out.i_extra );
580         memcpy( p_dec->fmt_out.p_extra,
581                 p_dec->fmt_in.p_extra, p_dec->fmt_out.i_extra );
582     }
583 #endif
584
585 end:
586     for( unsigned i = 0; i < i_count; i++ )
587         free( pp_data[i] );
588     return i_ret < 0 ? VLC_EGENERIC : VLC_SUCCESS;
589 }
590
591 /*****************************************************************************
592  * ProcessPacket: processes a kate packet.
593  *****************************************************************************/
594 static subpicture_t *ProcessPacket( decoder_t *p_dec, kate_packet *p_kp,
595                             block_t **pp_block )
596 {
597     decoder_sys_t *p_sys = p_dec->p_sys;
598     block_t *p_block = *pp_block;
599     subpicture_t *p_buf = NULL;
600
601     /* Date management */
602     if( p_block->i_pts > VLC_TS_INVALID && p_block->i_pts != p_sys->i_pts )
603     {
604         p_sys->i_pts = p_block->i_pts;
605     }
606
607     *pp_block = NULL; /* To avoid being fed the same packet again */
608
609 #ifdef ENABLE_PACKETIZER
610     if( p_sys->b_packetizer )
611     {
612         /* Date management */
613         p_block->i_dts = p_block->i_pts = p_sys->i_pts;
614
615         if( p_sys->i_headers >= p_sys->i_num_headers )
616             p_block->i_length = p_sys->i_pts - p_block->i_pts;
617         else
618             p_block->i_length = 0;
619
620         p_buf = p_block;
621     }
622     else
623 #endif
624     {
625         p_buf = DecodePacket( p_dec, p_kp, p_block );
626
627         if( p_block )
628             block_Release( p_block );
629     }
630
631     return p_buf;
632 }
633
634 /* nicked off blend.c */
635 static inline void rgb_to_yuv( uint8_t *y, uint8_t *u, uint8_t *v,
636                                int r, int g, int b )
637 {
638     *y = ( ( (  66 * r + 129 * g +  25 * b + 128 ) >> 8 ) + 16 );
639     *u =   ( ( -38 * r -  74 * g + 112 * b + 128 ) >> 8 ) + 128 ;
640     *v =   ( ( 112 * r -  94 * g -  18 * b + 128 ) >> 8 ) + 128 ;
641 }
642
643 /*
644   This retrieves the size of the video.
645   The best case is when the original video size is known, as we can then
646   scale images to match. In this case, since VLC autoscales, we want to
647   return the original size and let VLC scale everything.
648   if the original size is not known, then VLC can't resize, so we return
649   the size of the incoming video. If sizes in the Kate stream are in
650   relative units, it works fine. If they are absolute, you get what you
651   ask for. Images aren't rescaled.
652 */
653 static void GetVideoSize( decoder_t *p_dec, int *w, int *h )
654 {
655     /* searching for vout to get its size is frowned upon, so we don't and
656        use a default size if the original canvas size is not specified. */
657 #if 1
658     decoder_sys_t *p_sys = p_dec->p_sys;
659     if( p_sys->ki.original_canvas_width > 0 && p_sys->ki.original_canvas_height > 0 )
660     {
661         *w = p_sys->ki.original_canvas_width;
662         *h = p_sys->ki.original_canvas_height;
663         msg_Dbg( p_dec, "original canvas %zu %zu",
664                  p_sys->ki.original_canvas_width, p_sys->ki.original_canvas_height );
665     }
666     else
667     {
668         /* nothing, leave defaults */
669         msg_Dbg( p_dec, "original canvas size unknown");
670     }
671 #else
672     /* keep this just in case it might be allowed one day ;) */
673     vout_thread_t *p_vout;
674     p_vout = vlc_object_find( (vlc_object_t*)p_dec, VLC_OBJECT_VOUT, FIND_CHILD );
675     if( p_vout )
676     {
677         decoder_sys_t *p_sys = p_dec->p_sys;
678         if( p_sys->ki.original_canvas_width > 0 && p_sys->ki.original_canvas_height > 0 )
679         {
680             *w = p_sys->ki.original_canvas_width;
681             *h = p_sys->ki.original_canvas_height;
682         }
683         else
684         {
685             *w = p_vout->fmt_in.i_width;
686             *h = p_vout->fmt_in.i_height;
687         }
688         msg_Dbg( p_dec, "video: in %d %d, out %d %d, original canvas %zu %zu",
689                  p_vout->fmt_in.i_width, p_vout->fmt_in.i_height,
690                  p_vout->fmt_out.i_width, p_vout->fmt_out.i_height,
691                  p_sys->ki.original_canvas_width, p_sys->ki.original_canvas_height );
692         vlc_object_release( p_vout );
693     }
694 #endif
695 }
696
697 static void CreateKateBitmap( picture_t *pic, const kate_bitmap *bitmap )
698 {
699     size_t y;
700
701     for( y=0; y<bitmap->height; ++y )
702     {
703         uint8_t *dest = pic->Y_PIXELS+pic->Y_PITCH*y;
704         const uint8_t *src = bitmap->pixels+y*bitmap->width;
705         memcpy( dest, src, bitmap->width );
706     }
707 }
708
709 static void CreateKatePalette( video_palette_t *fmt_palette, const kate_palette *palette )
710 {
711     size_t n;
712
713     fmt_palette->i_entries = palette->ncolors;
714     for( n=0; n<palette->ncolors; ++n )
715     {
716         rgb_to_yuv(
717             &fmt_palette->palette[n][0], &fmt_palette->palette[n][1], &fmt_palette->palette[n][2],
718             palette->colors[n].r, palette->colors[n].g, palette->colors[n].b
719         );
720         fmt_palette->palette[n][3] = palette->colors[n].a;
721     }
722 }
723
724 static void SetupText( decoder_t *p_dec, subpicture_t *p_spu, const kate_event *ev )
725 {
726     decoder_sys_t *p_sys = p_dec->p_sys;
727
728     if( ev->text_encoding != kate_utf8 )
729     {
730         msg_Warn( p_dec, "Text isn't UTF-8, unsupported, ignored" );
731         return;
732     }
733
734     switch( ev->text_markup_type )
735     {
736         case kate_markup_none:
737             p_spu->p_region->psz_text = strdup( ev->text ); /* no leak, this actually gets killed by the core */
738             break;
739         case kate_markup_simple:
740             if( p_sys->b_formatted )
741             {
742                 /* the HTML renderer expects a top level text tag pair */
743                 char *buffer = NULL;
744                 if( asprintf( &buffer, "<text>%s</text>", ev->text ) >= 0 )
745                 {
746                     p_spu->p_region->psz_html = buffer;
747                 }
748                 break;
749             }
750             /* if not formatted, we fall through */
751         default:
752             /* we don't know about this one, so remove markup and display as text */
753             {
754                 char *copy = strdup( ev->text );
755                 size_t len0 = strlen( copy ) + 1;
756                 kate_text_remove_markup( ev->text_encoding, copy, &len0 );
757                 p_spu->p_region->psz_text = copy;
758             }
759             break;
760     }
761 }
762
763 #ifdef HAVE_TIGER
764
765 static void TigerDestroySubpicture( subpicture_t *p_subpic )
766 {
767     DecSysRelease( p_subpic->p_sys->p_dec_sys );
768 }
769
770 static void SubpictureReleaseRegions( subpicture_t *p_subpic )
771 {
772     if( p_subpic->p_region)
773     {
774         subpicture_region_ChainDelete( p_subpic->p_region );
775         p_subpic->p_region = NULL;
776     }
777 }
778
779 /*
780  * We get premultiplied alpha, but VLC doesn't expect this, so we demultiply
781  * alpha to avoid double multiply (and thus thinner text than we should)).
782  * Best would be to have VLC be able to handle premultiplied alpha, as it
783  * would be faster to blend as well.
784  *
785  * Also, we flip color components around for big endian machines, as Tiger
786  * outputs ARGB or ABGR (the one we selected here) in host endianness.
787  */
788 static void PostprocessTigerImage( plane_t *p_plane, unsigned int i_width )
789 {
790     PROFILE_START( tiger_renderer_postprocess );
791     int y;
792     for( y=0; y<p_plane->i_lines; ++y )
793     {
794         uint8_t *p_line = (uint8_t*)(p_plane->p_pixels + y*p_plane->i_pitch);
795         unsigned int x;
796         for( x=0; x<i_width; ++x )
797         {
798             uint8_t *p_pixel = p_line+x*4;
799 #ifdef WORDS_BIGENDIAN
800             uint8_t a = p_pixel[0];
801 #else
802             uint8_t a = p_pixel[3];
803 #endif
804             if( a )
805             {
806 #ifdef WORDS_BIGENDIAN
807                 uint8_t tmp = p_pixel[2];
808                 p_pixel[0] = clip_uint8_vlc((p_pixel[3] * 255 + a / 2) / a);
809                 p_pixel[3] = a;
810                 p_pixel[2] = clip_uint8_vlc((p_pixel[1] * 255 + a / 2) / a);
811                 p_pixel[1] = clip_uint8_vlc((tmp * 255 + a / 2) / a);
812 #else
813                 p_pixel[0] = clip_uint8_vlc((p_pixel[0] * 255 + a / 2) / a);
814                 p_pixel[1] = clip_uint8_vlc((p_pixel[1] * 255 + a / 2) / a);
815                 p_pixel[2] = clip_uint8_vlc((p_pixel[2] * 255 + a / 2) / a);
816 #endif
817             }
818             else
819             {
820                 p_pixel[0] = 0;
821                 p_pixel[1] = 0;
822                 p_pixel[2] = 0;
823                 p_pixel[3] = 0;
824             }
825         }
826     }
827     PROFILE_STOP( tiger_renderer_postprocess );
828 }
829
830 /* Tiger renders can end up looking a bit crap since they get overlaid on top of
831    a subsampled YUV image, so there can be a fair amount of chroma bleeding.
832    Looks good with white though since it's all luma. Hopefully that will be the
833    common case. */
834 static void TigerUpdateRegions( spu_t *p_spu, subpicture_t *p_subpic, const video_format_t *p_fmt, mtime_t ts )
835 {
836     decoder_sys_t *p_sys = p_subpic->p_sys->p_dec_sys;
837     subpicture_region_t *p_r;
838     video_format_t fmt;
839     plane_t *p_plane;
840     kate_float t;
841     int i_ret;
842
843     VLC_UNUSED( p_spu );
844
845     PROFILE_START( TigerUpdateRegions );
846
847     /* time in seconds from the start of the stream */
848     t = (p_subpic->p_sys->i_start + ts - p_subpic->i_start ) / 1000000.0f;
849
850     /* it is likely that the current region (if any) can be kept as is; test for this */
851     vlc_mutex_lock( &p_sys->lock );
852     if( p_subpic->p_region && !p_sys->b_dirty && !tiger_renderer_is_dirty( p_sys->p_tr ))
853     {
854         PROFILE_START( tiger_renderer_update1 );
855         i_ret = tiger_renderer_update( p_sys->p_tr, t, 1 );
856         PROFILE_STOP( tiger_renderer_update1 );
857         if( i_ret < 0 )
858         {
859             SubpictureReleaseRegions( p_subpic );
860             vlc_mutex_unlock( &p_sys->lock );
861             return;
862         }
863
864         if( !tiger_renderer_is_dirty( p_sys->p_tr ) )
865         {
866             /* we can keep the current region list */
867             PROFILE_STOP( TigerUpdateRegions );
868             vlc_mutex_unlock( &p_sys->lock );
869             return;
870         }
871     }
872     vlc_mutex_unlock( &p_sys->lock );
873
874     /* we have to render again, reset current region list */
875     SubpictureReleaseRegions( p_subpic );
876
877     /* create a full frame region - this will also tell Tiger the size of the frame */
878     fmt = *p_fmt;
879     fmt.i_chroma = VLC_CODEC_RGBA;
880     fmt.i_width = fmt.i_visible_width;
881     fmt.i_height = fmt.i_visible_height;
882     fmt.i_bits_per_pixel = 0;
883     fmt.i_x_offset = fmt.i_y_offset = 0;
884
885     p_r = subpicture_region_New( &fmt );
886     if( !p_r )
887     {
888         return;
889     }
890
891     p_r->i_x = 0;
892     p_r->i_y = 0;
893     p_r->i_align = SUBPICTURE_ALIGN_TOP | SUBPICTURE_ALIGN_LEFT;
894
895     vlc_mutex_lock( &p_sys->lock );
896
897     p_plane = &p_r->p_picture->p[0];
898     i_ret = tiger_renderer_set_buffer( p_sys->p_tr, p_plane->p_pixels, fmt.i_width, p_plane->i_lines, p_plane->i_pitch, 1 );
899     if( i_ret < 0 )
900     {
901         goto failure;
902     }
903
904     PROFILE_START( tiger_renderer_update );
905     i_ret = tiger_renderer_update( p_sys->p_tr, t, 1 );
906     if( i_ret < 0 )
907     {
908         goto failure;
909     }
910     PROFILE_STOP( tiger_renderer_update );
911
912     PROFILE_START( tiger_renderer_render );
913     i_ret = tiger_renderer_render( p_sys->p_tr );
914     if( i_ret < 0 )
915     {
916         goto failure;
917     }
918     PROFILE_STOP( tiger_renderer_render );
919
920     PostprocessTigerImage( p_plane, fmt.i_width );
921     p_subpic->p_region = p_r;
922     p_sys->b_dirty = false;
923
924     PROFILE_STOP( TigerUpdateRegions );
925
926     vlc_mutex_unlock( &p_sys->lock );
927
928     return;
929
930 failure:
931     vlc_mutex_unlock( &p_sys->lock );
932     subpicture_region_ChainDelete( p_r );
933 }
934
935 static uint32_t GetTigerColor( decoder_t *p_dec, const char *psz_prefix )
936 {
937     char *psz_tmp;
938     uint32_t i_color = 0;
939
940     if( asprintf( &psz_tmp, "%s-color", psz_prefix ) >= 0 )
941     {
942         uint32_t i_rgb = var_CreateGetInteger( p_dec, psz_tmp );
943         var_Destroy( p_dec, psz_tmp );
944         free( psz_tmp );
945         i_color |= i_rgb;
946     }
947
948     if( asprintf( &psz_tmp, "%s-alpha", psz_prefix ) >= 0 )
949     {
950         uint32_t i_alpha = var_CreateGetInteger( p_dec, psz_tmp );
951         var_Destroy( p_dec, psz_tmp );
952         free( psz_tmp );
953         i_color |= (i_alpha << 24);
954     }
955
956     return i_color;
957 }
958
959 static char *GetTigerString( decoder_t *p_dec, const char *psz_name )
960 {
961     char *psz_value = var_CreateGetString( p_dec, psz_name );
962     if( psz_value)
963     {
964         psz_value = strdup( psz_value );
965     }
966     var_Destroy( p_dec, psz_name );
967     return psz_value;
968 }
969
970 static int GetTigerInteger( decoder_t *p_dec, const char *psz_name )
971 {
972     int i_value = var_CreateGetInteger( p_dec, psz_name );
973     var_Destroy( p_dec, psz_name );
974     return i_value;
975 }
976
977 static double GetTigerFloat( decoder_t *p_dec, const char *psz_name )
978 {
979     double f_value = var_CreateGetFloat( p_dec, psz_name );
980     var_Destroy( p_dec, psz_name );
981     return f_value;
982 }
983
984 static void UpdateTigerQuality( decoder_t *p_dec )
985 {
986     decoder_sys_t *p_sys = (decoder_sys_t*)p_dec->p_sys;
987     CHECK_TIGER_RET( tiger_renderer_set_quality( p_sys->p_tr, p_sys->f_tiger_quality ) );
988     p_sys->b_dirty = true;
989 }
990
991 static void UpdateTigerFontDesc( decoder_t *p_dec )
992 {
993     decoder_sys_t *p_sys = (decoder_sys_t*)p_dec->p_sys;
994     CHECK_TIGER_RET( tiger_renderer_set_default_font_description( p_sys->p_tr, p_sys->psz_tiger_default_font_desc ) );
995     p_sys->b_dirty = true;
996 }
997
998 static void UpdateTigerFontColor( decoder_t *p_dec )
999 {
1000     decoder_sys_t *p_sys = (decoder_sys_t*)p_dec->p_sys;
1001     double f_a = ((p_sys->i_tiger_default_font_color >> 24) & 0xff) / 255.0;
1002     double f_r = ((p_sys->i_tiger_default_font_color >> 16) & 0xff) / 255.0;
1003     double f_g = ((p_sys->i_tiger_default_font_color >> 8) & 0xff) / 255.0;
1004     double f_b = (p_sys->i_tiger_default_font_color & 0xff) / 255.0;
1005     CHECK_TIGER_RET( tiger_renderer_set_default_font_color( p_sys->p_tr, f_r, f_g, f_b, f_a ) );
1006     p_sys->b_dirty = true;
1007 }
1008
1009 static void UpdateTigerBackgroundColor( decoder_t *p_dec )
1010 {
1011     decoder_sys_t *p_sys = (decoder_sys_t*)p_dec->p_sys;
1012     double f_a = ((p_sys->i_tiger_default_background_color >> 24) & 0xff) / 255.0;
1013     double f_r = ((p_sys->i_tiger_default_background_color >> 16) & 0xff) / 255.0;
1014     double f_g = ((p_sys->i_tiger_default_background_color >> 8) & 0xff) / 255.0;
1015     double f_b = (p_sys->i_tiger_default_background_color & 0xff) / 255.0;
1016     CHECK_TIGER_RET( tiger_renderer_set_default_background_fill_color( p_sys->p_tr, f_r, f_g, f_b, f_a ) );
1017     p_sys->b_dirty = true;
1018 }
1019
1020 static void UpdateTigerFontEffect( decoder_t *p_dec )
1021 {
1022     decoder_sys_t *p_sys = (decoder_sys_t*)p_dec->p_sys;
1023     CHECK_TIGER_RET( tiger_renderer_set_default_font_effect( p_sys->p_tr,
1024                                                              p_sys->e_tiger_default_font_effect,
1025                                                              p_sys->f_tiger_default_font_effect_strength ) );
1026     p_sys->b_dirty = true;
1027 }
1028
1029 static int OnConfigurationChanged( decoder_t *p_dec, const char *psz_var,
1030                                    vlc_value_t oldval, vlc_value_t newval )
1031 {
1032     decoder_sys_t *p_sys = (decoder_sys_t*)p_dec->p_sys;
1033
1034     VLC_UNUSED( oldval );
1035
1036     vlc_mutex_lock( &p_sys->lock );
1037
1038     msg_Dbg( p_dec, "OnConfigurationChanged: %s", psz_var );
1039
1040     if( !p_sys->b_use_tiger || !p_sys->p_tr )
1041     {
1042         vlc_mutex_unlock( &p_sys->lock );
1043         return VLC_SUCCESS;
1044     }
1045
1046 #define TEST_TIGER_VAR( name ) \
1047     if( !strcmp( name, psz_var ) )
1048
1049     TEST_TIGER_VAR( "kate-tiger-quality" )
1050     {
1051         p_sys->f_tiger_quality = newval.f_float;
1052         UpdateTigerQuality( p_dec );
1053     }
1054
1055     TEST_TIGER_VAR( "kate-tiger-default-font-desc" )
1056     {
1057         if( p_sys->psz_tiger_default_font_desc )
1058         {
1059             free( p_sys->psz_tiger_default_font_desc );
1060             p_sys->psz_tiger_default_font_desc = NULL;
1061         }
1062         if( newval.psz_string )
1063         {
1064             p_sys->psz_tiger_default_font_desc = strdup( newval.psz_string );
1065         }
1066         UpdateTigerFontDesc( p_dec );
1067     }
1068
1069     TEST_TIGER_VAR( "kate-tiger-default-font-color" )
1070     {
1071         p_sys->i_tiger_default_font_color = (p_sys->i_tiger_default_font_color & 0xff00000000) | newval.i_int;
1072         UpdateTigerFontColor( p_dec );
1073     }
1074
1075     TEST_TIGER_VAR( "kate-tiger-default-font-alpha" )
1076     {
1077         p_sys->i_tiger_default_font_color = (p_sys->i_tiger_default_font_color & 0x00ffffff) | (newval.i_int<<24);
1078         UpdateTigerFontColor( p_dec );
1079     }
1080
1081     TEST_TIGER_VAR( "kate-tiger-default-background-color" )
1082     {
1083         p_sys->i_tiger_default_background_color = (p_sys->i_tiger_default_background_color & 0xff00000000) | newval.i_int;
1084         UpdateTigerBackgroundColor( p_dec );
1085     }
1086
1087     TEST_TIGER_VAR( "kate-tiger-default-background-alpha" )
1088     {
1089         p_sys->i_tiger_default_background_color = (p_sys->i_tiger_default_background_color & 0x00ffffff) | (newval.i_int<<24);
1090         UpdateTigerBackgroundColor( p_dec );
1091     }
1092
1093     TEST_TIGER_VAR( "kate-tiger-default-font-effect" )
1094     {
1095         p_sys->e_tiger_default_font_effect = (tiger_font_effect)newval.i_int;
1096         UpdateTigerFontEffect( p_dec );
1097     }
1098
1099     TEST_TIGER_VAR( "kate-tiger-default-font-effect-strength" )
1100     {
1101         p_sys->f_tiger_default_font_effect_strength = newval.f_float;
1102         UpdateTigerFontEffect( p_dec );
1103     }
1104
1105 #undef TEST_TIGER_VAR
1106
1107     vlc_mutex_unlock( &p_sys->lock );
1108
1109     return VLC_SUCCESS;
1110 }
1111
1112 static int TigerConfigurationCallback( vlc_object_t *p_this, const char *psz_var,
1113                                        vlc_value_t oldval, vlc_value_t newval,
1114                                        void *p_data )
1115 {
1116     size_t i_idx;
1117
1118     VLC_UNUSED( p_this );
1119     VLC_UNUSED( oldval );
1120     VLC_UNUSED( newval );
1121     VLC_UNUSED( p_data );
1122
1123     vlc_mutex_lock( &kate_decoder_list_mutex );
1124
1125     /* Update all existing decoders from the global user prefs */
1126     for( i_idx = 0; i_idx < kate_decoder_list_size; i_idx++ )
1127     {
1128         decoder_t *p_dec = kate_decoder_list[ i_idx ];
1129         OnConfigurationChanged( p_dec, psz_var, oldval, newval );
1130     }
1131
1132     vlc_mutex_unlock( &kate_decoder_list_mutex );
1133
1134     return VLC_SUCCESS;
1135 }
1136
1137 #endif
1138
1139 /*****************************************************************************
1140  * DecodePacket: decodes a Kate packet.
1141  *****************************************************************************/
1142 static subpicture_t *DecodePacket( decoder_t *p_dec, kate_packet *p_kp, block_t *p_block )
1143 {
1144     decoder_sys_t *p_sys = p_dec->p_sys;
1145     const kate_event *ev = NULL;
1146     subpicture_t *p_spu = NULL;
1147     int i_ret;
1148
1149     if( !p_sys->b_ready )
1150     {
1151         msg_Err( p_dec, "Cannot decode Kate packet, decoder not initialized" );
1152         return NULL;
1153     }
1154
1155     i_ret = kate_decode_packetin( &p_sys->k, p_kp );
1156     if( i_ret < 0 )
1157     {
1158         msg_Err( p_dec, "Kate failed to decode packet: %d", i_ret );
1159         return NULL;
1160     }
1161
1162     i_ret = kate_decode_eventout( &p_sys->k, &ev );
1163     if( i_ret < 0 )
1164     {
1165         msg_Err( p_dec, "Kate failed to retrieve event: %d", i_ret );
1166         return NULL;
1167     }
1168     if( i_ret > 0 )
1169     {
1170         /* no event to go with this packet, this is normal */
1171         return NULL;
1172     }
1173
1174     /* we have an event */
1175
1176     /* Get a new spu */
1177     p_spu = decoder_NewSubpicture( p_dec );
1178     if( !p_spu )
1179     {
1180         /* this will happen for lyrics as there is no vout - so no error */
1181         /* msg_Err( p_dec, "Failed to allocate spu buffer" ); */
1182         return NULL;
1183     }
1184
1185     p_spu->i_start = p_block->i_pts;
1186     p_spu->i_stop = p_block->i_pts + INT64_C(1000000)*ev->duration*p_sys->ki.gps_denominator/p_sys->ki.gps_numerator;
1187     p_spu->b_ephemer = false;
1188     p_spu->b_absolute = false;
1189
1190 #ifdef HAVE_TIGER
1191     if( p_sys->b_use_tiger)
1192     {
1193         /* setup the structure to get our decoder struct back */
1194         p_spu->p_sys = malloc( sizeof( subpicture_sys_t ));
1195         if( !p_spu->p_sys )
1196         {
1197             decoder_DeleteSubpicture( p_dec, p_spu );
1198             return NULL;
1199         }
1200         p_spu->p_sys->p_dec_sys = p_sys;
1201         p_spu->p_sys->i_start = p_block->i_pts;
1202         DecSysHold( p_sys );
1203
1204         p_spu->i_stop = __MAX( p_sys->i_max_stop, p_spu->i_stop );
1205         p_spu->b_ephemer = true;
1206         p_spu->b_absolute = true;
1207
1208         /* add the event to tiger */
1209         vlc_mutex_lock( &p_sys->lock );
1210         CHECK_TIGER_RET( tiger_renderer_add_event( p_sys->p_tr, ev->ki, ev ) );
1211         vlc_mutex_unlock( &p_sys->lock );
1212
1213         /* hookup render/update routines */
1214         p_spu->pf_update_regions = TigerUpdateRegions;
1215         p_spu->pf_destroy = TigerDestroySubpicture;
1216     }
1217     else
1218 #endif
1219     {
1220         p_spu = SetupSimpleKateSPU( p_dec, p_spu, ev );
1221     }
1222
1223     return p_spu;
1224 }
1225
1226 /*****************************************************************************
1227  * SetupSimpleKateSPU: creates text/bitmap regions where appropriate
1228  *****************************************************************************/
1229 static subpicture_t *SetupSimpleKateSPU( decoder_t *p_dec, subpicture_t *p_spu,
1230                                          const kate_event *ev )
1231 {
1232     decoder_sys_t *p_sys = p_dec->p_sys;
1233     video_format_t fmt;
1234     subpicture_region_t *p_bitmap_region = NULL;
1235     video_palette_t palette;
1236     kate_tracker kin;
1237     bool b_tracker_valid = false;
1238     int i_ret;
1239
1240     /* these may be 0 for "not specified" */
1241     p_spu->i_original_picture_width = p_sys->ki.original_canvas_width;
1242     p_spu->i_original_picture_height = p_sys->ki.original_canvas_height;
1243
1244     /* Create a new subpicture region */
1245     memset( &fmt, 0, sizeof(video_format_t) );
1246
1247     if (p_sys->b_formatted)
1248     {
1249         i_ret = kate_tracker_init( &kin, &p_sys->ki, ev );
1250         if( i_ret < 0)
1251         {
1252             msg_Err( p_dec, "failed to initialize kate tracker, event will be unformatted: %d", i_ret );
1253         }
1254         else
1255         {
1256             int w = 720, h = 576; /* give sensible defaults just in case we fail to get the actual size */
1257             GetVideoSize(p_dec, &w, &h);
1258             i_ret = kate_tracker_update(&kin, 0, w, h, 0, 0, w, h);
1259             if( i_ret < 0)
1260             {
1261                 kate_tracker_clear(&kin);
1262                 msg_Err( p_dec, "failed to update kate tracker, event will be unformatted: %d", i_ret );
1263             }
1264             else
1265             {
1266                 // TODO: parse tracker and set style, init fmt
1267                 b_tracker_valid = true;
1268             }
1269         }
1270     }
1271
1272     if (ev->bitmap && ev->bitmap->type==kate_bitmap_type_paletted && ev->palette) {
1273
1274         /* create a separate region for the bitmap */
1275         memset( &fmt, 0, sizeof(video_format_t) );
1276         fmt.i_chroma = VLC_CODEC_YUVP;
1277         fmt.i_width = fmt.i_visible_width = ev->bitmap->width;
1278         fmt.i_height = fmt.i_visible_height = ev->bitmap->height;
1279         fmt.i_x_offset = fmt.i_y_offset = 0;
1280         fmt.p_palette = &palette;
1281         CreateKatePalette( fmt.p_palette, ev->palette );
1282
1283         p_bitmap_region = subpicture_region_New( &fmt );
1284         if( !p_bitmap_region )
1285         {
1286             msg_Err( p_dec, "cannot allocate SPU region" );
1287             decoder_DeleteSubpicture( p_dec, p_spu );
1288             return NULL;
1289         }
1290
1291         /* create the bitmap */
1292         CreateKateBitmap( p_bitmap_region->p_picture, ev->bitmap );
1293
1294         msg_Dbg(p_dec, "Created bitmap, %zux%zu, %zu colors", ev->bitmap->width, ev->bitmap->height, ev->palette->ncolors);
1295     }
1296
1297     /* text region */
1298     fmt.i_chroma = VLC_CODEC_TEXT;
1299     fmt.i_sar_num = 0;
1300     fmt.i_sar_den = 1;
1301     fmt.i_width = fmt.i_height = 0;
1302     fmt.i_x_offset = fmt.i_y_offset = 0;
1303     p_spu->p_region = subpicture_region_New( &fmt );
1304     if( !p_spu->p_region )
1305     {
1306         msg_Err( p_dec, "cannot allocate SPU region" );
1307         decoder_DeleteSubpicture( p_dec, p_spu );
1308         return NULL;
1309     }
1310
1311     SetupText( p_dec, p_spu, ev );
1312
1313     /* default positioning */
1314     p_spu->p_region->i_align = SUBPICTURE_ALIGN_BOTTOM;
1315     if (p_bitmap_region)
1316     {
1317         p_bitmap_region->i_align = SUBPICTURE_ALIGN_BOTTOM;
1318     }
1319     p_spu->p_region->i_x = 0;
1320     p_spu->p_region->i_y = 10;
1321
1322     /* override if tracker info present */
1323     if (b_tracker_valid)
1324     {
1325         if (kin.has.region)
1326         {
1327             p_spu->p_region->i_x = kin.region_x;
1328             p_spu->p_region->i_y = kin.region_y;
1329             if (p_bitmap_region)
1330             {
1331                 p_bitmap_region->i_x = kin.region_x;
1332                 p_bitmap_region->i_y = kin.region_y;
1333             }
1334             p_spu->b_absolute = true;
1335         }
1336
1337         kate_tracker_clear(&kin);
1338     }
1339
1340     /* if we have a bitmap, chain it before the text */
1341     if (p_bitmap_region)
1342     {
1343         p_bitmap_region->p_next = p_spu->p_region;
1344         p_spu->p_region = p_bitmap_region;
1345     }
1346
1347     return p_spu;
1348 }
1349
1350 /*****************************************************************************
1351  * ParseKateComments:
1352  *****************************************************************************/
1353 static void ParseKateComments( decoder_t *p_dec )
1354 {
1355     char *psz_name, *psz_value, *psz_comment;
1356     int i = 0;
1357
1358     while ( i < p_dec->p_sys->kc.comments )
1359     {
1360         psz_comment = strdup( p_dec->p_sys->kc.user_comments[i] );
1361         if( !psz_comment )
1362             break;
1363         psz_name = psz_comment;
1364         psz_value = strchr( psz_comment, '=' );
1365         if( psz_value )
1366         {
1367             *psz_value = '\0';
1368             psz_value++;
1369
1370             if( !p_dec->p_description )
1371                 p_dec->p_description = vlc_meta_New();
1372             if( p_dec->p_description )
1373                 vlc_meta_AddExtra( p_dec->p_description, psz_name, psz_value );
1374         }
1375         free( psz_comment );
1376         i++;
1377     }
1378 }
1379
1380 /*****************************************************************************
1381  * CloseDecoder: clean up the decoder
1382  *****************************************************************************/
1383 static void CloseDecoder( vlc_object_t *p_this )
1384 {
1385     decoder_t *p_dec = (decoder_t *)p_this;
1386     size_t     i_index;
1387
1388     /* remove the decoder from the global list */
1389     vlc_mutex_lock( &kate_decoder_list_mutex );
1390     for( i_index = 0; i_index < kate_decoder_list_size; i_index++ )
1391     {
1392         if( kate_decoder_list[ i_index ] == p_dec )
1393         {
1394             kate_decoder_list[ i_index ] = kate_decoder_list[ --kate_decoder_list_size ];
1395             break;
1396         }
1397     }
1398     vlc_mutex_unlock( &kate_decoder_list_mutex );
1399
1400     msg_Dbg( p_dec, "Closing Kate decoder" );
1401     DecSysRelease( p_dec->p_sys );
1402 }
1403
1404 static void DecSysHold( decoder_sys_t *p_sys )
1405 {
1406     vlc_mutex_lock( &p_sys->lock );
1407     p_sys->i_refcount++;
1408     vlc_mutex_unlock( &p_sys->lock );
1409 }
1410
1411 static void DecSysRelease( decoder_sys_t *p_sys )
1412 {
1413     vlc_mutex_lock( &p_sys->lock );
1414     p_sys->i_refcount--;
1415     if( p_sys->i_refcount > 0)
1416     {
1417         vlc_mutex_unlock( &p_sys->lock );
1418         return;
1419     }
1420
1421     vlc_mutex_unlock( &p_sys->lock );
1422     vlc_mutex_destroy( &p_sys->lock );
1423
1424 #ifdef HAVE_TIGER
1425     if( p_sys->p_tr )
1426         tiger_renderer_destroy( p_sys->p_tr );
1427     free( p_sys->psz_tiger_default_font_desc );
1428 #endif
1429
1430     if (p_sys->b_ready)
1431         kate_clear( &p_sys->k );
1432     kate_info_clear( &p_sys->ki );
1433     kate_comment_clear( &p_sys->kc );
1434
1435     free( p_sys );
1436 }
1437