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