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