]> git.sesse.net Git - vlc/blob - modules/codec/dvbsub.c
Remove --sout-dvbsub-timeout flag
[vlc] / modules / codec / dvbsub.c
1 /*****************************************************************************
2  * dvbsub.c : DVB subtitles decoder
3  *            DVB subtitles encoder (developed for Anevia, www.anevia.com)
4  *****************************************************************************
5  * Copyright (C) 2003 ANEVIA
6  * Copyright (C) 2003-2005 the VideoLAN team
7  * $Id$
8  *
9  * Authors: Gildas Bazin <gbazin@videolan.org>
10  *          Damien LUCAS <damien.lucas@anevia.com>
11  *          Laurent Aimar <fenrir@via.ecp.fr>
12  *          Jean-Paul Saman <jpsaman #_at_# m2x dot nl>
13  *
14  * This program is free software; you can redistribute it and/or modify
15  * it under the terms of the GNU General Public License as published by
16  * the Free Software Foundation; either version 2 of the License, or
17  * (at your option) any later version.
18  *
19  * This program is distributed in the hope that it will be useful,
20  * but WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22  * GNU General Public License for more details.
23  *
24  * You should have received a copy of the GNU General Public License
25  * along with this program; if not, write to the Free Software
26  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
27  *****************************************************************************/
28 /*****************************************************************************
29  * Preamble
30  *
31  * FIXME:
32  * DVB subtitles coded as strings of characters are not handled correctly.
33  * The character codes in the string should actually be indexes refering to a
34  * character table identified in the subtitle descriptor.
35  *****************************************************************************/
36 #include <vlc/vlc.h>
37 #include <vlc/vout.h>
38 #include <vlc/decoder.h>
39 #include <vlc/sout.h>
40
41 #include "vlc_bits.h"
42
43 /* #define DEBUG_DVBSUB 1 */
44
45 #define POSX_TEXT N_("Decoding X coordinate")
46 #define POSX_LONGTEXT N_("X coordinate of the rendered subtitle")
47
48 #define POSY_TEXT N_("Decoding Y coordinate")
49 #define POSY_LONGTEXT N_("Y coordinate of the rendered subtitle") 
50
51 #define POS_TEXT N_("Subpicture position")
52 #define POS_LONGTEXT N_( \
53   "You can enforce the subpicture position on the video " \
54   "(0=center, 1=left, 2=right, 4=top, 8=bottom, you can " \
55   "also use combinations of these values, e.g. 6=top-right).")
56
57 #define ENC_POSX_TEXT N_("Encoding X coordinate")
58 #define ENC_POSX_LONGTEXT N_("X coordinate of the encoded subtitle" )
59 #define ENC_POSY_TEXT N_("Encoding Y coordinate")
60 #define ENC_POSY_LONGTEXT N_("Y coordinate of the encoded subtitle" )
61
62 static int pi_pos_values[] = { 0, 1, 2, 4, 8, 5, 6, 9, 10 };
63 static char *ppsz_pos_descriptions[] =
64 { N_("Center"), N_("Left"), N_("Right"), N_("Top"), N_("Bottom"),
65   N_("Top-Left"), N_("Top-Right"), N_("Bottom-Left"), N_("Bottom-Right") };
66
67 /*****************************************************************************
68  * Module descriptor.
69  *****************************************************************************/
70 static int  Open ( vlc_object_t * );
71 static void Close( vlc_object_t * );
72 static subpicture_t *Decode( decoder_t *, block_t ** );
73
74 static int OpenEncoder  ( vlc_object_t * );
75 static void CloseEncoder( vlc_object_t * );
76 static block_t *Encode  ( encoder_t *, subpicture_t * );
77
78 vlc_module_begin();
79 #   define DVBSUB_CFG_PREFIX "dvbsub-"
80     set_description( _("DVB subtitles decoder") );
81     set_capability( "decoder", 50 );
82     set_category( CAT_INPUT );
83     set_subcategory( SUBCAT_INPUT_SCODEC );
84     set_callbacks( Open, Close );
85
86     add_integer( DVBSUB_CFG_PREFIX "position", 8, NULL, POS_TEXT, POS_LONGTEXT, VLC_TRUE );
87         change_integer_list( pi_pos_values, ppsz_pos_descriptions, 0 );
88     add_integer( DVBSUB_CFG_PREFIX "x", -1, NULL, POSX_TEXT, POSX_LONGTEXT, VLC_FALSE );
89     add_integer( DVBSUB_CFG_PREFIX "y", -1, NULL, POSY_TEXT, POSY_LONGTEXT, VLC_FALSE );
90
91 #   define ENC_CFG_PREFIX "sout-dvbsub-"
92     add_submodule();
93     set_description( _("DVB subtitles encoder") );
94     set_capability( "encoder", 100 );
95     set_callbacks( OpenEncoder, CloseEncoder );
96
97     add_integer( ENC_CFG_PREFIX "x", -1, NULL, ENC_POSX_TEXT, ENC_POSX_LONGTEXT, VLC_FALSE );
98     add_integer( ENC_CFG_PREFIX "y", -1, NULL, ENC_POSY_TEXT, ENC_POSY_LONGTEXT, VLC_FALSE );
99 vlc_module_end();
100
101 static const char *ppsz_enc_options[] = { NULL };
102
103 /****************************************************************************
104  * Local structures
105  ****************************************************************************
106  * Those structures refer closely to the ETSI 300 743 Object model
107  ****************************************************************************/
108
109 /* The object definition gives the position of the object in a region */
110 typedef struct dvbsub_objectdef_s
111 {
112     int i_id;
113     int i_type;
114     int i_x;
115     int i_y;
116     int i_fg_pc;
117     int i_bg_pc;
118     char *psz_text; /* for string of characters objects */
119
120 } dvbsub_objectdef_t;
121
122 /* The entry in the palette CLUT */
123 typedef struct
124 {
125     uint8_t                 Y;
126     uint8_t                 Cr;
127     uint8_t                 Cb;
128     uint8_t                 T;
129
130 } dvbsub_color_t;
131
132 /* */
133 typedef struct dvbsub_clut_s
134 {
135     uint8_t                 i_id;
136     uint8_t                 i_version;
137     dvbsub_color_t          c_2b[4];
138     dvbsub_color_t          c_4b[16];
139     dvbsub_color_t          c_8b[256];
140
141     struct dvbsub_clut_s    *p_next;
142
143 } dvbsub_clut_t;
144
145 /* The Region is an aera on the image
146  * with a list of the object definitions associated and a CLUT */
147 typedef struct dvbsub_region_s
148 {
149     int i_id;
150     int i_version;
151     int i_x;
152     int i_y;
153     int i_width;
154     int i_height;
155     int i_level_comp;
156     int i_depth;
157     int i_clut;
158
159     uint8_t *p_pixbuf;
160
161     int                    i_object_defs;
162     dvbsub_objectdef_t     *p_object_defs;
163
164     struct dvbsub_region_s *p_next;
165
166 } dvbsub_region_t;
167
168 /* The object definition gives the position of the object in a region */
169 typedef struct dvbsub_regiondef_s
170 {
171     int i_id;
172     int i_x;
173     int i_y;
174
175 } dvbsub_regiondef_t;
176
177 /* The page defines the list of regions */
178 typedef struct
179 {
180     int i_id;
181     int i_timeout; /* in seconds */
182     int i_state;
183     int i_version;
184
185     int                i_region_defs;
186     dvbsub_regiondef_t *p_region_defs;
187
188 } dvbsub_page_t;
189
190 struct decoder_sys_t
191 {
192     bs_t            bs;
193
194     /* Decoder internal data */
195     int             i_id;
196     int             i_ancillary_id;
197     mtime_t         i_pts;
198
199     vlc_bool_t      b_absolute;
200     int             i_spu_position;
201     int             i_spu_x;
202     int             i_spu_y;
203
204     vlc_bool_t      b_page;
205     dvbsub_page_t   *p_page;
206     dvbsub_region_t *p_regions;
207     dvbsub_clut_t   *p_cluts;
208     dvbsub_clut_t   default_clut;
209 };
210
211
212 /* List of different SEGMENT TYPES */
213 /* According to EN 300-743, table 2 */
214 #define DVBSUB_ST_PAGE_COMPOSITION      0x10
215 #define DVBSUB_ST_REGION_COMPOSITION    0x11
216 #define DVBSUB_ST_CLUT_DEFINITION       0x12
217 #define DVBSUB_ST_OBJECT_DATA           0x13
218 #define DVBSUB_ST_ENDOFDISPLAY          0x80
219 #define DVBSUB_ST_STUFFING              0xff
220 /* List of different OBJECT TYPES */
221 /* According to EN 300-743, table 6 */
222 #define DVBSUB_OT_BASIC_BITMAP          0x00
223 #define DVBSUB_OT_BASIC_CHAR            0x01
224 #define DVBSUB_OT_COMPOSITE_STRING      0x02
225 /* Pixel DATA TYPES */
226 /* According to EN 300-743, table 9 */ 
227 #define DVBSUB_DT_2BP_CODE_STRING       0x10
228 #define DVBSUB_DT_4BP_CODE_STRING       0x11
229 #define DVBSUB_DT_8BP_CODE_STRING       0x12
230 #define DVBSUB_DT_24_TABLE_DATA         0x20
231 #define DVBSUB_DT_28_TABLE_DATA         0x21
232 #define DVBSUB_DT_48_TABLE_DATA         0x22
233 #define DVBSUB_DT_END_LINE              0xf0
234 /* List of different Page Composition Segment state */
235 /* According to EN 300-743, 7.2.1 table 3 */
236 #define DVBSUB_PCS_STATE_ACQUISITION    0x01
237 #define DVBSUB_PCS_STATE_CHANGE         0x02
238
239 /*****************************************************************************
240  * Local prototypes
241  *****************************************************************************/
242 static void decode_segment( decoder_t *, bs_t * );
243 static void decode_page_composition( decoder_t *, bs_t * );
244 static void decode_region_composition( decoder_t *, bs_t * );
245 static void decode_object( decoder_t *, bs_t * );
246 static void decode_clut( decoder_t *, bs_t * );
247 static void free_all( decoder_t * );
248
249 static void default_clut_init( decoder_t * );
250
251 static subpicture_t *render( decoder_t * );
252
253 /*****************************************************************************
254  * Open: probe the decoder and return score
255  *****************************************************************************
256  * Tries to launch a decoder and return score so that the interface is able
257  * to chose.
258  *****************************************************************************/
259 static int Open( vlc_object_t *p_this )
260 {
261     decoder_t     *p_dec = (decoder_t *) p_this;
262     decoder_sys_t *p_sys;
263     vlc_value_t    val;
264     int i_posx, i_posy;
265
266     if( p_dec->fmt_in.i_codec != VLC_FOURCC('d','v','b','s') )
267     {
268         return VLC_EGENERIC;
269     }
270
271     p_dec->pf_decode_sub = Decode;
272     p_sys = p_dec->p_sys = malloc( sizeof(decoder_sys_t) );
273     memset( p_sys, 0, sizeof(decoder_sys_t) );
274
275     p_sys->i_pts          = (mtime_t) 0;    
276     p_sys->i_id           = p_dec->fmt_in.subs.dvb.i_id & 0xFFFF;
277     p_sys->i_ancillary_id = p_dec->fmt_in.subs.dvb.i_id >> 16;
278
279     p_sys->p_regions      = NULL;
280     p_sys->p_cluts        = NULL;
281     p_sys->p_page         = NULL;
282
283     var_Create( p_this, DVBSUB_CFG_PREFIX "position",
284                 VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
285     var_Get( p_this, DVBSUB_CFG_PREFIX "position", &val );
286     p_sys->i_spu_position = val.i_int;
287     var_Create( p_this, DVBSUB_CFG_PREFIX "x",
288                 VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
289     var_Get( p_this, DVBSUB_CFG_PREFIX "x", &val );
290     i_posx = val.i_int;
291     var_Create( p_this, DVBSUB_CFG_PREFIX "y",
292                 VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
293     var_Get( p_this, DVBSUB_CFG_PREFIX "y", &val );
294     i_posy = val.i_int;
295
296     /* Check if subpicture position was overridden */
297     p_sys->b_absolute = VLC_TRUE;
298     p_sys->i_spu_x = p_sys->i_spu_y = 0;
299
300     if( i_posx >= 0 && i_posy >= 0 )
301     {
302         p_sys->b_absolute = VLC_FALSE;
303         p_sys->i_spu_x = i_posx;
304         p_sys->i_spu_y = i_posy;
305     }
306
307     es_format_Init( &p_dec->fmt_out, SPU_ES, VLC_FOURCC( 'd','v','b','s' ) );
308
309     default_clut_init( p_dec );
310
311     return VLC_SUCCESS;
312 }
313
314 /*****************************************************************************
315  * Close:
316  *****************************************************************************/
317 static void Close( vlc_object_t *p_this )
318 {
319     decoder_t     *p_dec = (decoder_t*) p_this;
320     decoder_sys_t *p_sys = p_dec->p_sys;
321
322     var_Destroy( p_this, DVBSUB_CFG_PREFIX "x" );
323     var_Destroy( p_this, DVBSUB_CFG_PREFIX "y" );
324     var_Destroy( p_this, DVBSUB_CFG_PREFIX "position" );    
325
326     free_all( p_dec );
327     free( p_sys );
328 }
329
330 /*****************************************************************************
331  * Decode:
332  *****************************************************************************/
333 static subpicture_t *Decode( decoder_t *p_dec, block_t **pp_block )
334 {
335     decoder_sys_t *p_sys = p_dec->p_sys;
336     block_t       *p_block;
337     subpicture_t  *p_spu = NULL;
338
339     if( pp_block == NULL || *pp_block == NULL ) return NULL;
340     p_block = *pp_block;
341     *pp_block = NULL;
342
343     p_sys->i_pts = p_block->i_pts;
344     if( p_sys->i_pts <= 0 )
345     {
346 #ifdef DEBUG_DVBSUB
347         /* Some DVB channels send stuffing segments in non-dated packets so
348          * don't complain too loudly. */
349         msg_Warn( p_dec, "non dated subtitle" );
350 #endif
351         block_Release( p_block );
352         return NULL;
353     }
354
355     bs_init( &p_sys->bs, p_block->p_buffer, p_block->i_buffer );
356
357     if( bs_read( &p_sys->bs, 8 ) != 0x20 ) /* Data identifier */
358     {
359         msg_Dbg( p_dec, "invalid data identifier" );
360         block_Release( p_block );
361         return NULL;
362     }
363
364     if( bs_read( &p_sys->bs, 8 ) ) /* Subtitle stream id */
365     {
366         msg_Dbg( p_dec, "invalid subtitle stream id" );
367         block_Release( p_block );
368         return NULL;
369     }
370
371 #ifdef DEBUG_DVBSUB
372     msg_Dbg( p_dec, "subtitle packet received: "I64Fd, p_sys->i_pts );
373 #endif
374
375     p_sys->b_page = VLC_FALSE;
376     while( bs_show( &p_sys->bs, 8 ) == 0x0f ) /* Sync byte */
377     {
378         decode_segment( p_dec, &p_sys->bs );
379     }
380
381     if( bs_read( &p_sys->bs, 8 ) != 0xff ) /* End marker */
382     {
383         msg_Warn( p_dec, "end marker not found (corrupted subtitle ?)" );
384         block_Release( p_block );
385         return NULL;
386     }
387
388     /* Check if the page is to be displayed */
389     if( p_sys->p_page && p_sys->b_page ) p_spu = render( p_dec );
390
391     block_Release( p_block );
392
393     return p_spu;
394 }
395
396 /* following functions are local */
397
398 /*****************************************************************************
399  * default_clut_init: default clut as defined in EN 300-743 section 10
400  *****************************************************************************/
401 static void default_clut_init( decoder_t *p_dec )
402 {
403     decoder_sys_t *p_sys = p_dec->p_sys;
404     uint8_t i;
405
406 #define RGB_TO_Y(r, g, b) ((int16_t) 77 * r + 150 * g + 29 * b) / 256;
407 #define RGB_TO_U(r, g, b) ((int16_t) -44 * r - 87 * g + 131 * b) / 256;
408 #define RGB_TO_V(r, g, b) ((int16_t) 131 * r - 110 * g - 21 * b) / 256;
409
410     /* 4 entries CLUT */
411     for( i = 0; i < 4; i++ )
412     {
413         uint8_t R = 0, G = 0, B = 0, T = 0;
414
415         if( !(i & 0x2) && !(i & 0x1) ) T = 0xFF;
416         else if( !(i & 0x2) && (i & 0x1) ) R = G = B = 0xFF;
417         else if( (i & 0x2) && !(i & 0x1) ) R = G = B = 0;
418         else R = G = B = 0x7F;
419
420         p_sys->default_clut.c_2b[i].Y = RGB_TO_Y(R,G,B);
421         p_sys->default_clut.c_2b[i].Cr = RGB_TO_U(R,G,B);
422         p_sys->default_clut.c_2b[i].Cb = RGB_TO_V(R,G,B);
423         p_sys->default_clut.c_2b[i].T = T;
424     }
425
426     /* 16 entries CLUT */
427     for( i = 0; i < 16; i++ )
428     {
429         uint8_t R = 0, G = 0, B = 0, T = 0;
430
431         if( !(i & 0x8) )
432         {
433             if( !(i & 0x4) && !(i & 0x2) && !(i & 0x1) )
434             {
435                 T = 0xFF;
436             }
437             else
438             {
439                 R = (i & 0x1) ? 0xFF : 0;
440                 G = (i & 0x2) ? 0xFF : 0;
441                 B = (i & 0x4) ? 0xFF : 0;
442             }
443         }
444         else
445         {
446             R = (i & 0x1) ? 0x7F : 0;
447             G = (i & 0x2) ? 0x7F : 0;
448             B = (i & 0x4) ? 0x7F : 0;
449         }
450
451         p_sys->default_clut.c_4b[i].Y = RGB_TO_Y(R,G,B);
452         p_sys->default_clut.c_4b[i].Cr = RGB_TO_U(R,G,B);
453         p_sys->default_clut.c_4b[i].Cb = RGB_TO_V(R,G,B);
454         p_sys->default_clut.c_4b[i].T = T;
455     }
456
457     /* 256 entries CLUT */
458     memset( p_sys->default_clut.c_8b, 0xFF, 256 * sizeof(dvbsub_color_t) );
459 }
460
461 static void decode_segment( decoder_t *p_dec, bs_t *s )
462 {
463     decoder_sys_t *p_sys = p_dec->p_sys;
464     int i_type;
465     int i_page_id;
466     int i_size;
467
468     /* sync_byte (already checked) */
469     bs_skip( s, 8 );
470
471     /* segment type */
472     i_type = bs_read( s, 8 );
473
474     /* page id */
475     i_page_id = bs_read( s, 16 );
476
477     /* segment size */
478     i_size = bs_show( s, 16 );
479
480     if( i_page_id != p_sys->i_id && i_page_id != p_sys->i_ancillary_id )
481     {
482 #ifdef DEBUG_DVBSUB
483         msg_Dbg( p_dec, "subtitle skipped (page id: %i, %i)",
484                  i_page_id, p_sys->i_id );
485 #endif
486         bs_skip( s,  8 * ( 2 + i_size ) );
487         return;
488     }
489
490     if( p_sys->i_ancillary_id != p_sys->i_id &&
491         i_type == DVBSUB_ST_PAGE_COMPOSITION &&
492         i_page_id == p_sys->i_ancillary_id )
493     {
494 #ifdef DEBUG_DVBSUB
495         msg_Dbg( p_dec, "skipped invalid ancillary subtitle packet" );
496 #endif
497         bs_skip( s,  8 * ( 2 + i_size ) );
498         return;
499     }
500
501 #ifdef DEBUG_DVBSUB
502     if( i_page_id == p_sys->i_id )
503         msg_Dbg( p_dec, "segment (id: %i)", i_page_id );
504     else
505         msg_Dbg( p_dec, "ancillary segment (id: %i)", i_page_id );
506 #endif
507
508     switch( i_type )
509     {
510     case DVBSUB_ST_PAGE_COMPOSITION:
511 #ifdef DEBUG_DVBSUB
512         msg_Dbg( p_dec, "decode_page_composition" );
513 #endif
514         decode_page_composition( p_dec, s );
515         break;
516
517     case DVBSUB_ST_REGION_COMPOSITION:
518 #ifdef DEBUG_DVBSUB
519         msg_Dbg( p_dec, "decode_region_composition" );
520 #endif
521         decode_region_composition( p_dec, s );
522         break;
523
524     case DVBSUB_ST_CLUT_DEFINITION:
525 #ifdef DEBUG_DVBSUB
526         msg_Dbg( p_dec, "decode_clut" );
527 #endif
528         decode_clut( p_dec, s );
529         break;
530
531     case DVBSUB_ST_OBJECT_DATA:
532 #ifdef DEBUG_DVBSUB
533         msg_Dbg( p_dec, "decode_object" );
534 #endif
535         decode_object( p_dec, s );
536         break;
537
538     case DVBSUB_ST_ENDOFDISPLAY:
539 #ifdef DEBUG_DVBSUB
540         msg_Dbg( p_dec, "end of display" );
541 #endif
542         bs_skip( s,  8 * ( 2 + i_size ) );
543         break;
544
545     case DVBSUB_ST_STUFFING:
546 #ifdef DEBUG_DVBSUB
547         msg_Dbg( p_dec, "skip stuffing" );
548 #endif
549         bs_skip( s,  8 * ( 2 + i_size ) );
550         break;
551
552     default:
553         msg_Warn( p_dec, "unsupported segment type: (%04x)", i_type );
554         bs_skip( s,  8 * ( 2 + i_size ) );
555         break;
556     }
557 }
558
559 static void decode_clut( decoder_t *p_dec, bs_t *s )
560 {
561     decoder_sys_t *p_sys = p_dec->p_sys;
562     uint16_t      i_segment_length;
563     uint16_t      i_processed_length;
564     dvbsub_clut_t *p_clut, *p_next;
565     int           i_id, i_version;
566
567     i_segment_length = bs_read( s, 16 );
568     i_id             = bs_read( s, 8 );
569     i_version        = bs_read( s, 4 );
570
571     /* Check if we already have this clut */
572     for( p_clut = p_sys->p_cluts; p_clut != NULL; p_clut = p_clut->p_next )
573     {
574         if( p_clut->i_id == i_id ) break;
575     }
576
577     /* Check version number */
578     if( p_clut && p_clut->i_version == i_version )
579     {
580         /* Nothing to do */
581         bs_skip( s, 8 * i_segment_length - 12 );
582         return;
583     }
584
585     if( !p_clut )
586     {
587 #ifdef DEBUG_DVBSUB
588         msg_Dbg( p_dec, "new clut: %i", i_id );
589 #endif
590         p_clut = malloc( sizeof(dvbsub_clut_t) );
591         p_clut->p_next = p_sys->p_cluts;
592         p_sys->p_cluts = p_clut;
593     }
594
595     /* Initialize to default clut */
596     p_next = p_clut->p_next;
597     *p_clut = p_sys->default_clut;
598     p_clut->p_next = p_next;
599
600     /* We don't have this version of the CLUT: Parse it */
601     p_clut->i_version = i_version;
602     p_clut->i_id = i_id;
603     bs_skip( s, 4 ); /* Reserved bits */
604     i_processed_length = 2;
605     while( i_processed_length < i_segment_length )
606     {
607         uint8_t y, cb, cr, t;
608         uint8_t i_id;
609         uint8_t i_type;
610
611         i_id = bs_read( s, 8 );
612         i_type = bs_read( s, 3 );
613
614         bs_skip( s, 4 );
615
616         if( bs_read( s, 1 ) )
617         {
618             y  = bs_read( s, 8 );
619             cr = bs_read( s, 8 );
620             cb = bs_read( s, 8 );
621             t  = bs_read( s, 8 );
622             i_processed_length += 6;
623         }
624         else
625         {
626             y  = bs_read( s, 6 ) << 2;
627             cr = bs_read( s, 4 ) << 4;
628             cb = bs_read( s, 4 ) << 4;
629             t  = bs_read( s, 2 ) << 6;
630             i_processed_length += 4;
631         }
632
633         /* We are not entirely compliant here as full transparency is indicated
634          * with a luma value of zero, not a transparency value of 0xff
635          * (full transparency would actually be 0xff + 1). */
636         if( y == 0 )
637         {
638             cr = cb = 0;
639             t  = 0xff;
640         }
641
642         /* According to EN 300-743 section 7.2.3 note 1, type should
643          * not have more than 1 bit set to one, but some streams don't
644          * respect this note. */
645         if( i_type & 0x04 && i_id < 4 )
646         {
647             p_clut->c_2b[i_id].Y = y;
648             p_clut->c_2b[i_id].Cr = cr;
649             p_clut->c_2b[i_id].Cb = cb;
650             p_clut->c_2b[i_id].T = t;
651         }
652         if( i_type & 0x02 && i_id < 16 )
653         {
654             p_clut->c_4b[i_id].Y = y;
655             p_clut->c_4b[i_id].Cr = cr;
656             p_clut->c_4b[i_id].Cb = cb;
657             p_clut->c_4b[i_id].T = t;
658         }
659         if( i_type & 0x01 )
660         {
661             p_clut->c_8b[i_id].Y = y;
662             p_clut->c_8b[i_id].Cr = cr;
663             p_clut->c_8b[i_id].Cb = cb;
664             p_clut->c_8b[i_id].T = t;
665         }
666     }
667 }
668
669 static void decode_page_composition( decoder_t *p_dec, bs_t *s )
670 {
671     decoder_sys_t *p_sys = p_dec->p_sys;
672     int i_version, i_state, i_segment_length, i_timeout, i;
673
674     /* A page is composed by 0 or more region */
675     i_segment_length = bs_read( s, 16 );
676     i_timeout = bs_read( s, 8 );
677     i_version = bs_read( s, 4 );
678     i_state = bs_read( s, 2 );
679     bs_skip( s, 2 ); /* Reserved */
680
681     if( i_state == DVBSUB_PCS_STATE_CHANGE )
682     {
683         /* End of an epoch, reset decoder buffer */
684 #ifdef DEBUG_DVBSUB
685         msg_Dbg( p_dec, "page composition mode change" );
686 #endif
687         free_all( p_dec );
688     }
689     else if( !p_sys->p_page && i_state != DVBSUB_PCS_STATE_ACQUISITION &&
690              i_state != DVBSUB_PCS_STATE_CHANGE )
691     {
692         /* Not a full PCS, we need to wait for one */
693         msg_Dbg( p_dec, "didn't receive an acquisition page yet" );
694
695 #if 0
696         /* Try to start decoding even without an acquisition page */
697         bs_skip( s,  8 * (i_segment_length - 2) );
698         return;
699 #endif
700     }
701
702 #ifdef DEBUG_DVBSUB
703     if( i_state == DVBSUB_PCS_STATE_ACQUISITION )
704         msg_Dbg( p_dec, "acquisition page composition" );
705 #endif
706
707     /* Check version number */
708     if( p_sys->p_page && p_sys->p_page->i_version == i_version )
709     {
710         bs_skip( s,  8 * (i_segment_length - 2) );
711         return;
712     }
713     else if( p_sys->p_page )
714     {
715         if( p_sys->p_page->i_region_defs )
716             free( p_sys->p_page->p_region_defs );
717         p_sys->p_page->i_region_defs = 0;
718     }
719
720     if( !p_sys->p_page )
721     {
722 #ifdef DEBUG_DVBSUB
723         msg_Dbg( p_dec, "new page" );
724 #endif
725         /* Allocate a new page */
726         p_sys->p_page = malloc( sizeof(dvbsub_page_t) );
727     }
728
729     p_sys->p_page->i_version = i_version;
730     p_sys->p_page->i_timeout = i_timeout;
731     p_sys->b_page = VLC_TRUE;
732
733     /* Number of regions */
734     p_sys->p_page->i_region_defs = (i_segment_length - 2) / 6;
735
736     if( p_sys->p_page->i_region_defs == 0 ) return;
737
738     p_sys->p_page->p_region_defs =
739         malloc( p_sys->p_page->i_region_defs * sizeof(dvbsub_region_t) );
740     for( i = 0; i < p_sys->p_page->i_region_defs; i++ )
741     {
742         p_sys->p_page->p_region_defs[i].i_id = bs_read( s, 8 );
743         bs_skip( s, 8 ); /* Reserved */
744         p_sys->p_page->p_region_defs[i].i_x = bs_read( s, 16 );
745         p_sys->p_page->p_region_defs[i].i_y = bs_read( s, 16 );
746
747 #ifdef DEBUG_DVBSUB
748         msg_Dbg( p_dec, "page_composition, region %i (%i,%i)",
749                  i, p_sys->p_page->p_region_defs[i].i_x,
750                  p_sys->p_page->p_region_defs[i].i_y );
751 #endif
752     }
753 }
754
755 static void decode_region_composition( decoder_t *p_dec, bs_t *s )
756 {
757     decoder_sys_t *p_sys = p_dec->p_sys;
758     dvbsub_region_t *p_region, **pp_region = &p_sys->p_regions;
759     int i_segment_length, i_processed_length, i_id, i_version;
760     int i_width, i_height, i_level_comp, i_depth, i_clut;
761     int i_8_bg, i_4_bg, i_2_bg;
762     vlc_bool_t b_fill;
763
764     i_segment_length = bs_read( s, 16 );
765     i_id = bs_read( s, 8 );
766     i_version = bs_read( s, 4 );
767
768     /* Check if we already have this region */
769     for( p_region = p_sys->p_regions; p_region != NULL;
770          p_region = p_region->p_next )
771     {
772         pp_region = &p_region->p_next;
773         if( p_region->i_id == i_id ) break;
774     }
775
776     /* Check version number */
777     if( p_region && p_region->i_version == i_version )
778     {
779         bs_skip( s, 8 * (i_segment_length - 1) - 4 );
780         return;
781     }
782
783     if( !p_region )
784     {
785 #ifdef DEBUG_DVBSUB
786         msg_Dbg( p_dec, "new region: %i", i_id );
787 #endif
788         p_region = *pp_region = malloc( sizeof(dvbsub_region_t) );
789         memset( p_region, 0, sizeof(dvbsub_region_t) );
790         p_region->p_object_defs = NULL;
791         p_region->p_pixbuf = NULL;
792         p_region->p_next = NULL;
793     }
794
795     /* Region attributes */
796     p_region->i_id = i_id;
797     p_region->i_version = i_version;
798     b_fill = bs_read( s, 1 );
799     bs_skip( s, 3 ); /* Reserved */
800
801     i_width = bs_read( s, 16 );
802     i_height = bs_read( s, 16 );
803 #ifdef DEBUG_DVBSUB
804     msg_Dbg( p_dec, " width=%d height=%d", i_width, i_height );
805 #endif
806     i_level_comp = bs_read( s, 3 );
807     i_depth = bs_read( s, 3 );
808     bs_skip( s, 2 ); /* Reserved */
809     i_clut = bs_read( s, 8 );
810
811     i_8_bg = bs_read( s, 8 );
812     i_4_bg = bs_read( s, 4 );
813     i_2_bg = bs_read( s, 2 );
814     bs_skip( s, 2 ); /* Reserved */
815
816     /* Free old object defs */
817     while( p_region->i_object_defs )
818     {
819         int i = p_region->i_object_defs - 1;
820         if( p_region->p_object_defs[i].psz_text )
821             free( p_region->p_object_defs[i].psz_text );
822         if( !i ) free( p_region->p_object_defs );
823
824         p_region->i_object_defs--;
825     }
826     p_region->p_object_defs = NULL;
827
828     /* Extra sanity checks */
829     if( p_region->i_width != i_width || p_region->i_height != i_height )
830     {
831         if( p_region->p_pixbuf )
832         {
833             msg_Dbg( p_dec, "region size changed (%dx%d->%dx%d)",
834                      p_region->i_width, p_region->i_height, i_width, i_height );
835             free( p_region->p_pixbuf );
836         }
837
838         p_region->p_pixbuf = malloc( i_height * i_width );
839         p_region->i_depth = 0;
840         b_fill = VLC_TRUE;
841     }
842     if( p_region->i_depth && (p_region->i_depth != i_depth ||
843         p_region->i_level_comp != i_level_comp || p_region->i_clut != i_clut) )
844     {
845         msg_Dbg( p_dec, "region parameters changed (not allowed)" );
846     }
847
848     /* Erase background of region */
849     if( b_fill )
850     {
851         int i_background = (p_region->i_depth == 1) ? i_2_bg :
852             (p_region->i_depth == 2) ? i_4_bg : i_8_bg;
853         memset( p_region->p_pixbuf, i_background, i_width * i_height );
854     }
855
856     p_region->i_width = i_width;
857     p_region->i_height = i_height;
858     p_region->i_level_comp = i_level_comp;
859     p_region->i_depth = i_depth;
860     p_region->i_clut = i_clut;
861
862     /* List of objects in the region */
863     i_processed_length = 10;
864     while( i_processed_length < i_segment_length )
865     {
866         dvbsub_objectdef_t *p_obj;
867
868         /* We create a new object */
869         p_region->i_object_defs++;
870         p_region->p_object_defs =
871             realloc( p_region->p_object_defs,
872                      sizeof(dvbsub_objectdef_t) * p_region->i_object_defs );
873
874         /* We parse object properties */
875         p_obj = &p_region->p_object_defs[p_region->i_object_defs - 1];
876         p_obj->i_id         = bs_read( s, 16 );
877         p_obj->i_type       = bs_read( s, 2 );
878         bs_skip( s, 2 ); /* Provider */
879         p_obj->i_x          = bs_read( s, 12 );
880         bs_skip( s, 4 ); /* Reserved */
881         p_obj->i_y          = bs_read( s, 12 );
882         p_obj->psz_text     = 0;
883
884         i_processed_length += 6;
885
886         if( p_obj->i_type == DVBSUB_OT_BASIC_CHAR ||
887             p_obj->i_type == DVBSUB_OT_COMPOSITE_STRING )
888         {
889             p_obj->i_fg_pc =  bs_read( s, 8 );
890             p_obj->i_bg_pc =  bs_read( s, 8 );
891             i_processed_length += 2;
892         }
893     }
894 }
895
896 static void dvbsub_render_pdata( decoder_t *, dvbsub_region_t *, int, int,
897                                  uint8_t *, int );
898 static void dvbsub_pdata2bpp( bs_t *, uint8_t *, int, int * );
899 static void dvbsub_pdata4bpp( bs_t *, uint8_t *, int, int * );
900 static void dvbsub_pdata8bpp( bs_t *, uint8_t *, int, int * );
901
902 static void decode_object( decoder_t *p_dec, bs_t *s )
903 {
904     decoder_sys_t *p_sys = p_dec->p_sys;
905     dvbsub_region_t *p_region;
906     int i_segment_length, i_coding_method, i_version, i_id, i;
907     vlc_bool_t b_non_modify_color;
908
909     /* ETSI 300-743 paragraph 7.2.4
910      * sync_byte, segment_type and page_id have already been processed.
911      */
912     i_segment_length = bs_read( s, 16 );
913     i_id             = bs_read( s, 16 );
914     i_version        = bs_read( s, 4 );
915     i_coding_method  = bs_read( s, 2 );
916
917     if( i_coding_method > 1 )
918     {
919         msg_Dbg( p_dec, "unknown DVB subtitling coding %d is not handled!", i_coding_method );
920         bs_skip( s, 8 * (i_segment_length - 2) - 6 );
921         return;
922     }
923
924     /* Check if the object needs to be rendered in at least one
925      * of the regions */
926     for( p_region = p_sys->p_regions; p_region != NULL;
927          p_region = p_region->p_next )
928     {
929         for( i = 0; i < p_region->i_object_defs; i++ )
930             if( p_region->p_object_defs[i].i_id == i_id ) break;
931
932         if( i != p_region->i_object_defs ) break;
933     }
934     if( !p_region )
935     {
936         bs_skip( s, 8 * (i_segment_length - 2) - 6 );
937         return;
938     }
939
940 #ifdef DEBUG_DVBSUB
941     msg_Dbg( p_dec, "new object: %i", i_id );
942 #endif
943
944     b_non_modify_color = bs_read( s, 1 );
945     bs_skip( s, 1 ); /* Reserved */
946
947     if( i_coding_method == 0x00 )
948     {
949         int i_topfield, i_bottomfield;
950         uint8_t *p_topfield, *p_bottomfield;
951
952         i_topfield    = bs_read( s, 16 );
953         i_bottomfield = bs_read( s, 16 );
954         p_topfield    = s->p_start + bs_pos( s ) / 8;
955         p_bottomfield = p_topfield + i_topfield;
956
957         bs_skip( s, 8 * (i_segment_length - 7) );
958
959         /* Sanity check */
960         if( i_segment_length < i_topfield + i_bottomfield + 7 ||
961             p_topfield + i_topfield + i_bottomfield > s->p_end )
962         {
963             msg_Dbg( p_dec, "corrupted object data" );
964             return;
965         }
966
967         for( p_region = p_sys->p_regions; p_region != NULL;
968              p_region = p_region->p_next )
969         {
970             for( i = 0; i < p_region->i_object_defs; i++ )
971             {
972                 if( p_region->p_object_defs[i].i_id != i_id ) continue;
973
974                 dvbsub_render_pdata( p_dec, p_region,
975                                      p_region->p_object_defs[i].i_x,
976                                      p_region->p_object_defs[i].i_y,
977                                      p_topfield, i_topfield );
978
979                 if( i_bottomfield )
980                 {
981                     dvbsub_render_pdata( p_dec, p_region,
982                                          p_region->p_object_defs[i].i_x,
983                                          p_region->p_object_defs[i].i_y + 1,
984                                          p_bottomfield, i_bottomfield );
985                 }
986                 else
987                 {
988                     /* Duplicate the top field */
989                     dvbsub_render_pdata( p_dec, p_region,
990                                          p_region->p_object_defs[i].i_x,
991                                          p_region->p_object_defs[i].i_y + 1,
992                                          p_topfield, i_topfield );
993                 }
994             }
995         }
996     }
997     else
998     {
999         /* DVB subtitling as characters */
1000         int i_number_of_codes = bs_read( s, 8 );
1001         uint8_t* p_start = s->p_start + bs_pos( s ) / 8;
1002
1003         /* Sanity check */
1004         if( i_segment_length <  i_number_of_codes*2 + 4 ||
1005             p_start + i_number_of_codes*2 > s->p_end )
1006         {
1007             msg_Dbg( p_dec, "corrupted object data" );
1008             return;
1009         }
1010
1011         for( p_region = p_sys->p_regions; p_region != NULL;
1012              p_region = p_region->p_next )
1013         {
1014             for( i = 0; i < p_region->i_object_defs; i++ )
1015             {
1016                 int j;
1017
1018                 if( p_region->p_object_defs[i].i_id != i_id ) continue;
1019
1020                 p_region->p_object_defs[i].psz_text =
1021                     realloc( p_region->p_object_defs[i].psz_text,
1022                              i_number_of_codes + 1 );
1023
1024                 for( j = 0; j < i_number_of_codes; j++ )
1025                 {
1026                     p_region->p_object_defs[i].psz_text[j] = bs_read( s, 16 );
1027                 }
1028                 p_region->p_object_defs[i].psz_text[j] = 0;
1029             }
1030         }
1031     }
1032
1033 #ifdef DEBUG_DVBSUB
1034     msg_Dbg( p_dec, "end object: %i", i_id );
1035 #endif
1036 }
1037
1038 static void dvbsub_render_pdata( decoder_t *p_dec, dvbsub_region_t *p_region,
1039                                  int i_x, int i_y,
1040                                  uint8_t *p_field, int i_field )
1041 {
1042     uint8_t *p_pixbuf;
1043     int i_offset = 0;
1044     bs_t bs;
1045
1046     /* Sanity check */
1047     if( !p_region->p_pixbuf )
1048     {
1049         msg_Err( p_dec, "region %i has no pixel buffer!", p_region->i_id );
1050         return;
1051     }
1052     if( i_y < 0 || i_x < 0 || i_y >= p_region->i_height ||
1053         i_x >= p_region->i_width )
1054     {
1055         msg_Dbg( p_dec, "invalid offset (%i,%i)", i_x, i_y );
1056         return;
1057     }
1058
1059     p_pixbuf = p_region->p_pixbuf + i_y * p_region->i_width;
1060     bs_init( &bs, p_field, i_field );
1061
1062     while( !bs_eof( &bs ) )
1063     {
1064         /* Sanity check */
1065         if( i_y >= p_region->i_height ) return;
1066
1067         switch( bs_read( &bs, 8 ) )
1068         {
1069         case 0x10:
1070             dvbsub_pdata2bpp( &bs, p_pixbuf + i_x, p_region->i_width - i_x,
1071                               &i_offset );
1072             break;
1073
1074         case 0x11:
1075             dvbsub_pdata4bpp( &bs, p_pixbuf + i_x, p_region->i_width - i_x,
1076                               &i_offset );
1077             break;
1078
1079         case 0x12:
1080             dvbsub_pdata8bpp( &bs, p_pixbuf + i_x, p_region->i_width - i_x,
1081                               &i_offset );
1082             break;
1083
1084         case 0x20:
1085         case 0x21:
1086         case 0x22:
1087             /* We don't use map tables */
1088             break;
1089
1090         case 0xf0: /* End of line code */
1091             p_pixbuf += 2*p_region->i_width;
1092             i_offset = 0; i_y += 2;
1093             break;
1094         }
1095     }
1096 }
1097
1098 static void dvbsub_pdata2bpp( bs_t *s, uint8_t *p, int i_width, int *pi_off )
1099 {
1100     vlc_bool_t b_stop = 0;
1101
1102     while( !b_stop && !bs_eof( s ) )
1103     {
1104         int i_count = 0, i_color = 0;
1105
1106         if( (i_color = bs_read( s, 2 )) != 0x00 )
1107         {
1108             i_count = 1;
1109         }
1110         else
1111         {
1112             if( bs_read( s, 1 ) == 0x01 )         // Switch1
1113             {
1114                 i_count = 3 + bs_read( s, 3 );
1115                 i_color = bs_read( s, 2 );
1116             }
1117             else
1118             {
1119                 if( bs_read( s, 1 ) == 0x00 )     //Switch2
1120                 {
1121                     switch( bs_read( s, 2 ) )     //Switch3
1122                     {
1123                     case 0x00:
1124                         b_stop = 1;
1125                         break;
1126                     case 0x01:
1127                         i_count = 2;
1128                         break;
1129                     case 0x02:
1130                         i_count =  12 + bs_read( s, 4 );
1131                         i_color = bs_read( s, 2 );
1132                         break;
1133                     case 0x03:
1134                         i_count =  29 + bs_read( s, 8 );
1135                         i_color = bs_read( s, 2 );
1136                         break;
1137                     default:
1138                         break;
1139                     }
1140                 }
1141                 else
1142                 {
1143                     /* 1 pixel color 0 */
1144                     i_count = 1;
1145                 }
1146             }
1147         }
1148
1149         if( !i_count ) continue;
1150
1151         /* Sanity check */
1152         if( i_count + *pi_off > i_width ) break;
1153
1154         if( i_count == 1 ) p[*pi_off] = i_color;
1155         else memset( p + *pi_off, i_color, i_count );
1156
1157         (*pi_off) += i_count;
1158     }
1159
1160     bs_align( s );
1161 }
1162
1163 static void dvbsub_pdata4bpp( bs_t *s, uint8_t *p, int i_width, int *pi_off )
1164 {
1165     vlc_bool_t b_stop = 0;
1166
1167     while( !b_stop && !bs_eof( s ) )
1168     {
1169         int i_count = 0, i_color = 0;
1170
1171         if( (i_color = bs_read( s, 4 )) != 0x00 )
1172         {
1173             /* Add 1 pixel */
1174             i_count = 1;
1175         }
1176         else
1177         {
1178             if( bs_read( s, 1 ) == 0x00 )           // Switch1
1179             {
1180                 if( bs_show( s, 3 ) != 0x00 )
1181                 {
1182                     i_count = 2 + bs_read( s, 3 );
1183                 }
1184                 else
1185                 {
1186                     bs_skip( s, 3 );
1187                     b_stop = 1;
1188                 }
1189             }
1190             else
1191             {
1192                 if( bs_read( s, 1 ) == 0x00)        //Switch2
1193                 {
1194                     i_count =  4 + bs_read( s, 2 );
1195                     i_color = bs_read( s, 4 );
1196                 }
1197                 else
1198                 {
1199                     switch ( bs_read( s, 2 ) )     //Switch3
1200                     {
1201                     case 0x0:
1202                         i_count = 1;
1203                         break;
1204                     case 0x1:
1205                         i_count = 2;
1206                         break;
1207                     case 0x2:
1208                         i_count = 9 + bs_read( s, 4 );
1209                         i_color = bs_read( s, 4 );
1210                         break;
1211                     case 0x3:
1212                         i_count= 25 + bs_read( s, 8 );
1213                         i_color = bs_read( s, 4 );
1214                         break;
1215                     }
1216                 }
1217             }
1218         }
1219
1220         if( !i_count ) continue;
1221
1222         /* Sanity check */
1223         if( i_count + *pi_off > i_width ) break;
1224
1225         if( i_count == 1 ) p[*pi_off] = i_color;
1226         else memset( p + *pi_off, i_color, i_count );
1227
1228         (*pi_off) += i_count;
1229     }
1230
1231     bs_align( s );
1232 }
1233
1234 static void dvbsub_pdata8bpp( bs_t *s, uint8_t *p, int i_width, int *pi_off )
1235 {
1236     vlc_bool_t b_stop = 0;
1237
1238     while( !b_stop && !bs_eof( s ) )
1239     {
1240         int i_count = 0, i_color = 0;
1241
1242         if( (i_color = bs_read( s, 8 )) != 0x00 )
1243         {
1244             /* Add 1 pixel */
1245             i_count = 1;
1246         }
1247         else
1248         {
1249             if( bs_read( s, 1 ) == 0x00 )           // Switch1
1250             {
1251                 if( bs_show( s, 7 ) != 0x00 )
1252                 {
1253                     i_count = bs_read( s, 7 );
1254                 }
1255                 else
1256                 {
1257                     bs_skip( s, 7 );
1258                     b_stop = 1;
1259                 }
1260             }
1261             else
1262             {
1263                 i_count = bs_read( s, 7 );
1264                 i_color = bs_read( s, 8 );
1265             }
1266         }
1267
1268         if( !i_count ) continue;
1269
1270         /* Sanity check */
1271         if( i_count + *pi_off > i_width ) break;
1272
1273         if( i_count == 1 ) p[*pi_off] = i_color;
1274         else memset( p + *pi_off, i_color, i_count );
1275
1276         (*pi_off) += i_count;
1277     }
1278
1279     bs_align( s );
1280 }
1281
1282 static void free_all( decoder_t *p_dec )
1283 {
1284     decoder_sys_t *p_sys = p_dec->p_sys;
1285     dvbsub_region_t *p_reg, *p_reg_next;
1286     dvbsub_clut_t *p_clut, *p_clut_next;
1287
1288     for( p_clut = p_sys->p_cluts; p_clut != NULL; p_clut = p_clut_next )
1289     {
1290         p_clut_next = p_clut->p_next;
1291         free( p_clut );
1292     }
1293     p_sys->p_cluts = NULL;
1294
1295     for( p_reg = p_sys->p_regions; p_reg != NULL; p_reg = p_reg_next )
1296     {
1297         int i;
1298
1299         p_reg_next = p_reg->p_next;
1300         for( i = 0; i < p_reg->i_object_defs; i++ )
1301             if( p_reg->p_object_defs[i].psz_text )
1302                 free( p_reg->p_object_defs[i].psz_text );
1303         if( p_reg->i_object_defs ) free( p_reg->p_object_defs );
1304         if( p_reg->p_pixbuf ) free( p_reg->p_pixbuf );
1305         free( p_reg );
1306     }
1307     p_sys->p_regions = NULL;
1308
1309     if( p_sys->p_page )
1310     {
1311         if( p_sys->p_page->i_region_defs )
1312             free( p_sys->p_page->p_region_defs );
1313         free( p_sys->p_page );
1314     }
1315     p_sys->p_page = NULL;
1316 }
1317
1318 static subpicture_t *render( decoder_t *p_dec )
1319 {
1320     decoder_sys_t *p_sys = p_dec->p_sys;
1321     subpicture_t *p_spu;
1322     subpicture_region_t **pp_spu_region;
1323     int i, j, i_timeout = 0;
1324
1325     /* Allocate the subpicture internal data. */
1326     p_spu = p_dec->pf_spu_buffer_new( p_dec );
1327     if( !p_spu ) return NULL;
1328
1329     pp_spu_region = &p_spu->p_region;
1330
1331     /* Loop on region definitions */
1332 #ifdef DEBUG_DVBSUB
1333     if( p_sys->p_page )
1334         msg_Dbg( p_dec, "rendering %i regions", p_sys->p_page->i_region_defs );
1335 #endif
1336
1337     for( i = 0; p_sys->p_page && i < p_sys->p_page->i_region_defs; i++ )
1338     {
1339         dvbsub_region_t     *p_region;
1340         dvbsub_regiondef_t  *p_regiondef;
1341         dvbsub_clut_t       *p_clut;
1342         dvbsub_color_t      *p_color;
1343         subpicture_region_t *p_spu_region;
1344         uint8_t *p_src, *p_dst;
1345         video_format_t fmt;
1346         int i_pitch;
1347
1348         i_timeout = p_sys->p_page->i_timeout;
1349
1350         p_regiondef = &p_sys->p_page->p_region_defs[i];
1351
1352 #ifdef DEBUG_DVBSUB
1353         msg_Dbg( p_dec, "rendering region %i (%i,%i)", i,
1354                  p_regiondef->i_x, p_regiondef->i_y );
1355 #endif
1356
1357         /* Find associated region */
1358         for( p_region = p_sys->p_regions; p_region != NULL;
1359              p_region = p_region->p_next )
1360         {
1361             if( p_regiondef->i_id == p_region->i_id ) break;
1362         }
1363
1364         if( !p_region )
1365         {
1366             msg_Dbg( p_dec, "region %i not found", p_regiondef->i_id );
1367             continue;
1368         }
1369
1370         /* Find associated CLUT */
1371         for( p_clut = p_sys->p_cluts; p_clut != NULL; p_clut = p_clut->p_next )
1372         {
1373             if( p_region->i_clut == p_clut->i_id ) break;
1374         }
1375         if( !p_clut )
1376         {
1377             msg_Dbg( p_dec, "clut %i not found", p_region->i_clut );
1378             continue;
1379         }
1380
1381         /* Create new SPU region */
1382         memset( &fmt, 0, sizeof(video_format_t) );
1383         fmt.i_chroma = VLC_FOURCC('Y','U','V','P');
1384         fmt.i_aspect = 0; /* 0 means use aspect ratio of background video */
1385         fmt.i_width = fmt.i_visible_width = p_region->i_width;
1386         fmt.i_height = fmt.i_visible_height = p_region->i_height;
1387         fmt.i_x_offset = fmt.i_y_offset = 0;
1388         p_spu_region = p_spu->pf_create_region( VLC_OBJECT(p_dec), &fmt );
1389         if( !p_spu_region )
1390         {
1391             msg_Err( p_dec, "cannot allocate SPU region" );
1392             continue;
1393         }
1394         p_spu_region->i_x = p_regiondef->i_x;
1395         p_spu_region->i_y = p_regiondef->i_y;
1396         *pp_spu_region = p_spu_region;
1397         pp_spu_region = &p_spu_region->p_next;
1398
1399         /* Build palette */
1400         fmt.p_palette->i_entries = p_region->i_depth == 1 ? 4 :
1401             p_region->i_depth == 2 ? 16 : 256;
1402         p_color = (p_region->i_depth == 1) ? p_clut->c_2b :
1403             (p_region->i_depth == 2) ? p_clut->c_4b : p_clut->c_8b;
1404         for( j = 0; j < fmt.p_palette->i_entries; j++ )
1405         {
1406             fmt.p_palette->palette[j][0] = p_color[j].Y;
1407             fmt.p_palette->palette[j][1] = p_color[j].Cr;
1408             fmt.p_palette->palette[j][2] = p_color[j].Cb;
1409             fmt.p_palette->palette[j][3] = 0xff - p_color[j].T;
1410         }
1411
1412         p_src = p_region->p_pixbuf;
1413         p_dst = p_spu_region->picture.Y_PIXELS;
1414         i_pitch = p_spu_region->picture.Y_PITCH;
1415
1416         /* Copy pixel buffer */
1417         for( j = 0; j < p_region->i_height; j++ )
1418         {
1419             memcpy( p_dst, p_src, p_region->i_width );
1420             p_src += p_region->i_width;
1421             p_dst += i_pitch;
1422         }
1423
1424         /* Check subtitles encoded as strings of characters
1425          * (since there are not rendered in the pixbuffer) */
1426         for( j = 0; j < p_region->i_object_defs; j++ )
1427         {
1428             dvbsub_objectdef_t *p_object_def = &p_region->p_object_defs[j];
1429
1430             if( p_object_def->i_type != 1 || !p_object_def->psz_text )
1431                 continue;
1432
1433             /* Create new SPU region */
1434             memset( &fmt, 0, sizeof(video_format_t) );
1435             fmt.i_chroma = VLC_FOURCC('T','E','X','T');
1436             fmt.i_aspect = VOUT_ASPECT_FACTOR;
1437             fmt.i_width = fmt.i_visible_width = p_region->i_width;
1438             fmt.i_height = fmt.i_visible_height = p_region->i_height;
1439             fmt.i_x_offset = fmt.i_y_offset = 0;
1440             p_spu_region = p_spu->pf_create_region( VLC_OBJECT(p_dec), &fmt );
1441             if( !p_region )
1442             {
1443                 msg_Err( p_dec, "cannot allocate SPU region" );
1444                 continue;
1445             }
1446
1447             p_spu_region->psz_text = strdup( p_object_def->psz_text );
1448             p_spu_region->i_x = p_regiondef->i_x + p_object_def->i_x;
1449             p_spu_region->i_y = p_regiondef->i_y + p_object_def->i_y;
1450             *pp_spu_region = p_spu_region;
1451             pp_spu_region = &p_spu_region->p_next;
1452         }
1453     }
1454
1455     /* Set the pf_render callback */
1456     p_spu->i_start = p_sys->i_pts;
1457     p_spu->i_stop = p_spu->i_start + (mtime_t) (i_timeout * 1000000);
1458     p_spu->b_ephemer = VLC_TRUE;
1459     p_spu->b_fade = VLC_TRUE;
1460
1461     /* Correct positioning of SPU */
1462     p_spu->b_absolute = p_sys->b_absolute;
1463     p_spu->i_flags = p_sys->i_spu_position;
1464     p_spu->i_x = p_sys->i_spu_x;
1465     p_spu->i_y = p_sys->i_spu_y;
1466
1467     return p_spu;
1468 }
1469
1470 /*****************************************************************************
1471  * encoder_sys_t : encoder descriptor
1472  *****************************************************************************/
1473 typedef struct encoder_region_t
1474 {
1475     int i_width;
1476     int i_height;
1477
1478 } encoder_region_t;
1479
1480 struct encoder_sys_t
1481 {
1482     unsigned int i_page_ver;
1483     unsigned int i_region_ver;
1484     unsigned int i_clut_ver;
1485
1486     int i_regions;
1487     encoder_region_t *p_regions;
1488
1489     mtime_t i_pts;
1490
1491     /* subpicture positioning */
1492     int i_offset_x;
1493     int i_offset_y;
1494 };
1495
1496 static void encode_page_composition( encoder_t *, bs_t *, subpicture_t * );
1497 static void encode_clut( encoder_t *, bs_t *, subpicture_t * );
1498 static void encode_region_composition( encoder_t *, bs_t *, subpicture_t * );
1499 static void encode_object( encoder_t *, bs_t *, subpicture_t * );
1500
1501 /*****************************************************************************
1502  * OpenEncoder: probe the encoder and return score
1503  *****************************************************************************/
1504 static int OpenEncoder( vlc_object_t *p_this )
1505 {
1506     encoder_t *p_enc = (encoder_t *)p_this;
1507     encoder_sys_t *p_sys;
1508     vlc_value_t val;
1509
1510     if( p_enc->fmt_out.i_codec != VLC_FOURCC('d','v','b','s') &&
1511         !p_enc->b_force )
1512     {
1513         return VLC_EGENERIC;
1514     }
1515
1516     /* Allocate the memory needed to store the decoder's structure */
1517     if( ( p_sys = (encoder_sys_t *)malloc(sizeof(encoder_sys_t)) ) == NULL )
1518     {
1519         msg_Err( p_enc, "out of memory" );
1520         return VLC_ENOMEM;
1521     }
1522     p_enc->p_sys = p_sys;
1523
1524     p_enc->pf_encode_sub = Encode;
1525     p_enc->fmt_out.i_codec = VLC_FOURCC('d','v','b','s');
1526     p_enc->fmt_out.subs.dvb.i_id  = 1 << 16 | 1;
1527
1528     sout_CfgParse( p_enc, ENC_CFG_PREFIX, ppsz_enc_options, p_enc->p_cfg );
1529
1530     p_sys->i_page_ver = 0;
1531     p_sys->i_region_ver = 0;
1532     p_sys->i_clut_ver = 0;
1533     p_sys->i_regions = 0;
1534     p_sys->p_regions = 0;
1535
1536     var_Create( p_this, ENC_CFG_PREFIX "x", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
1537     var_Get( p_this, ENC_CFG_PREFIX "x", &val );
1538     p_sys->i_offset_x = val.i_int;
1539     var_Create( p_this, ENC_CFG_PREFIX "y", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
1540     var_Get( p_this, ENC_CFG_PREFIX "y", &val );
1541     p_sys->i_offset_y = val.i_int;
1542
1543     return VLC_SUCCESS;
1544 }
1545
1546 /* FIXME: this routine is a hack to convert VLC_FOURCC('Y','U','V','A') 
1547  *        into VLC_FOURCC('Y','U','V','P')
1548  */
1549 static subpicture_t *YuvaYuvp( encoder_t *p_enc, subpicture_t *p_subpic )
1550 {
1551     subpicture_region_t *p_region = NULL;
1552
1553     if( !p_subpic ) return NULL;
1554
1555     for( p_region = p_subpic->p_region; p_region; p_region = p_region->p_next )
1556     {
1557         video_format_t *p_fmt = &p_region->fmt;
1558         int i = 0, j = 0, n = 0, p = 0;
1559         int i_max_entries = 256;
1560
1561 #ifdef RANDOM_DITHERING
1562         int i_seed = 0xdeadbeef; /* random seed */
1563 #else
1564         int *pi_delta;
1565 #endif
1566         int i_pixels = p_region->picture.p[0].i_visible_lines
1567                         * p_region->picture.p[0].i_pitch;
1568         int i_iterator = p_region->picture.p[0].i_visible_lines * 3 / 4
1569                             * p_region->picture.p[0].i_pitch
1570                         + p_region->picture.p[0].i_pitch * 1 / 3;
1571         int i_tolerance = 0;
1572
1573 #if DEBUG_DVBSUB
1574         msg_Dbg( p_enc, "YuvaYuvp: i_pixels=%d, i_iterator=%d", i_pixels, i_iterator );
1575 #endif
1576         p_fmt->i_chroma = VLC_FOURCC('Y','U','V','P');
1577         p_fmt->p_palette = (video_palette_t *) malloc( sizeof( video_palette_t ) );
1578         if( !p_fmt->p_palette ) break;
1579         p_fmt->p_palette->i_entries = 0;
1580
1581         /* Find best iterator using Euclide’s algorithm */
1582         for( ; i_iterator > 1 ; i_iterator-- )
1583         {
1584             int a = i_pixels;
1585             int b = i_iterator;
1586             int c;
1587
1588             while( b )
1589             {
1590                 c = a % b;
1591                 a = b;
1592                 b = c;
1593             }
1594
1595             if( a == 1 )
1596             {
1597                 break;
1598             }
1599         }
1600
1601         /* Count colors, build best palette */
1602         for( i_tolerance = 0; i_tolerance < 128; i_tolerance++ )
1603         {
1604             vlc_bool_t b_success = VLC_TRUE;
1605             p_fmt->p_palette->i_entries = 0;
1606
1607             for( i = 0; i < i_pixels ; )
1608             {
1609                 uint8_t y, u, v, a;
1610                 y = p_region->picture.p[0].p_pixels[i];
1611                 u = p_region->picture.p[1].p_pixels[i];
1612                 v = p_region->picture.p[2].p_pixels[i];
1613                 a = p_region->picture.p[3].p_pixels[i];
1614                 for( j = 0; j < p_fmt->p_palette->i_entries; j++ )
1615                 {
1616                     if( abs((int)p_fmt->p_palette->palette[j][0] - (int)y) <= i_tolerance &&
1617                         abs((int)p_fmt->p_palette->palette[j][1] - (int)u) <= i_tolerance &&
1618                         abs((int)p_fmt->p_palette->palette[j][2] - (int)v) <= i_tolerance &&
1619                         abs((int)p_fmt->p_palette->palette[j][3] - (int)a) <= i_tolerance / 2 )
1620                     {
1621                         break;
1622                     }
1623                 }
1624                 if( j == p_fmt->p_palette->i_entries )
1625                 {
1626                     p_fmt->p_palette->palette[j][0] = y;
1627                     p_fmt->p_palette->palette[j][1] = u;
1628                     p_fmt->p_palette->palette[j][2] = v;
1629                     p_fmt->p_palette->palette[j][3] = a;
1630                     p_fmt->p_palette->i_entries++;
1631                 }
1632                 if( p_fmt->p_palette->i_entries >= i_max_entries )
1633                 {
1634                     b_success = VLC_FALSE;
1635                     break;
1636                 }
1637                 i += i_iterator;
1638                 if( i > i_pixels )
1639                 {
1640                     i -= i_pixels;
1641                 }
1642             }
1643
1644             if( b_success )
1645             {
1646                 break;
1647             }
1648         }
1649
1650 #if DEBUG_DVBSUB
1651         msg_Dbg( p_enc, "best palette has %d colors", p_fmt->p_palette->i_entries );
1652 #endif
1653
1654 #ifndef RANDOM_DITHERING
1655         pi_delta = malloc( ( p_region->picture.p[0].i_pitch + 1 )
1656                             * sizeof(int) * 4  );
1657         for( i = 0; i < (p_region->picture.p[0].i_pitch + 1) * 4 ; i++ )
1658         {
1659             pi_delta[ i ] = 0;
1660         }
1661 #endif
1662
1663         /* Fill image with our new colours */
1664         for( p = 0; p < p_region->picture.p[0].i_visible_lines ; p++ )
1665         {
1666             int i_ydelta = 0, i_udelta = 0, i_vdelta = 0, i_adelta = 0;
1667
1668             for( n = 0; n < p_region->picture.p[0].i_pitch ; n++ )
1669             {
1670                 int i_offset = p * p_region->picture.p[0].i_pitch + n;
1671                 int y, u, v, a;
1672                 int i_mindist, i_best;
1673
1674                 y = (int)p_region->picture.p[0].p_pixels[i_offset];
1675                 u = (int)p_region->picture.p[1].p_pixels[i_offset];
1676                 v = (int)p_region->picture.p[2].p_pixels[i_offset];
1677                 a = (int)p_region->picture.p[3].p_pixels[i_offset];
1678
1679                 /* Add dithering compensation */
1680 #ifdef RANDOM_DITHERING
1681                 y += ((i_seed & 0xff) - 0x80) * i_tolerance / 0x80;
1682                 u += (((i_seed >> 8) & 0xff) - 0x80) * i_tolerance / 0x80;
1683                 v += (((i_seed >> 16) & 0xff) - 0x80) * i_tolerance / 0x80;
1684                 a += (((i_seed >> 24) & 0xff) - 0x80) * i_tolerance / 0x80;
1685 #else
1686                 y += i_ydelta + pi_delta[ n * 4 ];
1687                 u += i_udelta + pi_delta[ n * 4 + 1 ];
1688                 v += i_vdelta + pi_delta[ n * 4 + 2 ];
1689                 a += i_adelta + pi_delta[ n * 4 + 3 ];
1690 #endif
1691
1692                 /* Find best colour in palette */
1693                 for( i_mindist = 99999999, i_best = 0, j = 0; j < p_fmt->p_palette->i_entries; j++ )
1694                 {
1695                     int i_dist = 0;
1696
1697                     i_dist += abs((int)p_fmt->p_palette->palette[j][0] - y);
1698                     i_dist += abs((int)p_fmt->p_palette->palette[j][1] - u);
1699                     i_dist += abs((int)p_fmt->p_palette->palette[j][2] - v);
1700                     i_dist += 2 * abs((int)p_fmt->p_palette->palette[j][3] - a);
1701
1702                     if( i_dist < i_mindist )
1703                     {
1704                         i_mindist = i_dist;
1705                         i_best = j;
1706                     }
1707                 }
1708
1709                 /* Set pixel to best color */
1710                 p_region->picture.p[0].p_pixels[i_offset] = i_best;
1711
1712                 /* Update dithering state */
1713 #ifdef RANDOM_DITHERING
1714                 i_seed = (i_seed * 0x1283837) ^ 0x789479 ^ (i_seed >> 13);
1715 #else
1716                 i_ydelta = y - (int)p_fmt->p_palette->palette[i_best][0];
1717                 i_udelta = u - (int)p_fmt->p_palette->palette[i_best][1];
1718                 i_vdelta = v - (int)p_fmt->p_palette->palette[i_best][2];
1719                 i_adelta = a - (int)p_fmt->p_palette->palette[i_best][3];
1720                 pi_delta[ n * 4 ] = i_ydelta * 3 / 8;
1721                 pi_delta[ n * 4 + 1 ] = i_udelta * 3 / 8;
1722                 pi_delta[ n * 4 + 2 ] = i_vdelta * 3 / 8;
1723                 pi_delta[ n * 4 + 3 ] = i_adelta * 3 / 8;
1724                 i_ydelta = i_ydelta * 5 / 8;
1725                 i_udelta = i_udelta * 5 / 8;
1726                 i_vdelta = i_vdelta * 5 / 8;
1727                 i_adelta = i_adelta * 5 / 8;
1728 #endif
1729             }
1730         }
1731 #ifndef RANDOM_DITHERING
1732         free( pi_delta );
1733 #endif
1734
1735         /* pad palette */
1736         for( i = p_fmt->p_palette->i_entries; i < i_max_entries; i++ )
1737         {
1738             p_fmt->p_palette->palette[i][0] = 0;
1739             p_fmt->p_palette->palette[i][1] = 0;
1740             p_fmt->p_palette->palette[i][2] = 0;
1741             p_fmt->p_palette->palette[i][3] = 0;
1742         }
1743         p_fmt->p_palette->i_entries = i_max_entries;
1744 #if DEBUG_DVBSUB
1745         msg_Dbg( p_enc, "best palette has %d colors", p_fmt->p_palette->i_entries );
1746 #endif
1747     }
1748     return p_subpic;
1749 } /* End of hack */
1750
1751 /****************************************************************************
1752  * Encode: the whole thing
1753  ****************************************************************************/
1754 static block_t *Encode( encoder_t *p_enc, subpicture_t *p_subpic )
1755 {
1756     subpicture_t *p_temp = NULL;
1757     subpicture_region_t *p_region = NULL;
1758     bs_t bits, *s = &bits;
1759     block_t *p_block;
1760
1761     if( !p_subpic || !p_subpic->p_region ) return NULL;
1762
1763     /* FIXME: this is a hack to convert VLC_FOURCC('Y','U','V','A') into
1764      *  VLC_FOURCC('Y','U','V','P')
1765      */
1766     p_region = p_subpic->p_region;
1767     if( p_region->fmt.i_chroma == VLC_FOURCC('Y','U','V','A') )
1768     {
1769         p_temp = YuvaYuvp( p_enc, p_subpic );
1770         if( !p_temp )
1771         {
1772             msg_Err( p_enc, "no picture in subpicture" );
1773             return NULL;
1774         }
1775         p_region = p_subpic->p_region;
1776     }
1777
1778     /* Sanity check */
1779     if( !p_region ) return NULL;
1780
1781     if( p_region->fmt.i_chroma != VLC_FOURCC('T','E','X','T') &&
1782         p_region->fmt.i_chroma != VLC_FOURCC('Y','U','V','P') ) return NULL;
1783
1784     if( p_region->fmt.p_palette )
1785     {
1786         switch( p_region->fmt.p_palette->i_entries )
1787         {
1788             case 0:
1789             case 4:
1790             case 16:
1791             case 256:
1792                 break;
1793             default:
1794                 msg_Err( p_enc, "subpicture palette (%d) not handled",
1795                             p_region->fmt.p_palette->i_entries );
1796                 return NULL;
1797         }
1798     }
1799     /* End of hack */
1800
1801 #if DEBUG_DVBSUB
1802     msg_Dbg( p_enc, "encoding subpicture" );
1803 #endif
1804     p_block = block_New( p_enc, 64000 );
1805     bs_init( s, p_block->p_buffer, p_block->i_buffer );
1806
1807     bs_write( s, 8, 0x20 ); /* Data identifier */
1808     bs_write( s, 8, 0x0 );  /* Subtitle stream id */
1809
1810     encode_page_composition( p_enc, s, p_subpic );
1811     encode_region_composition( p_enc, s, p_subpic );
1812     encode_clut( p_enc, s, p_subpic );
1813     encode_object( p_enc, s, p_subpic );
1814
1815     /* End of display */
1816     bs_write( s, 8, 0x0f ); /* Sync byte */
1817     bs_write( s, 8, DVBSUB_ST_ENDOFDISPLAY ); /* Segment type */
1818     bs_write( s, 16, 1 );  /* Page id */
1819     bs_write( s, 16, 0 );  /* Segment length */
1820
1821     bs_write( s, 8, 0xff );/* End marker */
1822     p_block->i_buffer = bs_pos( s ) / 8;
1823     p_block->i_pts = p_block->i_dts = p_subpic->i_start;
1824     if( !p_subpic->b_ephemer && p_subpic->i_stop > p_subpic->i_start )
1825     {
1826         block_t *p_block_stop;
1827
1828         p_block->i_length = p_subpic->i_stop - p_subpic->i_start;
1829
1830         /* Send another (empty) subtitle to signal the end of display */
1831         p_block_stop = block_New( p_enc, 64000 );
1832         bs_init( s, p_block_stop->p_buffer, p_block_stop->i_buffer );
1833         bs_write( s, 8, 0x20 ); /* Data identifier */
1834         bs_write( s, 8, 0x0 );  /* Subtitle stream id */
1835         encode_page_composition( p_enc, s, 0 );
1836         bs_write( s, 8, 0x0f ); /* Sync byte */
1837         bs_write( s, 8, DVBSUB_ST_ENDOFDISPLAY ); /* Segment type */
1838         bs_write( s, 16, 1 );  /* Page id */
1839         bs_write( s, 16, 0 );  /* Segment length */
1840         bs_write( s, 8, 0xff );/* End marker */
1841         p_block_stop->i_buffer = bs_pos( s ) / 8;
1842         p_block_stop->i_pts = p_block_stop->i_dts = p_subpic->i_stop;
1843         block_ChainAppend( &p_block, p_block_stop );
1844         p_block_stop->i_length = 100000; /* p_subpic->i_stop - p_subpic->i_start; */
1845     }
1846 #ifdef DEBUG_DVBSUB
1847     msg_Dbg( p_enc, "subpicture encoded properly" );
1848 #endif
1849     return p_block;
1850 }
1851
1852 /*****************************************************************************
1853  * CloseEncoder: encoder destruction
1854  *****************************************************************************/
1855 static void CloseEncoder( vlc_object_t *p_this )
1856 {
1857     encoder_t *p_enc = (encoder_t *)p_this;
1858     encoder_sys_t *p_sys = p_enc->p_sys;
1859
1860     var_Destroy( p_this , ENC_CFG_PREFIX "x" );
1861     var_Destroy( p_this , ENC_CFG_PREFIX "y" );
1862     var_Destroy( p_this , ENC_CFG_PREFIX "timeout" );
1863
1864     if( p_sys->i_regions ) free( p_sys->p_regions );
1865     free( p_sys );
1866 }
1867
1868 static void encode_page_composition( encoder_t *p_enc, bs_t *s,
1869                                      subpicture_t *p_subpic )
1870 {
1871     encoder_sys_t *p_sys = p_enc->p_sys;
1872     subpicture_region_t *p_region;
1873     vlc_bool_t b_mode_change = VLC_FALSE;
1874     int i_regions, i_timeout;
1875
1876     bs_write( s, 8, 0x0f ); /* Sync byte */
1877     bs_write( s, 8, DVBSUB_ST_PAGE_COMPOSITION ); /* Segment type */
1878     bs_write( s, 16, 1 ); /* Page id */
1879
1880     for( i_regions = 0, p_region = p_subpic ? p_subpic->p_region : 0;
1881          p_region; p_region = p_region->p_next, i_regions++ )
1882     {
1883         if( i_regions >= p_sys->i_regions )
1884         {
1885             encoder_region_t region;
1886             region.i_width = region.i_height = 0;
1887             p_sys->p_regions =
1888                 realloc( p_sys->p_regions, sizeof(encoder_region_t) *
1889                          (p_sys->i_regions + 1) );
1890             p_sys->p_regions[p_sys->i_regions++] = region;
1891         }
1892
1893         if( ( p_sys->p_regions[i_regions].i_width <
1894               (int)p_region->fmt.i_visible_width ) || 
1895             ( p_sys->p_regions[i_regions].i_width >
1896               (int)p_region->fmt.i_visible_width ) )
1897         {
1898             b_mode_change = VLC_TRUE;
1899             msg_Dbg( p_enc, "region %i width change: %i -> %i",
1900                      i_regions, p_sys->p_regions[i_regions].i_width,
1901                      p_region->fmt.i_visible_width );
1902             p_sys->p_regions[i_regions].i_width =
1903                 p_region->fmt.i_visible_width;
1904         }
1905         if( p_sys->p_regions[i_regions].i_height <
1906              (int)p_region->fmt.i_visible_height )
1907         {
1908             b_mode_change = VLC_TRUE;
1909             msg_Dbg( p_enc, "region %i height change: %i -> %i",
1910                      i_regions, p_sys->p_regions[i_regions].i_height,
1911                      p_region->fmt.i_visible_height );
1912             p_sys->p_regions[i_regions].i_height =
1913                 p_region->fmt.i_visible_height;
1914         }
1915     }
1916
1917     bs_write( s, 16, i_regions * 6 + 2 ); /* Segment length */
1918
1919     i_timeout = 0;
1920     if( p_subpic && !p_subpic->b_ephemer &&
1921         p_subpic->i_stop > p_subpic->i_start )
1922     {
1923         i_timeout = (p_subpic->i_stop - p_subpic->i_start) / 1000000;
1924     }
1925
1926     bs_write( s, 8, i_timeout ); /* Timeout */
1927     bs_write( s, 4, p_sys->i_page_ver++ );
1928     bs_write( s, 2, b_mode_change ?
1929               DVBSUB_PCS_STATE_CHANGE : DVBSUB_PCS_STATE_ACQUISITION );
1930     bs_write( s, 2, 0 ); /* Reserved */
1931
1932     for( i_regions = 0, p_region = p_subpic ? p_subpic->p_region : 0;
1933          p_region; p_region = p_region->p_next, i_regions++ )
1934     {
1935         bs_write( s, 8, i_regions );
1936         bs_write( s, 8, 0 ); /* Reserved */
1937         if( (p_sys->i_offset_x > 0) && (p_sys->i_offset_y > 0) )
1938         {
1939             bs_write( s, 16, p_sys->i_offset_x ); /* override x position */
1940             bs_write( s, 16, p_sys->i_offset_y ); /* override y position */
1941         }
1942         else
1943         {
1944             bs_write( s, 16, p_region->i_x );
1945             bs_write( s, 16, p_region->i_y );
1946         }
1947     }
1948 }
1949
1950 static void encode_clut( encoder_t *p_enc, bs_t *s, subpicture_t *p_subpic )
1951 {
1952     encoder_sys_t *p_sys = p_enc->p_sys;
1953     subpicture_region_t *p_region = p_subpic->p_region;
1954     video_palette_t *p_pal, pal;
1955     int i;
1956
1957     /* Sanity check */
1958     if( !p_region ) return;
1959
1960     if( p_region->fmt.i_chroma == VLC_FOURCC('Y','U','V','P') )
1961     {
1962         p_pal = p_region->fmt.p_palette;
1963     }
1964     else
1965     {
1966         pal.i_entries = 4;
1967         for( i = 0; i < 4; i++ )
1968         {
1969             pal.palette[i][0] = 0;
1970             pal.palette[i][1] = 0;
1971             pal.palette[i][2] = 0;
1972             pal.palette[i][3] = 0;
1973         }
1974         p_pal = &pal;
1975     }
1976
1977     bs_write( s, 8, 0x0f ); /* Sync byte */
1978     bs_write( s, 8, DVBSUB_ST_CLUT_DEFINITION ); /* Segment type */
1979     bs_write( s, 16, 1 );  /* Page id */
1980
1981     bs_write( s, 16, p_pal->i_entries * 6 + 2 ); /* Segment length */
1982     bs_write( s, 8, 1 ); /* Clut id */
1983     bs_write( s, 4, p_sys->i_clut_ver++ );
1984     bs_write( s, 4, 0 ); /* Reserved */
1985
1986     for( i = 0; i < p_pal->i_entries; i++ )
1987     {
1988         bs_write( s, 8, i ); /* Clut entry id */
1989         bs_write( s, 1, p_pal->i_entries == 4 );   /* 2bit/entry flag */
1990         bs_write( s, 1, p_pal->i_entries == 16 );  /* 4bit/entry flag */
1991         bs_write( s, 1, p_pal->i_entries == 256 ); /* 8bit/entry flag */
1992         bs_write( s, 4, 0 ); /* Reserved */
1993         bs_write( s, 1, 1 ); /* Full range flag */
1994         bs_write( s, 8, p_pal->palette[i][3] ?  /* Y value */
1995                   (p_pal->palette[i][0] ? p_pal->palette[i][0] : 16) : 0 );
1996         bs_write( s, 8, p_pal->palette[i][1] ); /* Cr value */
1997         bs_write( s, 8, p_pal->palette[i][2] ); /* Cb value */
1998         bs_write( s, 8, 0xff - p_pal->palette[i][3] ); /* T value */
1999     }
2000 }
2001
2002 static void encode_region_composition( encoder_t *p_enc, bs_t *s,
2003                                        subpicture_t *p_subpic )
2004 {
2005     encoder_sys_t *p_sys = p_enc->p_sys;
2006     subpicture_region_t *p_region;
2007     int i_region;
2008
2009     for( i_region = 0, p_region = p_subpic->p_region; p_region;
2010          p_region = p_region->p_next, i_region++ )
2011     {
2012         int i_entries = 4, i_depth = 0x1, i_bg = 0;
2013         vlc_bool_t b_text =
2014             p_region->fmt.i_chroma == VLC_FOURCC('T','E','X','T');
2015
2016         if( !b_text )
2017         {
2018             video_palette_t *p_pal = p_region->fmt.p_palette;
2019
2020             if( !p_pal )
2021             {
2022                 msg_Err( p_enc, "subpicture has no palette - ignoring it" );
2023                 break;
2024             }
2025
2026             i_entries = p_pal->i_entries;
2027             i_depth = i_entries == 4 ? 0x1 : i_entries == 16 ? 0x2 : 0x3;
2028
2029             for( i_bg = 0; i_bg < p_pal->i_entries; i_bg++ )
2030             {
2031                 if( !p_pal->palette[i_bg][3] ) break;
2032             }
2033         }
2034
2035         bs_write( s, 8, 0x0f ); /* Sync byte */
2036         bs_write( s, 8, DVBSUB_ST_REGION_COMPOSITION ); /* Segment type */
2037         bs_write( s, 16, 1 );   /* Page id */
2038
2039         bs_write( s, 16, 10 + 6 + (b_text ? 2 : 0) ); /* Segment length */
2040         bs_write( s, 8, i_region );
2041         bs_write( s, 4, p_sys->i_region_ver++ );
2042
2043         /* Region attributes */
2044         bs_write( s, 1, i_bg < i_entries ); /* Fill */
2045         bs_write( s, 3, 0 ); /* Reserved */
2046         bs_write( s, 16, p_sys->p_regions[i_region].i_width );
2047         bs_write( s, 16, p_sys->p_regions[i_region].i_height );
2048         bs_write( s, 3, i_depth );  /* Region level of compatibility */
2049         bs_write( s, 3, i_depth  ); /* Region depth */
2050         bs_write( s, 2, 0 ); /* Reserved */
2051         bs_write( s, 8, 1 ); /* Clut id */
2052         bs_write( s, 8, i_bg ); /* region 8bit pixel code */
2053         bs_write( s, 4, i_bg ); /* region 4bit pixel code */
2054         bs_write( s, 2, i_bg ); /* region 2bit pixel code */
2055         bs_write( s, 2, 0 ); /* Reserved */
2056
2057         /* In our implementation we only have 1 object per region */
2058         bs_write( s, 16, i_region );
2059         bs_write( s, 2, b_text ? DVBSUB_OT_BASIC_CHAR:DVBSUB_OT_BASIC_BITMAP );
2060         bs_write( s, 2, 0 ); /* object provider flag */
2061         bs_write( s, 12, 0 );/* object horizontal position */
2062         bs_write( s, 4, 0 ); /* Reserved */
2063         bs_write( s, 12, 0 );/* object vertical position */
2064
2065         if( b_text )
2066         {
2067             bs_write( s, 8, 1 ); /* foreground pixel code */
2068             bs_write( s, 8, 0 ); /* background pixel code */
2069         }
2070     }
2071 }
2072
2073 static void encode_pixel_data( encoder_t *p_enc, bs_t *s,
2074                                subpicture_region_t *p_region,
2075                                vlc_bool_t b_top );
2076
2077 static void encode_object( encoder_t *p_enc, bs_t *s, subpicture_t *p_subpic )
2078 {
2079     encoder_sys_t *p_sys = p_enc->p_sys;
2080     subpicture_region_t *p_region;
2081     int i_region;
2082
2083     int i_length_pos, i_update_pos, i_pixel_data_pos;
2084
2085     for( i_region = 0, p_region = p_subpic->p_region; p_region;
2086          p_region = p_region->p_next, i_region++ )
2087     {
2088         bs_write( s, 8, 0x0f ); /* Sync byte */
2089         bs_write( s, 8, DVBSUB_ST_OBJECT_DATA ); /* Segment type */
2090         bs_write( s, 16, 1 ); /* Page id */
2091
2092         i_length_pos = bs_pos( s );
2093         bs_write( s, 16, 0 ); /* Segment length */
2094         bs_write( s, 16, i_region ); /* Object id */
2095         bs_write( s, 4, p_sys->i_region_ver++ );
2096
2097         /* object coding method */
2098         switch( p_region->fmt.i_chroma )
2099         {
2100         case VLC_FOURCC( 'Y','U','V','P' ):
2101             bs_write( s, 2, 0 );
2102             break;
2103         case VLC_FOURCC( 'T','E','X','T' ):
2104             bs_write( s, 2, 1 );
2105             break;
2106         default:
2107             msg_Err( p_enc, "FOURCC %d not supported by encoder.", p_region->fmt.i_chroma );
2108             continue;
2109         }
2110
2111         bs_write( s, 1, 0 ); /* non modifying color flag */
2112         bs_write( s, 1, 0 ); /* Reserved */
2113
2114         if( p_region->fmt.i_chroma == VLC_FOURCC( 'T','E','X','T' ) )
2115         {
2116             int i_size, i;
2117
2118             if( !p_region->psz_text ) continue;
2119
2120             i_size = __MIN( strlen( p_region->psz_text ), 256 );
2121
2122             bs_write( s, 8, i_size ); /* number of characters in string */
2123             for( i = 0; i < i_size; i++ )
2124             {
2125                 bs_write( s, 16, p_region->psz_text[i] );
2126             }
2127
2128             /* Update segment length */
2129             SetWBE( &s->p_start[i_length_pos/8],
2130                     (bs_pos(s) - i_length_pos)/8 -2 );
2131             continue;
2132         }
2133
2134         /* Coding of a bitmap object */
2135         i_update_pos = bs_pos( s );
2136         bs_write( s, 16, 0 ); /* topfield data block length */
2137         bs_write( s, 16, 0 ); /* bottomfield data block length */
2138
2139         /* Top field */
2140         i_pixel_data_pos = bs_pos( s );
2141         encode_pixel_data( p_enc, s, p_region, VLC_TRUE );
2142         i_pixel_data_pos = ( bs_pos( s ) - i_pixel_data_pos ) / 8;
2143         SetWBE( &s->p_start[i_update_pos/8], i_pixel_data_pos );
2144
2145         /* Bottom field */
2146         i_pixel_data_pos = bs_pos( s );
2147         encode_pixel_data( p_enc, s, p_region, VLC_FALSE );
2148         i_pixel_data_pos = ( bs_pos( s ) - i_pixel_data_pos ) / 8;
2149         SetWBE( &s->p_start[i_update_pos/8+2], i_pixel_data_pos );
2150
2151         /* Stuffing for word alignment */
2152         bs_align_0( s );
2153         if( bs_pos( s ) % 16 ) bs_write( s, 8, 0 );
2154
2155         /* Update segment length */
2156         SetWBE( &s->p_start[i_length_pos/8], (bs_pos(s) - i_length_pos)/8 -2 );
2157     }
2158 }
2159
2160 static void encode_pixel_line_2bp( encoder_t *p_enc, bs_t *s,
2161                                    subpicture_region_t *p_region,
2162                                    int i_line );
2163 static void encode_pixel_line_4bp( encoder_t *p_enc, bs_t *s,
2164                                    subpicture_region_t *p_region,
2165                                    int i_line );
2166 static void encode_pixel_line_8bp( encoder_t *p_enc, bs_t *s,
2167                                    subpicture_region_t *p_region,
2168                                    int i_line );
2169 static void encode_pixel_data( encoder_t *p_enc, bs_t *s,
2170                                subpicture_region_t *p_region,
2171                                vlc_bool_t b_top )
2172 {
2173     unsigned int i_line;
2174
2175     /* Sanity check */
2176     if( p_region->fmt.i_chroma != VLC_FOURCC('Y','U','V','P') ) return;
2177
2178     /* Encode line by line */
2179     for( i_line = !b_top; i_line < p_region->fmt.i_visible_height;
2180          i_line += 2 )
2181     {
2182         switch( p_region->fmt.p_palette->i_entries )
2183         {
2184         case 0:
2185             break;
2186
2187         case 4:
2188             bs_write( s, 8, 0x10 ); /* 2 bit/pixel code string */
2189             encode_pixel_line_2bp( p_enc, s, p_region, i_line );
2190             break;
2191
2192         case 16:
2193             bs_write( s, 8, 0x11 ); /* 4 bit/pixel code string */
2194             encode_pixel_line_4bp( p_enc, s, p_region, i_line );
2195             break;
2196
2197         case 256:
2198             bs_write( s, 8, 0x12 ); /* 8 bit/pixel code string */
2199             encode_pixel_line_8bp( p_enc, s, p_region, i_line );
2200             break;
2201
2202         default:
2203             msg_Err( p_enc, "subpicture palette (%i) not handled",
2204                      p_region->fmt.p_palette->i_entries );
2205             break;
2206         }
2207
2208         bs_write( s, 8, 0xf0 ); /* End of object line code */
2209     }
2210 }
2211
2212 static void encode_pixel_line_2bp( encoder_t *p_enc, bs_t *s,
2213                                    subpicture_region_t *p_region,
2214                                    int i_line )
2215 {
2216     unsigned int i, i_length = 0;
2217     int i_pitch = p_region->picture.p->i_pitch;
2218     uint8_t *p_data = &p_region->picture.p->p_pixels[ i_pitch * i_line ];
2219     int i_last_pixel = p_data[0];
2220
2221     for( i = 0; i <= p_region->fmt.i_visible_width; i++ )
2222     {
2223         if( i != p_region->fmt.i_visible_width &&
2224             p_data[i] == i_last_pixel && i_length != 284 )
2225         {
2226             i_length++;
2227             continue;
2228         }
2229
2230         if( i_length == 1 || i_length == 11 || i_length == 28 )
2231         {
2232             /* 2bit/pixel code */
2233             if( i_last_pixel ) bs_write( s, 2, i_last_pixel );
2234             else
2235             {
2236                 bs_write( s, 2, 0 );
2237                 bs_write( s, 1, 0 );
2238                 bs_write( s, 1, 1 ); /* pseudo color 0 */
2239             }
2240             i_length--;
2241         }
2242
2243         if( i_length == 2 )
2244         {
2245             if( i_last_pixel )
2246             {
2247                 bs_write( s, 2, i_last_pixel );
2248                 bs_write( s, 2, i_last_pixel );
2249             }
2250             else
2251             {
2252                 bs_write( s, 2, 0 );
2253                 bs_write( s, 1, 0 );
2254                 bs_write( s, 1, 0 );
2255                 bs_write( s, 2, 1 ); /* 2 * pseudo color 0 */
2256             }
2257         }
2258         else if( i_length > 2 )
2259         {
2260             bs_write( s, 2, 0 );
2261             if( i_length <= 10 )
2262             {
2263                 bs_write( s, 1, 1 );
2264                 bs_write( s, 3, i_length - 3 );
2265                 bs_write( s, 2, i_last_pixel );
2266             }
2267             else
2268             {
2269                 bs_write( s, 1, 0 );
2270                 bs_write( s, 1, 0 );
2271
2272                 if( i_length <= 27 )
2273                 {
2274                     bs_write( s, 2, 2 );
2275                     bs_write( s, 4, i_length - 12 );
2276                     bs_write( s, 2, i_last_pixel );
2277                 }
2278                 else
2279                 {
2280                     bs_write( s, 2, 3 );
2281                     bs_write( s, 8, i_length - 29 );
2282                     bs_write( s, 2, i_last_pixel );
2283                 }
2284             }
2285         }
2286
2287         if( i == p_region->fmt.i_visible_width ) break;
2288
2289         i_last_pixel = p_data[i];
2290         i_length = 1;
2291     }
2292
2293     /* Stop */
2294     bs_write( s, 2, 0 );
2295     bs_write( s, 1, 0 );
2296     bs_write( s, 1, 0 );
2297     bs_write( s, 2, 0 );
2298
2299     /* Stuffing */
2300     bs_align_0( s );
2301 }
2302
2303 static void encode_pixel_line_4bp( encoder_t *p_enc, bs_t *s,
2304                                    subpicture_region_t *p_region,
2305                                    int i_line )
2306 {
2307     unsigned int i, i_length = 0;
2308     int i_pitch = p_region->picture.p->i_pitch;
2309     uint8_t *p_data = &p_region->picture.p->p_pixels[ i_pitch * i_line ];
2310     int i_last_pixel = p_data[0];
2311
2312     for( i = 0; i <= p_region->fmt.i_visible_width; i++ )
2313     {
2314         if( i != p_region->fmt.i_visible_width &&
2315             p_data[i] == i_last_pixel && i_length != 280 )
2316         {
2317             i_length++;
2318             continue;
2319         }
2320
2321         if( i_length == 1 || (i_length == 3 && i_last_pixel) || i_length == 8 )
2322         {
2323             /* 4bit/pixel code */
2324             if( i_last_pixel ) bs_write( s, 4, i_last_pixel );
2325             else
2326             {
2327                 bs_write( s, 4, 0 );
2328                 bs_write( s, 1, 1 );
2329                 bs_write( s, 1, 1 );
2330                 bs_write( s, 2, 0 ); /* pseudo color 0 */
2331             }
2332             i_length--;
2333         }
2334
2335         if( i_length == 2 )
2336         {
2337             if( i_last_pixel )
2338             {
2339                 bs_write( s, 4, i_last_pixel );
2340                 bs_write( s, 4, i_last_pixel );
2341             }
2342             else
2343             {
2344                 bs_write( s, 4, 0 );
2345                 bs_write( s, 1, 1 );
2346                 bs_write( s, 1, 1 );
2347                 bs_write( s, 2, 1 ); /* 2 * pseudo color 0 */
2348             }
2349         }
2350         else if( !i_last_pixel && i_length >= 3 && i_length <= 9 )
2351         {
2352             bs_write( s, 4, 0 );
2353             bs_write( s, 1, 0 );
2354             bs_write( s, 3, i_length - 2 ); /* (i_length - 2) * color 0 */
2355         }
2356         else if( i_length > 2 )
2357         {
2358             bs_write( s, 4, 0 );
2359             bs_write( s, 1, 1 );
2360
2361             if( i_length <= 7 )
2362             {
2363                 bs_write( s, 1, 0 );
2364                 bs_write( s, 2, i_length - 4 );
2365                 bs_write( s, 4, i_last_pixel );
2366             }
2367             else
2368             {
2369                 bs_write( s, 1, 1 );
2370
2371                 if( i_length <= 24 )
2372                 {
2373                     bs_write( s, 2, 2 );
2374                     bs_write( s, 4, i_length - 9 );
2375                     bs_write( s, 4, i_last_pixel );
2376                 }
2377                 else
2378                 {
2379                     bs_write( s, 2, 3 );
2380                     bs_write( s, 8, i_length - 25 );
2381                     bs_write( s, 4, i_last_pixel );
2382                 }
2383             }
2384         }
2385
2386         if( i == p_region->fmt.i_visible_width ) break;
2387
2388         i_last_pixel = p_data[i];
2389         i_length = 1;
2390     }
2391
2392     /* Stop */
2393     bs_write( s, 8, 0 );
2394
2395     /* Stuffing */
2396     bs_align_0( s );
2397 }
2398
2399 static void encode_pixel_line_8bp( encoder_t *p_enc, bs_t *s,
2400                                    subpicture_region_t *p_region,
2401                                    int i_line )
2402 {
2403     unsigned int i, i_length = 0;
2404     int i_pitch = p_region->picture.p->i_pitch;
2405     uint8_t *p_data = &p_region->picture.p->p_pixels[ i_pitch * i_line ];
2406     int i_last_pixel = p_data[0];
2407
2408     for( i = 0; i <= p_region->fmt.i_visible_width; i++ )
2409     {
2410         if( i != p_region->fmt.i_visible_width &&
2411             p_data[i] == i_last_pixel && i_length != 127 )
2412         {
2413             i_length++;
2414             continue;
2415         }
2416
2417         if( i_length == 1 && i_last_pixel )
2418         {
2419             /* 8bit/pixel code */
2420             bs_write( s, 8, i_last_pixel );
2421         }
2422         else if( i_length == 2 && i_last_pixel )
2423         {
2424             /* 8bit/pixel code */
2425             bs_write( s, 8, i_last_pixel );
2426             bs_write( s, 8, i_last_pixel );
2427         }
2428         else if( i_length <= 127 )
2429         {
2430             bs_write( s, 8, 0 );
2431
2432             if( !i_last_pixel )
2433             {
2434                 bs_write( s, 1, 0 );
2435                 bs_write( s, 7, i_length ); /* pseudo color 0 */
2436             }
2437             else
2438             {
2439                 bs_write( s, 1, 1 );
2440                 bs_write( s, 7, i_length );
2441                 bs_write( s, 8, i_last_pixel );
2442             }
2443         }
2444
2445         if( i == p_region->fmt.i_visible_width ) break;
2446
2447         i_last_pixel = p_data[i];
2448         i_length = 1;
2449     }
2450
2451     /* Stop */
2452     bs_write( s, 8, 0 );
2453     bs_write( s, 8, 0 );
2454
2455     /* Stuffing */
2456     bs_align_0( s );
2457 }