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