]> git.sesse.net Git - vlc/blob - modules/codec/dvbsub.c
* modules/mux/mpeg/ts.c: reworked muxing of subtitles ES.
[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-2004 VideoLAN
7  * $Id$
8  *
9  * Authors: Damien LUCAS <damien.lucas@anevia.com>
10  *          Laurent Aimar <fenrir@via.ecp.fr>
11  *          Gildas Bazin <gbazin@videolan.org>
12  *
13  * This program is free software; you can redistribute it and/or modify
14  * it under the terms of the GNU General Public License as published by
15  * the Free Software Foundation; either version 2 of the License, or
16  * (at your option) any later version.
17  *
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21  * GNU General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program; if not, write to the Free Software
25  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
26  *****************************************************************************/
27 /*****************************************************************************
28  * Preamble
29  *****************************************************************************/
30 #include <vlc/vlc.h>
31 #include <vlc/vout.h>
32 #include <vlc/decoder.h>
33 #include <vlc/sout.h>
34
35 #include "vlc_bits.h"
36
37 //#define DEBUG_DVBSUB 1
38
39 /*****************************************************************************
40  * Module descriptor.
41  *****************************************************************************/
42 static int  Open ( vlc_object_t * );
43 static void Close( vlc_object_t * );
44 static subpicture_t *Decode( decoder_t *, block_t ** );
45
46 static int OpenEncoder  ( vlc_object_t * );
47 static void CloseEncoder( vlc_object_t * );
48 static block_t *Encode  ( encoder_t *, subpicture_t * );
49
50 vlc_module_begin();
51     set_description( _("DVB subtitles decoder") );
52     set_capability( "decoder", 50 );
53     set_callbacks( Open, Close );
54
55 #   define ENC_CFG_PREFIX "sout-dvbsub-"
56     add_submodule();
57     set_description( _("DVB subtitles encoder") );
58     set_capability( "encoder", 100 );
59     set_callbacks( OpenEncoder, CloseEncoder );
60 vlc_module_end();
61
62 static const char *ppsz_enc_options[] = { NULL };
63
64 /****************************************************************************
65  * Local structures
66  ****************************************************************************
67  * Those structures refer closely to the ETSI 300 743 Object model
68  ****************************************************************************/
69
70 /* Storage of a RLE entry */
71 typedef struct dvbsub_rle_s
72 {
73     uint16_t                i_num;
74     int                     i_color_code;
75     int                     i_bpp;
76     uint8_t                 y;
77     uint8_t                 cr;
78     uint8_t                 cb;
79     uint8_t                 t;
80     struct dvbsub_rle_s     *p_next;
81
82 } dvbsub_rle_t;
83
84 /* A subpicture image is a list of codes
85  * We need to store the length of each line since nothing specify in
86  * the standard that all lines should have the same length
87  * WARNING: We assume here that a spu is less than 576 lines high */
88 typedef struct
89 {
90     uint16_t                i_rows;
91     uint16_t                i_cols[576];
92     dvbsub_rle_t            *p_last;
93     dvbsub_rle_t            *p_codes;
94
95 } dvbsub_image_t;
96
97 /* The object definition gives the position of the object in a region */
98 typedef struct dvbsub_objectdef_s
99 {
100     uint16_t                  i_id;
101     uint8_t                   i_type;
102     uint8_t                   i_provider;
103     uint16_t                  i_x;
104     uint16_t                  i_y;
105     uint8_t                   i_fg_pc;
106     uint8_t                   i_bg_pc;
107
108 } dvbsub_objectdef_t;
109
110 /* An object is constituted of 2 images (for interleaving) */
111 typedef struct dvbsub_object_s
112 {
113     uint16_t                i_id;
114     uint8_t                 i_version_number;
115     uint8_t                 i_coding_method;
116     vlc_bool_t              b_non_modify_color;
117     dvbsub_image_t         *topfield;
118     dvbsub_image_t         *bottomfield;
119     struct dvbsub_object_s *p_next;
120
121 } dvbsub_object_t;
122
123 /* The object definition gives the position of the object in a region */
124 typedef struct dvbsub_regiondef_s
125 {
126     uint16_t                  i_id;
127     uint16_t                  i_x;
128     uint16_t                  i_y;
129
130 } dvbsub_regiondef_t;
131
132 /* The Region is an aera on the image
133  * with a list of the object definitions associated and a CLUT */
134 typedef struct dvbsub_region_s
135 {
136     uint8_t                 i_id;
137     uint8_t                 i_version_number;
138     vlc_bool_t              b_fill;
139     uint16_t                i_x;
140     uint16_t                i_y;
141     uint16_t                i_width;
142     uint16_t                i_height;
143     uint8_t                 i_level_comp;
144     uint8_t                 i_depth;
145     uint8_t                 i_clut;
146     uint8_t                 i_8bp_code;
147     uint8_t                 i_4bp_code;
148     uint8_t                 i_2bp_code;
149
150     int                     i_object_defs;
151     dvbsub_objectdef_t      *p_object_defs;
152
153     struct dvbsub_region_s  *p_next;
154
155 } dvbsub_region_t;
156
157 /* The page defines the list of regions */
158 typedef struct
159 {
160     uint16_t              i_id;
161     uint8_t               i_timeout;
162     uint8_t               i_state;
163     uint8_t               i_version_number;
164
165     uint8_t               i_region_defs;
166     dvbsub_regiondef_t    *p_region_defs;
167
168 } dvbsub_page_t;
169
170 /* The entry in the palette CLUT */
171 typedef struct
172 {
173     uint8_t                 Y;
174     uint8_t                 Cr;
175     uint8_t                 Cb;
176     uint8_t                 T;
177
178 } dvbsub_color_t;
179
180 /* */
181 typedef struct
182 {
183     uint8_t                 i_id;
184     uint8_t                 i_version_number;
185     dvbsub_color_t          c_2b[4];
186     dvbsub_color_t          c_4b[16];
187     dvbsub_color_t          c_8b[256];
188
189 } dvbsub_clut_t;
190
191 struct decoder_sys_t
192 {
193     bs_t            bs;
194
195     /* Decoder internal data */
196     int             i_id;
197     int             i_ancillary_id;
198     mtime_t         i_pts;
199
200     dvbsub_page_t   *p_page;
201     dvbsub_region_t *p_regions;
202     dvbsub_object_t *p_objects;
203
204     dvbsub_clut_t   *p_clut[256];
205     dvbsub_clut_t   default_clut;
206 };
207
208
209 // List of different SEGMENT TYPES
210 // According to EN 300-743, table 2
211 #define DVBSUB_ST_PAGE_COMPOSITION      0x10
212 #define DVBSUB_ST_REGION_COMPOSITION    0x11
213 #define DVBSUB_ST_CLUT_DEFINITION       0x12
214 #define DVBSUB_ST_OBJECT_DATA           0x13
215 #define DVBSUB_ST_ENDOFDISPLAY          0x80
216 #define DVBSUB_ST_STUFFING              0xff
217 // List of different OBJECT TYPES
218 // According to EN 300-743, table 6
219 #define DVBSUB_OT_BASIC_BITMAP          0x00
220 #define DVBSUB_OT_BASIC_CHAR            0x01
221 #define DVBSUB_OT_COMPOSITE_STRING      0x02
222 // Pixel DATA TYPES
223 // According to EN 300-743, table 9
224 #define DVBSUB_DT_2BP_CODE_STRING       0x10
225 #define DVBSUB_DT_4BP_CODE_STRING       0x11
226 #define DVBSUB_DT_8BP_CODE_STRING       0x12
227 #define DVBSUB_DT_24_TABLE_DATA         0x20
228 #define DVBSUB_DT_28_TABLE_DATA         0x21
229 #define DVBSUB_DT_48_TABLE_DATA         0x22
230 #define DVBSUB_DT_END_LINE              0xf0
231 // List of different Page Composition Segment state
232 // According to EN 300-743, 7.2.1 table 3
233 #define DVBSUB_PCS_STATE_ACQUISITION    0x01
234 #define DVBSUB_PCS_STATE_CHANGE         0x10
235
236 /*****************************************************************************
237  * Local prototypes
238  *****************************************************************************/
239 static void decode_segment( decoder_t *, bs_t * );
240 static void decode_page_composition( decoder_t *, bs_t * );
241 static void decode_region_composition( decoder_t *, bs_t * );
242 static void decode_object( decoder_t *, bs_t * );
243 static void decode_clut( decoder_t *, bs_t * );
244
245 static void free_objects( decoder_t * );
246 static void free_all( decoder_t * );
247
248 static subpicture_t *render( decoder_t * );
249
250 static void default_clut_init( decoder_t * );
251
252 /*****************************************************************************
253  * Open: probe the decoder and return score
254  *****************************************************************************
255  * Tries to launch a decoder and return score so that the interface is able
256  * to chose.
257  *****************************************************************************/
258 static int Open( vlc_object_t *p_this )
259 {
260     decoder_t     *p_dec = (decoder_t *) p_this;
261     decoder_sys_t *p_sys;
262     int i;
263
264     if( p_dec->fmt_in.i_codec != VLC_FOURCC('d','v','b','s') )
265     {
266         return VLC_EGENERIC;
267     }
268
269     p_dec->pf_decode_sub = Decode;
270     p_sys = p_dec->p_sys = malloc( sizeof(decoder_sys_t) );
271
272     p_sys->i_pts          = 0;
273     p_sys->i_id           = p_dec->fmt_in.subs.dvb.i_id & 0xFFFF;
274     p_sys->i_ancillary_id = p_dec->fmt_in.subs.dvb.i_id >> 16;
275     p_sys->p_page         = NULL;
276     p_sys->p_regions      = NULL;
277     p_sys->p_objects      = NULL;
278     for( i = 0; i < 256; i++ ) p_sys->p_clut[i] = NULL;
279
280     es_format_Init( &p_dec->fmt_out, SPU_ES, VLC_FOURCC( 'd','v','b','s' ) );
281
282     default_clut_init( p_dec );
283
284     return VLC_SUCCESS;
285 }
286
287 /*****************************************************************************
288  * Close:
289  *****************************************************************************/
290 static void Close( vlc_object_t *p_this )
291 {
292     decoder_t     *p_dec = (decoder_t*) p_this;
293     decoder_sys_t *p_sys = p_dec->p_sys;
294
295     free_all( p_dec );
296     free( p_sys );
297 }
298
299 /*****************************************************************************
300  * Decode:
301  *****************************************************************************/
302 static subpicture_t *Decode( decoder_t *p_dec, block_t **pp_block )
303 {
304     decoder_sys_t *p_sys = p_dec->p_sys;
305     block_t       *p_block;
306     subpicture_t  *p_spu = NULL;
307
308     if( pp_block == NULL || *pp_block == NULL ) return NULL;
309     p_block = *pp_block;
310     *pp_block = NULL;
311
312     p_sys->i_pts = p_block->i_pts;
313     if( p_sys->i_pts <= 0 )
314     {
315         msg_Warn( p_dec, "non dated subtitle" );
316         block_Release( p_block );
317         return NULL;
318     }
319
320     bs_init( &p_sys->bs, p_block->p_buffer, p_block->i_buffer );
321
322     if( bs_read( &p_sys->bs, 8 ) != 0x20 ) /* Data identifier */
323     {
324         msg_Dbg( p_dec, "invalid data identifier" );
325         block_Release( p_block );
326         return NULL;
327     }
328
329     if( bs_read( &p_sys->bs, 8 ) != 0x20 && 0 ) /* Subtitle stream id */
330     {
331         msg_Dbg( p_dec, "invalid subtitle stream id" );
332         block_Release( p_block );
333         return NULL;
334     }
335
336     while( bs_show( &p_sys->bs, 8 ) == 0x0f ) /* Sync byte */
337     {
338         decode_segment( p_dec, &p_sys->bs );
339     }
340
341     if( bs_read( &p_sys->bs, 8 ) != 0xff ) /* End marker */
342     {
343         msg_Warn( p_dec, "end marker not found (corrupted subtitle ?)" );
344         block_Release( p_block );
345         return NULL;
346     }
347
348     /* Check if the page is to be displayed */
349     if( p_sys->p_page ) p_spu = render( p_dec );
350
351     block_Release( p_block );
352
353     return p_spu;
354 }
355
356 /* following functions are local */
357
358 /*****************************************************************************
359  * default_clut_init: default clut as defined in EN 300-743 section 10
360  *****************************************************************************/
361 static void default_clut_init( decoder_t *p_dec )
362 {
363     decoder_sys_t *p_sys = p_dec->p_sys;
364     uint8_t i;
365
366 #define RGB_TO_Y(r, g, b) ((int16_t) 77 * r + 150 * g + 29 * b) / 256;
367 #define RGB_TO_U(r, g, b) ((int16_t) -44 * r - 87 * g + 131 * b) / 256;
368 #define RGB_TO_V(r, g, b) ((int16_t) 131 * r - 110 * g - 21 * b) / 256;
369
370     /* 4 entries CLUT */
371     for( i = 0; i < 4; i++ )
372     {
373         uint8_t R = 0, G = 0, B = 0, T = 0;
374
375         if( !(i & 0x2) && !(i & 0x1) ) T = 0xFF;
376         else if( !(i & 0x2) && (i & 0x1) ) R = G = B = 0xFF;
377         else if( (i & 0x2) && !(i & 0x1) ) R = G = B = 0;
378         else R = G = B = 0x7F;
379
380         p_sys->default_clut.c_2b[i].Y = RGB_TO_Y(R,G,B);
381         p_sys->default_clut.c_2b[i].Cr = RGB_TO_U(R,G,B);
382         p_sys->default_clut.c_2b[i].Cb = RGB_TO_V(R,G,B);
383         p_sys->default_clut.c_2b[i].T = T;
384     }
385
386     /* 16 entries CLUT */
387     for( i = 0; i < 16; i++ )
388     {
389         uint8_t R = 0, G = 0, B = 0, T = 0;
390
391         if( !(i & 0x8) )
392         {
393             if( !(i & 0x4) && !(i & 0x2) && !(i & 0x1) )
394             {
395                 T = 0xFF;
396             }
397             else
398             {
399                 R = (i & 0x1) ? 0xFF : 0;
400                 G = (i & 0x2) ? 0xFF : 0;
401                 B = (i & 0x4) ? 0xFF : 0;
402             }
403         }
404         else
405         {
406             R = (i & 0x1) ? 0x7F : 0;
407             G = (i & 0x2) ? 0x7F : 0;
408             B = (i & 0x4) ? 0x7F : 0;
409         }
410
411         p_sys->default_clut.c_4b[i].Y = RGB_TO_Y(R,G,B);
412         p_sys->default_clut.c_4b[i].Cr = RGB_TO_U(R,G,B);
413         p_sys->default_clut.c_4b[i].Cb = RGB_TO_V(R,G,B);
414         p_sys->default_clut.c_4b[i].T = T;
415     }
416
417     /* 256 entries CLUT (TODO) */
418     memset( p_sys->default_clut.c_8b, 0xFF, 256 * sizeof(dvbsub_color_t) );
419 }
420
421 static void decode_segment( decoder_t *p_dec, bs_t *s )
422 {
423     decoder_sys_t *p_sys = p_dec->p_sys;
424     int i_type;
425     int i_page_id;
426     int i_size;
427
428     /* sync_byte (already checked) */
429     bs_skip( s, 8 );
430
431     /* segment type */
432     i_type = bs_read( s, 8 );
433
434     /* page id */
435     i_page_id = bs_read( s, 16 );
436
437     /* segment size */
438     i_size = bs_show( s, 16 );
439
440     if( i_page_id != p_sys->i_id && i_page_id != p_sys->i_ancillary_id )
441     {
442 #ifdef DEBUG_DVBSUB
443         msg_Dbg( p_dec, "subtitle skipped (page id: %i, %i)",
444                  i_page_id, p_sys->i_id );
445 #endif
446         bs_skip( s,  8 * ( 2 + i_size ) );
447         return;
448     }
449
450 #ifdef DEBUG_DVBSUB
451     if( i_page_id == p_sys->i_id )
452         msg_Dbg( p_dec, "segment (id: %i)", i_page_id );
453     else
454         msg_Dbg( p_dec, "ancillary segment (id: %i)", i_page_id );
455 #endif
456
457     switch( i_type )
458     {
459     case DVBSUB_ST_PAGE_COMPOSITION:
460 #ifdef DEBUG_DVBSUB
461         msg_Dbg( p_dec, "decode_page_composition" );
462 #endif
463         decode_page_composition( p_dec, s );
464         break;
465
466     case DVBSUB_ST_REGION_COMPOSITION:
467 #ifdef DEBUG_DVBSUB
468         msg_Dbg( p_dec, "decode_region_composition" );
469 #endif
470         decode_region_composition( p_dec, s );
471         break;
472
473     case DVBSUB_ST_CLUT_DEFINITION:
474 #ifdef DEBUG_DVBSUB
475         msg_Dbg( p_dec, "decode_clut" );
476 #endif
477         decode_clut( p_dec, s );
478         break;
479
480     case DVBSUB_ST_OBJECT_DATA:
481 #ifdef DEBUG_DVBSUB
482         msg_Dbg( p_dec, "decode_object" );
483 #endif
484         decode_object( p_dec, s );
485         break;
486
487     case DVBSUB_ST_ENDOFDISPLAY:
488 #ifdef DEBUG_DVBSUB
489         msg_Dbg( p_dec, "end of display" );
490 #endif
491         bs_skip( s,  8 * ( 2 + i_size ) );
492         break;
493
494     case DVBSUB_ST_STUFFING:
495 #ifdef DEBUG_DVBSUB
496         msg_Dbg( p_dec, "skip stuffing" );
497 #endif
498         bs_skip( s,  8 * ( 2 + i_size ) );
499         break;
500
501     default:
502         msg_Warn( p_dec, "unsupported segment type: (%04x)", i_type );
503         bs_skip( s,  8 * ( 2 + i_size ) );
504         break;
505     }
506 }
507
508 static void decode_clut( decoder_t *p_dec, bs_t *s )
509 {
510     decoder_sys_t *p_sys = p_dec->p_sys;
511     uint16_t      i_segment_length;
512     uint16_t      i_processed_length;
513     dvbsub_clut_t *p_clut;
514     uint8_t       i_clut_id;
515     uint8_t       i_version_number;
516
517     i_segment_length = bs_read( s, 16 );
518     i_clut_id        = bs_read( s, 8 );
519     i_version_number = bs_read( s, 4 );
520
521     /* Check that this id doesn't not already exist with the same version
522      * number and allocate memory if necessary */
523     if( p_sys->p_clut[i_clut_id] != NULL &&
524         p_sys->p_clut[i_clut_id]->i_version_number == i_version_number )
525     {
526         /* Nothing to do */
527         bs_skip( s,  8 * i_segment_length - 12 );
528         return;
529     }
530
531     if( !p_sys->p_clut[i_clut_id] )
532     {
533         p_sys->p_clut[i_clut_id] = malloc( sizeof(dvbsub_clut_t) );
534     }
535
536     p_clut = p_sys->p_clut[i_clut_id];
537
538     /* We don't have this version of the CLUT: Parse it */
539     p_clut->i_version_number = i_version_number;
540     bs_skip( s, 4 ); /* Reserved bits */
541     i_processed_length = 2;
542     while( i_processed_length < i_segment_length )
543     {
544         uint8_t y, cb, cr, t;
545         uint8_t i_id;
546         uint8_t i_type;
547
548         i_id = bs_read( s, 8 );
549         i_type = bs_read( s, 3 );
550
551         bs_skip( s, 4 );
552
553         if( bs_read( s, 1 ) )
554         {
555             y  = bs_read( s, 8 );
556             cr = bs_read( s, 8 );
557             cb = bs_read( s, 8 );
558             t  = bs_read( s, 8 );
559             i_processed_length += 6;
560         }
561         else
562         {
563             y  = bs_read( s, 6 );
564             cr = bs_read( s, 4 );
565             cb = bs_read( s, 4 );
566             t  = bs_read( s, 2 );
567             i_processed_length += 4;
568         }
569
570         /* According to EN 300-743 section 7.2.3 note 1, type should
571          * not have more than 1 bit set to one, but some strams don't
572          * respect this note. */
573
574         if( i_type&0x04)
575         {
576             p_clut->c_2b[i_id].Y = y;
577             p_clut->c_2b[i_id].Cr = cr;
578             p_clut->c_2b[i_id].Cb = cb;
579             p_clut->c_2b[i_id].T = t;
580         }
581         if( i_type&0x02)
582         {
583             p_clut->c_4b[i_id].Y = y;
584             p_clut->c_4b[i_id].Cr = cr;
585             p_clut->c_4b[i_id].Cb = cb;
586             p_clut->c_4b[i_id].T = t;
587         }
588         if( i_type & 0x01)
589         {
590             p_clut->c_8b[i_id].Y = y;
591             p_clut->c_8b[i_id].Cr = cr;
592             p_clut->c_8b[i_id].Cb = cb;
593             p_clut->c_8b[i_id].T = t;
594         }
595     }
596 }
597
598 static void decode_page_composition( decoder_t *p_dec, bs_t *s )
599 {
600     decoder_sys_t *p_sys = p_dec->p_sys;
601     unsigned int i_version_number;
602     unsigned int i_state;
603     unsigned int i_segment_length;
604     uint8_t i_timeout;
605     unsigned int i;
606
607     /* A page is composed by one or more region */
608
609     i_segment_length = bs_read( s, 16 );
610     i_timeout = bs_read( s, 8 );
611     i_version_number = bs_read( s, 4 );
612     i_state = bs_read( s, 2 );
613     bs_skip( s, 2 ); /* Reserved */
614
615     if( i_state == DVBSUB_PCS_STATE_CHANGE )
616     {
617         /* End of an epoch, reset decoder buffer */
618 #ifdef DEBUG_DVBSUB
619         msg_Dbg( p_dec, "page composition mode change" );
620 #endif
621         free_all( p_dec );
622     }
623     else if( !p_sys->p_page && i_state != DVBSUB_PCS_STATE_ACQUISITION )
624     {
625         /* Not a full PCS, we need to wait for one */
626         bs_skip( s,  8 * (i_segment_length - 2) );
627         return;
628     }
629
630     if( i_state == DVBSUB_PCS_STATE_ACQUISITION )
631     {
632         /* Make sure we clean up regularly our objects list.
633          * Is it the best place to do this ? */
634         free_objects( p_dec );
635     }
636
637     /* Check version number */
638     if( p_sys->p_page &&
639         p_sys->p_page->i_version_number == i_version_number )
640     {
641         bs_skip( s,  8 * (i_segment_length - 2) );
642         return;
643     }
644     else if( p_sys->p_page )
645     {
646         if( p_sys->p_page->i_region_defs )
647             free( p_sys->p_page->p_region_defs );
648         p_sys->p_page->i_region_defs = 0;
649     }
650
651     if( !p_sys->p_page )
652     {
653         /* Allocate a new page */
654         p_sys->p_page = malloc( sizeof(dvbsub_page_t) );
655     }
656
657     p_sys->p_page->i_version_number = i_version_number;
658     p_sys->p_page->i_timeout = i_timeout;
659
660     /* Number of regions */
661     p_sys->p_page->i_region_defs = (i_segment_length - 2) / 6;
662
663     if( p_sys->p_page->i_region_defs == 0 ) return;
664
665     p_sys->p_page->p_region_defs =
666         malloc( p_sys->p_page->i_region_defs * sizeof(dvbsub_region_t) );
667     for( i = 0; i < p_sys->p_page->i_region_defs; i++ )
668     {
669         p_sys->p_page->p_region_defs[i].i_id = bs_read( s, 8 );
670         bs_skip( s, 8 ); /* Reserved */
671         p_sys->p_page->p_region_defs[i].i_x = bs_read( s, 16 );
672         p_sys->p_page->p_region_defs[i].i_y = bs_read( s, 16 );
673
674 #ifdef DEBUG_DVBSUB
675         msg_Dbg( p_dec, "page_composition, region %i (%i,%i)",
676                  i, p_sys->p_page->p_region_defs[i].i_x,
677                  p_sys->p_page->p_region_defs[i].i_y );
678 #endif
679     }
680 }
681
682 static void decode_region_composition( decoder_t *p_dec, bs_t *s )
683 {
684     decoder_sys_t *p_sys = p_dec->p_sys;
685     dvbsub_region_t *p_region, **pp_region = &p_sys->p_regions;
686     int i_segment_length;
687     int i_processed_length;
688     int i_region_id;
689     int i_version_number;
690
691     i_segment_length = bs_read( s, 16 );
692     i_region_id = bs_read( s, 8 );
693     i_version_number = bs_read( s, 4 );
694
695     /* Check if we already have this region */
696     for( p_region = p_sys->p_regions; p_region != NULL;
697          p_region = p_region->p_next )
698     {
699         pp_region = &p_region->p_next;
700         if( p_region->i_id == i_region_id ) break;
701     }
702
703     /* Check version number */
704     if( p_region &&
705         p_region->i_version_number == i_version_number )
706     {
707         bs_skip( s,  8 * (i_segment_length - 1) - 4 );
708         return;
709     }
710     else if( p_region )
711     {
712         if( p_region->i_object_defs )
713             free( p_region->p_object_defs );
714     }
715
716     if( !p_region )
717     {
718 #ifdef DEBUG_DVBSUB
719         msg_Dbg( p_dec, "new region: %i", i_region_id );
720 #endif
721         p_region = *pp_region = malloc( sizeof(dvbsub_region_t) );
722         p_region->p_next = NULL;
723     }
724
725     /* Region attributes */
726     p_region->i_id = i_region_id;
727     p_region->i_version_number = i_version_number;
728     p_region->b_fill           = bs_read( s, 1 );
729     bs_skip( s, 3 ); /* Reserved */
730     p_region->i_width          = bs_read( s, 16 );
731     p_region->i_height         = bs_read( s, 16 );
732     p_region->i_level_comp     = bs_read( s, 3 );
733     p_region->i_depth          = bs_read( s, 3 );
734     bs_skip( s, 2 ); /* Reserved */
735     p_region->i_clut           = bs_read( s, 8 );
736     p_region->i_8bp_code       = bs_read( s, 8 );
737     p_region->i_4bp_code       = bs_read( s, 4 );
738     p_region->i_2bp_code       = bs_read( s, 2 );
739     bs_skip( s, 2 ); /* Reserved */
740     p_region->p_object_defs    = NULL;
741     p_region->i_object_defs    = 0;
742
743     /* List of objects in the region */
744     i_processed_length = 10;
745     while( i_processed_length < i_segment_length )
746     {
747         dvbsub_objectdef_t *p_obj;
748
749         /* We create a new object */
750         p_region->i_object_defs++;
751         p_region->p_object_defs =
752             realloc( p_region->p_object_defs,
753                      sizeof(dvbsub_objectdef_t) * p_region->i_object_defs );
754
755         /* We parse object properties */
756         p_obj = &p_region->p_object_defs[p_region->i_object_defs - 1];
757         p_obj->i_id         = bs_read( s, 16 );
758         p_obj->i_type       = bs_read( s, 2 );
759         p_obj->i_provider   = bs_read( s, 2 );
760         p_obj->i_x          = bs_read( s, 12 );
761         bs_skip( s, 4 ); /* Reserved */
762         p_obj->i_y          = bs_read( s, 12 );
763
764         i_processed_length += 6;
765
766         if( p_obj->i_type == DVBSUB_OT_BASIC_CHAR ||
767             p_obj->i_type == DVBSUB_OT_COMPOSITE_STRING )
768         {
769             p_obj->i_fg_pc =  bs_read( s, 8 );
770             p_obj->i_bg_pc =  bs_read( s, 8 );
771             i_processed_length += 2;
772         }
773     }
774 }
775
776 static dvbsub_image_t *dvbsub_parse_pdata( decoder_t *, bs_t *, uint16_t );
777 static uint16_t dvbsub_pdata2bpp( bs_t *, uint16_t *, dvbsub_image_t *, int );
778 static uint16_t dvbsub_pdata4bpp( bs_t *, uint16_t *, dvbsub_image_t *, int );
779 static uint16_t dvbsub_pdata8bpp( bs_t *, uint16_t *, dvbsub_image_t *, int );
780
781 static void decode_object( decoder_t *p_dec, bs_t *s )
782 {
783     decoder_sys_t   *p_sys = p_dec->p_sys;
784     dvbsub_object_t *p_obj, **pp_obj = &p_sys->p_objects;
785     int i_segment_length;
786     int i_version_number;
787     int i_coding_method;
788     int i_obj_id;
789
790     i_segment_length   = bs_read( s, 16 );
791     i_obj_id           = bs_read( s, 16 );
792     i_version_number   = bs_read( s, 4 );
793     i_coding_method    = bs_read( s, 2 );
794
795     if( i_coding_method )
796     {
797         /* TODO: DVB subtitling as characters */
798         msg_Dbg( p_dec, "DVB subtitling as characters is not handled!" );
799         bs_skip( s,  8 * (i_segment_length - 2) - 6 );
800         return;
801     }
802
803     /* Check if we already have this region */
804     for( p_obj = p_sys->p_objects; p_obj != NULL; p_obj = p_obj->p_next )
805     {
806         pp_obj = &p_obj->p_next;
807         if( p_obj->i_id == i_obj_id ) break;
808     }
809
810     /* Check version number */
811     if( p_obj && p_obj->i_version_number == i_version_number )
812     {
813         bs_skip( s,  8 * (i_segment_length - 2) - 6 );
814         return;
815     }
816     else if( p_obj )
817     {
818         /* Clean structure */
819     }
820
821     if( !p_obj )
822     {
823 #ifdef DEBUG_DVBSUB
824         msg_Dbg( p_dec, "new object: %i", i_obj_id );
825 #endif
826         p_obj = *pp_obj = malloc( sizeof(dvbsub_object_t) );
827         p_obj->p_next = NULL;
828     }
829
830     p_obj->i_id               = i_obj_id;
831     p_obj->i_version_number   = i_version_number;
832     p_obj->i_coding_method    = i_coding_method;
833     p_obj->b_non_modify_color = bs_read( s, 1 );
834     bs_skip( s, 1 ); /* Reserved */
835
836     if( p_obj->i_coding_method == 0x00 )
837     {
838         uint16_t i_topfield_length;
839         uint16_t i_bottomfield_length;
840
841         i_topfield_length    = bs_read( s, 16 );
842         i_bottomfield_length = bs_read( s, 16 );
843
844         p_obj->topfield =
845             dvbsub_parse_pdata( p_dec, s, i_topfield_length );
846         p_obj->bottomfield =
847             dvbsub_parse_pdata( p_dec, s, i_bottomfield_length );
848
849         /* Check word-alignement */
850         bs_align( s );
851         if( bs_pos( s ) % 16 ) bs_skip( s, 8 );
852     }
853     else
854     {
855         /* TODO: DVB subtitling as characters */
856     }
857
858 #ifdef DEBUG_DVBSUB
859         msg_Dbg( p_dec, "end object: %i", i_obj_id );
860 #endif
861 }
862
863 static dvbsub_image_t* dvbsub_parse_pdata( decoder_t *p_dec, bs_t *s,
864                                            uint16_t length )
865 {
866     dvbsub_image_t* p_image;
867     uint16_t i_processed_length = 0;
868     uint16_t i_lines = 0;
869     uint16_t i_cols_last = 0;
870
871     p_image = malloc( sizeof(dvbsub_image_t) );
872     p_image->p_last = p_image->p_codes = NULL;
873
874     memset( p_image->i_cols, 0, 576 * sizeof(uint16_t) );
875
876     /* Let's parse it a first time to determine the size of the buffer */
877     while( i_processed_length < length )
878     {
879         i_processed_length++;
880
881         switch( bs_read( s, 8 ) )
882         {
883             case 0x10:
884                 i_processed_length +=
885                     dvbsub_pdata2bpp( s, &p_image->i_cols[i_lines],
886                                       p_image, length - i_processed_length );
887                 break;
888             case 0x11:
889                 i_processed_length +=
890                     dvbsub_pdata4bpp( s, &p_image->i_cols[i_lines],
891                                       p_image, length - i_processed_length );
892                 break;
893             case 0x12:
894                 i_processed_length +=
895                     dvbsub_pdata8bpp( s, &p_image->i_cols[i_lines],
896                                       p_image, length - i_processed_length );
897                 break;
898             case 0x20:
899             case 0x21:
900             case 0x22:
901                 /* We don't use map tables */
902                 break;
903             case 0xf0:
904                 i_lines++; /* End of line code */
905                 break;
906         }
907     }
908
909     p_image->i_rows = i_lines;
910     p_image->i_cols[i_lines] = i_cols_last;
911
912     return p_image;
913 }
914
915 static void add_rle_code( dvbsub_image_t *p, uint16_t num, uint8_t color,
916                           int i_bpp )
917 {
918     if( p->p_last != NULL )
919     {
920         p->p_last->p_next = malloc( sizeof(dvbsub_rle_t) );
921         p->p_last = p->p_last->p_next;
922     }
923     else
924     {
925         p->p_codes = malloc( sizeof(dvbsub_rle_t) );
926         p->p_last = p->p_codes;
927     }
928     p->p_last->i_num = num;
929
930     p->p_last->i_color_code = color;
931     p->p_last->i_bpp = i_bpp;
932     p->p_last->p_next = NULL;
933 }
934
935 static uint16_t dvbsub_pdata2bpp( bs_t *s, uint16_t* p,
936                                   dvbsub_image_t* p_image, int i_length )
937 {
938     uint16_t i_processed = 0;
939     vlc_bool_t b_stop = 0;
940     uint16_t i_count = 0;
941     uint8_t i_color = 0;
942
943     while( !b_stop && i_processed/8 < i_length )
944     {
945         i_processed += 2;
946         if( (i_color = bs_read( s, 2 )) != 0x00 )
947         {
948             (*p)++;
949
950             /* Add 1 pixel */
951             add_rle_code( p_image, 1, i_color, 2 );
952         }
953         else
954         {
955             i_processed++;
956             if( bs_read( s, 1 ) == 0x01 )         // Switch1
957             {
958                 i_count = 3 + bs_read( s, 3 );
959                 (*p) += i_count ;
960                 i_color = bs_read( s, 2 );
961                 add_rle_code( p_image, i_count, i_color, 2 );
962                 i_processed += 5;
963             }
964             else
965             {
966                 i_processed++;
967                 if( bs_read( s, 1 ) == 0x00 )     //Switch2
968                 {
969                     i_processed += 2;
970                     switch( bs_read( s, 2 ) )     //Switch3
971                     {
972                     case 0x00:
973                         b_stop=1;
974                         break;
975                     case 0x01:
976                         (*p) += 2 ;
977                         add_rle_code( p_image, 2, 0, 2 );
978                         break;
979                     case 0x02:
980                         i_count =  12 + bs_read( s, 4 );
981                         i_color = bs_read( s, 2 );
982                         (*p) += i_count;
983                         i_processed += 6;
984                         add_rle_code( p_image, i_count, i_color, 2 );
985                         break;
986                     case 0x03:
987                         i_count =  29 + bs_read( s, 8 );
988                         i_color = bs_read( s, 2 );
989                         (*p) += i_count;
990                         i_processed += 10;
991                         add_rle_code( p_image, i_count, i_color, 2 );
992                         break;
993                     default:
994                         break;
995                     }
996                 }
997                 else
998                 {
999                     (*p)++;
1000                     add_rle_code( p_image, 1, 0, 2 ); /* 1 pixel color 0 */
1001                 }
1002             }
1003         }
1004     }
1005
1006     bs_align( s );
1007
1008     return ( i_processed + 7 ) / 8;
1009 }
1010
1011 static uint16_t dvbsub_pdata4bpp( bs_t *s, uint16_t* p,
1012                                   dvbsub_image_t* p_image, int i_length )
1013 {
1014     uint16_t i_processed = 0;
1015     vlc_bool_t b_stop = 0;
1016     uint16_t i_count = 0;
1017     uint8_t i_color = 0;
1018
1019     while( !b_stop && i_processed/8 < i_length )
1020     {
1021         if( (i_color = bs_read( s, 4 )) != 0x00 )
1022         {
1023             (*p)++;
1024             i_processed+=4;
1025
1026             /* Add 1 pixel */
1027             add_rle_code( p_image, 1, i_color, 4 );
1028         }
1029         else
1030         {
1031             if( bs_read( s, 1 ) == 0x00 )           // Switch1
1032             {
1033                 if( bs_show( s, 3 ) != 0x00 )
1034                 {
1035                     i_count = 2 + bs_read( s, 3 );
1036                     (*p) += i_count ;
1037                     add_rle_code( p_image, i_count, 0x00, 4 );
1038                 }
1039                 else
1040                 {
1041                     bs_skip( s, 3 );
1042                     b_stop=1;
1043                 }
1044                 i_processed += 8;
1045             }
1046             else
1047             {
1048                 if( bs_read( s, 1 ) == 0x00)        //Switch2
1049                 {
1050                     i_count =  4 + bs_read( s, 2 );
1051                     i_color = bs_read( s, 4 );
1052                     (*p) += i_count;
1053                     i_processed += 12;
1054                     add_rle_code( p_image, i_count, i_color, 4 );
1055                 }
1056                 else
1057                 {
1058                     switch ( bs_read( s, 2 ) )     //Switch3
1059                     {
1060                         case 0x0:
1061                             (*p)++;
1062                             i_processed += 8;
1063                             add_rle_code( p_image, 1, 0x00, 4 );
1064                             break;
1065                         case 0x1:
1066                             (*p)+=2;
1067                             i_processed += 8;
1068                             add_rle_code( p_image, 2, 0x00, 4 );
1069                             break;
1070                         case 0x2:
1071                              i_count = 9 + bs_read( s, 4 );
1072                              i_color = bs_read( s, 4 );
1073                              (*p)+= i_count;
1074                              i_processed += 16;
1075                              add_rle_code( p_image, i_count, i_color, 4 );
1076                              break;
1077                         case 0x3:
1078                              i_count= 25 + bs_read( s, 8 );
1079                              i_color = bs_read( s, 4 );
1080                              (*p)+= i_count;
1081                              i_processed += 20;
1082                              add_rle_code( p_image, i_count, i_color, 4 );
1083                              break;
1084                     }
1085                 }
1086             }
1087         }
1088     }
1089
1090     bs_align( s );
1091
1092     return ( i_processed + 7 ) / 8 ;
1093 }
1094
1095 static uint16_t dvbsub_pdata8bpp( bs_t *s, uint16_t* p,
1096                                   dvbsub_image_t* p_image, int i_length )
1097 {
1098     uint16_t i_processed = 0;
1099     vlc_bool_t b_stop = 0;
1100     uint16_t i_count = 0;
1101     uint8_t i_color = 0;
1102
1103     while( !b_stop && i_processed/8 < i_length )
1104     {
1105         i_processed += 8;
1106         if( (i_color = bs_read( s, 8 )) != 0x00 )
1107         {
1108             (*p)++;
1109
1110             /* Add 1 pixel */
1111             add_rle_code( p_image, 1, i_color, 8 );
1112         }
1113         else
1114         {
1115             i_processed++;
1116             if( bs_read( s, 1 ) == 0x00 )           // Switch1
1117             {
1118                 if( bs_show( s, 7 ) != 0x00 )
1119                 {
1120                     i_count = bs_read( s, 7 );
1121                     (*p) += i_count ;
1122                     add_rle_code( p_image, i_count, 0x00, 8 );
1123                 }
1124                 else
1125                 {
1126                     bs_skip( s, 7 );
1127                     b_stop = 1;
1128                 }
1129                 i_processed += 7;
1130             }
1131             else
1132             {
1133                 i_count = bs_read( s, 7 );
1134                 (*p) += i_count ;
1135                 i_color = bs_read( s, 8 );
1136                 add_rle_code( p_image, i_count, i_color, 8 );
1137                 i_processed += 15;
1138             }
1139         }
1140     }
1141
1142     bs_align( s );
1143
1144     return ( i_processed + 7 ) / 8 ;
1145 }
1146
1147 static void free_image( dvbsub_image_t *p_i )
1148 {
1149     dvbsub_rle_t *p1;
1150     dvbsub_rle_t *p2 = NULL;
1151
1152     for( p1 = p_i->p_codes; p1 != NULL; p1 = p2 )
1153     {
1154         p2 = p1->p_next;
1155         free( p1 );
1156         p1 = NULL;
1157     }
1158
1159     free( p_i );
1160 }
1161
1162 static void free_objects( decoder_t *p_dec )
1163 {
1164     decoder_sys_t *p_sys = p_dec->p_sys;
1165     dvbsub_object_t *p_obj, *p_obj_next;
1166
1167     for( p_obj = p_sys->p_objects; p_obj != NULL; p_obj = p_obj_next )
1168     {
1169         p_obj_next = p_obj->p_next;
1170         free_image( p_obj->topfield );
1171         free_image( p_obj->bottomfield );
1172         free( p_obj );
1173     }
1174     p_sys->p_objects = NULL;
1175 }
1176
1177 static void free_all( decoder_t *p_dec )
1178 {
1179     decoder_sys_t *p_sys = p_dec->p_sys;
1180     dvbsub_region_t *p_reg, *p_reg_next;
1181     int i;
1182
1183     for( i = 0; i < 256; i++ )
1184     {
1185         if( p_sys->p_clut[i] ) free( p_sys->p_clut[i] );
1186         p_sys->p_clut[i] = NULL;
1187     }
1188
1189     if( p_sys->p_page )
1190     {
1191         if( p_sys->p_page->i_region_defs )
1192             free( p_sys->p_page->p_region_defs );
1193         free( p_sys->p_page );
1194         p_sys->p_page = NULL;
1195     }
1196
1197     for( p_reg = p_sys->p_regions; p_reg != NULL; p_reg = p_reg_next )
1198     {
1199         p_reg_next = p_reg->p_next;
1200         if( p_reg->i_object_defs ) free( p_reg->p_object_defs );
1201         free( p_reg );
1202     }
1203     p_sys->p_regions = NULL;
1204
1205     free_objects( p_dec );
1206 }
1207
1208 static subpicture_t *render( decoder_t *p_dec )
1209 {
1210     decoder_sys_t   *p_sys = p_dec->p_sys;
1211     dvbsub_clut_t   *p_clut;
1212     dvbsub_rle_t    *p_c;
1213     subpicture_t    *p_spu;
1214     subpicture_region_t **pp_spu_region;
1215     int i, j = 0, i_timeout = 0;
1216
1217     /* Allocate the subpicture internal data. */
1218     p_spu = p_dec->pf_spu_buffer_new( p_dec );
1219     if( !p_spu ) return NULL;
1220
1221     pp_spu_region = &p_spu->p_region;
1222
1223     /* Loop on region definitions */
1224 #ifdef DEBUG_DVBSUB
1225     if( p_sys->p_page )
1226         msg_Dbg( p_dec, "rendering %i regions", p_sys->p_page->i_region_defs );
1227 #endif
1228
1229     for( i = 0; p_sys->p_page && i < p_sys->p_page->i_region_defs; i++ )
1230     {
1231         dvbsub_region_t     *p_region;
1232         dvbsub_regiondef_t  *p_regiondef;
1233         subpicture_region_t *p_spu_region;
1234         uint8_t *p_y, *p_u, *p_v, *p_a;
1235         video_format_t fmt;
1236         int i_pitch;
1237
1238         i_timeout = p_sys->p_page->i_timeout;
1239
1240         p_regiondef = &p_sys->p_page->p_region_defs[i];
1241
1242 #ifdef DEBUG_DVBSUB
1243         msg_Dbg( p_dec, "rendering region %i (%i,%i)", i,
1244                  p_regiondef->i_x, p_regiondef->i_y );
1245 #endif
1246
1247         /* Find associated region */
1248         for( p_region = p_sys->p_regions; p_region != NULL;
1249              p_region = p_region->p_next )
1250         {
1251             if( p_regiondef->i_id == p_region->i_id ) break;
1252         }
1253
1254         if( !p_region )
1255         {
1256             msg_Err( p_dec, "no region founddddd!!!" );
1257             continue;
1258         }
1259
1260         /* Create new SPU region */
1261         memset( &fmt, 0, sizeof(video_format_t) );
1262         fmt.i_chroma = VLC_FOURCC('Y','U','V','A');
1263         fmt.i_aspect = VOUT_ASPECT_FACTOR;
1264         fmt.i_width = fmt.i_visible_width = p_region->i_width;
1265         fmt.i_height = fmt.i_visible_height = p_region->i_height;
1266         fmt.i_x_offset = fmt.i_y_offset = 0;
1267         p_spu_region = p_spu->pf_create_region( VLC_OBJECT(p_dec), &fmt );
1268         if( !p_region )
1269         {
1270             msg_Err( p_dec, "cannot allocate SPU region" );
1271             continue;
1272         }
1273         p_spu_region->i_x = p_regiondef->i_x;
1274         p_spu_region->i_y = p_regiondef->i_y;
1275         *pp_spu_region = p_spu_region;
1276         pp_spu_region = &p_spu_region->p_next;
1277
1278         p_y = p_spu_region->picture.Y_PIXELS;
1279         p_u = p_spu_region->picture.U_PIXELS;
1280         p_v = p_spu_region->picture.V_PIXELS;
1281         p_a = p_spu_region->picture.A_PIXELS;
1282         i_pitch = p_spu_region->picture.Y_PITCH;
1283         memset( p_a, 0, i_pitch * p_region->i_height );
1284
1285         /* Loop on object definitions */
1286         for( j = 0; j < p_region->i_object_defs; j++ )
1287         {
1288             dvbsub_object_t    *p_object;
1289             dvbsub_objectdef_t *p_objectdef;
1290             uint16_t k, l, x, y;
1291
1292             p_objectdef = &p_region->p_object_defs[j];
1293
1294 #ifdef DEBUG_DVBSUB
1295             msg_Dbg( p_dec, "rendering object %i (%i,%i)", p_objectdef->i_id,
1296                      p_objectdef->i_x, p_objectdef->i_y );
1297 #endif
1298
1299             /* Look for the right object */
1300             for( p_object = p_sys->p_objects; p_object != NULL;
1301                  p_object = p_object->p_next )
1302             {
1303                 if( p_objectdef->i_id == p_object->i_id ) break;
1304             }
1305
1306             if( !p_object )
1307             {
1308                 msg_Err( p_dec, "no object founddddd!!!" );
1309                 continue;
1310             }
1311
1312             /* Draw SPU region */
1313             p_clut = p_sys->p_clut[p_region->i_clut];
1314             if( !p_clut ) p_clut = &p_sys->default_clut;
1315
1316             for( k = 0, l = 0, p_c = p_object->topfield->p_codes;
1317                  p_c && p_c->p_next; p_c = p_c->p_next )
1318             {
1319                 /* Compute the color data according to the appropriate CLUT */
1320                 dvbsub_color_t *p_color = (p_c->i_bpp == 2) ? p_clut->c_2b :
1321                     (p_c->i_bpp == 4) ? p_clut->c_4b : p_clut->c_8b;
1322
1323                 x = l + p_objectdef->i_x;
1324                 y = 2 * k + p_objectdef->i_y;
1325                 memset( p_y + y * i_pitch + x, p_color[p_c->i_color_code].Y,
1326                         p_c->i_num );
1327                 memset( p_u + y * i_pitch + x, p_color[p_c->i_color_code].Cr,
1328                         p_c->i_num );
1329                 memset( p_v + y * i_pitch + x, p_color[p_c->i_color_code].Cb,
1330                         p_c->i_num );
1331                 memset( p_a + y * i_pitch + x,
1332                         255 - p_color[p_c->i_color_code].T, p_c->i_num );
1333
1334                 l += p_c->i_num;
1335                 if( l >= p_object->topfield->i_cols[k] ) { k++; l = 0; }
1336                 if( k >= p_object->topfield->i_rows) break;
1337
1338             }
1339
1340             for( k = 0, l = 0, p_c = p_object->bottomfield->p_codes;
1341                  p_c && p_c->p_next; p_c = p_c->p_next )
1342             {
1343                 /* Compute the color data according to the appropriate CLUT */
1344                 dvbsub_color_t *p_color = (p_c->i_bpp == 2) ? p_clut->c_2b :
1345                     (p_c->i_bpp == 4) ? p_clut->c_4b : p_clut->c_8b;
1346
1347                 x = l + p_objectdef->i_x;
1348                 y = 2 * k + 1 + p_objectdef->i_y;
1349                 memset( p_y + y * i_pitch + x, p_color[p_c->i_color_code].Y,
1350                         p_c->i_num );
1351                 memset( p_u + y * i_pitch + x, p_color[p_c->i_color_code].Cr,
1352                         p_c->i_num );
1353                 memset( p_v + y * i_pitch + x, p_color[p_c->i_color_code].Cb,
1354                         p_c->i_num );
1355                 memset( p_a + y * i_pitch + x,
1356                         255 - p_color[p_c->i_color_code].T, p_c->i_num );
1357
1358                 l += p_c->i_num;
1359                 if( l >= p_object->bottomfield->i_cols[k] ) { k++; l = 0; }
1360                 if( k >= p_object->bottomfield->i_rows) break;
1361
1362             }
1363         }
1364     }
1365
1366     /* Set the pf_render callback */
1367     p_spu->i_start = p_sys->i_pts;
1368     p_spu->i_stop = p_spu->i_start + i_timeout * 1000000;
1369     p_spu->b_ephemer = VLC_TRUE;
1370
1371     return p_spu;
1372 }
1373
1374 /*****************************************************************************
1375  * encoder_sys_t : encoder descriptor
1376  *****************************************************************************/
1377 struct encoder_sys_t
1378 {
1379     unsigned int i_page_ver;
1380     unsigned int i_region_ver;
1381     unsigned int i_clut_ver;
1382
1383     /*
1384      * Input properties
1385      */
1386     /*
1387      * Common properties
1388      */
1389     mtime_t i_pts;
1390 };
1391
1392 static void encode_page_composition( encoder_t *, bs_t *, subpicture_t * );
1393 static void encode_clut( encoder_t *, bs_t *, subpicture_t * );
1394 static void encode_region_composition( encoder_t *, bs_t *, subpicture_t * );
1395 static void encode_object( encoder_t *, bs_t *, subpicture_t * );
1396
1397 /*****************************************************************************
1398  * OpenEncoder: probe the encoder and return score
1399  *****************************************************************************/
1400 static int OpenEncoder( vlc_object_t *p_this )
1401 {
1402     encoder_t *p_enc = (encoder_t *)p_this;
1403     encoder_sys_t *p_sys;
1404
1405     if( p_enc->fmt_out.i_codec != VLC_FOURCC('d','v','b','s') &&
1406         !p_enc->b_force )
1407     {
1408         return VLC_EGENERIC;
1409     }
1410
1411     /* Allocate the memory needed to store the decoder's structure */
1412     if( ( p_sys = (encoder_sys_t *)malloc(sizeof(encoder_sys_t)) ) == NULL )
1413     {
1414         msg_Err( p_enc, "out of memory" );
1415         return VLC_EGENERIC;
1416     }
1417     p_enc->p_sys = p_sys;
1418
1419     p_enc->pf_encode_sub = Encode;
1420     p_enc->fmt_out.i_codec = VLC_FOURCC('d','v','b','s');
1421     p_enc->fmt_out.subs.dvb.i_id  = 1 << 16 | 1;
1422
1423     sout_CfgParse( p_enc, ENC_CFG_PREFIX, ppsz_enc_options, p_enc->p_cfg );
1424
1425     p_sys->i_page_ver = 0;
1426     p_sys->i_region_ver = 0;
1427     p_sys->i_clut_ver = 0;
1428
1429     return VLC_SUCCESS;
1430 }
1431
1432 /****************************************************************************
1433  * Encode: the whole thing
1434  ****************************************************************************/
1435 static block_t *Encode( encoder_t *p_enc, subpicture_t *p_subpic )
1436 {
1437     bs_t bits, *s = &bits;
1438     block_t *p_block;
1439
1440     if( !p_subpic || !p_subpic->p_region ) return 0;
1441
1442     msg_Dbg( p_enc, "encoding subpicture" );
1443
1444     p_block = block_New( p_enc, 64000 );
1445     bs_init( s, p_block->p_buffer, p_block->i_buffer );
1446
1447     bs_write( s, 8, 0x20 ); /* Data identifier */
1448     bs_write( s, 8, 0x20 ); /* Subtitle stream id */
1449
1450     encode_page_composition( p_enc, s, p_subpic );
1451     encode_clut( p_enc, s, p_subpic );
1452     encode_region_composition( p_enc, s, p_subpic );
1453     encode_object( p_enc, s, p_subpic );
1454
1455     /* End of display */
1456     bs_write( s, 8, 0x0f ); /* Sync byte */
1457     bs_write( s, 8, DVBSUB_ST_ENDOFDISPLAY ); /* Segment type */
1458     bs_write( s, 16, 1 ); /* Page id */
1459     bs_write( s, 16, 0 ); /* Segment length */
1460
1461     bs_write( s, 8, 0xff ); /* End marker */
1462     p_block->i_buffer = bs_pos( s ) / 8;
1463     p_block->i_pts = p_block->i_dts = p_subpic->i_start;
1464     if( !p_subpic->b_ephemer && p_subpic->i_stop )
1465         p_block->i_length = p_subpic->i_stop - p_subpic->i_start;
1466
1467     msg_Dbg( p_enc, "subpicture encoded properly" );
1468
1469     return p_block;
1470 }
1471
1472 /*****************************************************************************
1473  * CloseEncoder: encoder destruction
1474  *****************************************************************************/
1475 static void CloseEncoder( vlc_object_t *p_this )
1476 {
1477     encoder_t *p_enc = (encoder_t *)p_this;
1478     encoder_sys_t *p_sys = p_enc->p_sys;
1479
1480     free( p_sys );
1481 }
1482
1483 static void encode_page_composition( encoder_t *p_enc, bs_t *s,
1484                                      subpicture_t *p_subpic )
1485 {
1486     encoder_sys_t *p_sys = p_enc->p_sys;
1487     subpicture_region_t *p_region;
1488     int i_regions;
1489
1490     bs_write( s, 8, 0x0f ); /* Sync byte */
1491     bs_write( s, 8, DVBSUB_ST_PAGE_COMPOSITION ); /* Segment type */
1492     bs_write( s, 16, 1 ); /* Page id */
1493
1494     for( i_regions = 0, p_region = p_subpic->p_region; p_region;
1495          p_region = p_region->p_next, i_regions++ );
1496
1497     bs_write( s, 16, i_regions * 6 + 2 ); /* Segment length */
1498
1499     bs_write( s, 8, 5 ); /* Timeout */
1500     bs_write( s, 4, p_sys->i_page_ver++ );
1501     bs_write( s, 2, DVBSUB_PCS_STATE_ACQUISITION );
1502     bs_write( s, 2, 0 ); /* Reserved */
1503
1504     for( i_regions = 0, p_region = p_subpic->p_region; p_region;
1505          p_region = p_region->p_next, i_regions++ )
1506     {
1507         bs_write( s, 8, i_regions );
1508         bs_write( s, 8, 0 ); /* Reserved */
1509         bs_write( s, 16, p_region->i_x );
1510         bs_write( s, 16, p_region->i_y );
1511     }
1512 }
1513
1514 static void encode_clut( encoder_t *p_enc, bs_t *s, subpicture_t *p_subpic )
1515 {
1516     encoder_sys_t *p_sys = p_enc->p_sys;
1517     subpicture_region_t *p_region = p_subpic->p_region;
1518     video_palette_t *p_pal;
1519     int i;
1520
1521     /* Sanity check */
1522     if( !p_region || !p_region->fmt.p_palette ||
1523         p_region->fmt.i_chroma != VLC_FOURCC('Y','U','V','P') ) return;
1524
1525     bs_write( s, 8, 0x0f ); /* Sync byte */
1526     bs_write( s, 8, DVBSUB_ST_CLUT_DEFINITION ); /* Segment type */
1527     bs_write( s, 16, 1 ); /* Page id */
1528
1529     p_pal = p_region->fmt.p_palette;
1530
1531     bs_write( s, 16, p_pal->i_entries * 6 + 2 ); /* Segment length */
1532     bs_write( s, 8, 1 ); /* Clut id */
1533     bs_write( s, 4, p_sys->i_clut_ver++ );
1534     bs_write( s, 4, 0 ); /* Reserved */
1535
1536     for( i = 0; i < p_pal->i_entries; i++ )
1537     {
1538         bs_write( s, 8, i ); /* Clut entry id */
1539         bs_write( s, 1, p_pal->i_entries == 4 );   /* 2bit/entry flag */
1540         bs_write( s, 1, p_pal->i_entries == 16 );  /* 4bit/entry flag */
1541         bs_write( s, 1, p_pal->i_entries == 256 ); /* 8bit/entry flag */
1542         bs_write( s, 4, 0 ); /* Reserved */
1543         bs_write( s, 1, 1 ); /* Full range flag */
1544         bs_write( s, 8, p_pal->palette[i][0] ); /* Y value */
1545         bs_write( s, 8, p_pal->palette[i][1] ); /* Cr value */
1546         bs_write( s, 8, p_pal->palette[i][2] ); /* Cb value */
1547         bs_write( s, 8, 0xff - p_pal->palette[i][3] ); /* T value */
1548     }
1549 }
1550
1551 static void encode_region_composition( encoder_t *p_enc, bs_t *s,
1552                                        subpicture_t *p_subpic )
1553 {
1554     encoder_sys_t *p_sys = p_enc->p_sys;
1555     subpicture_region_t *p_region;
1556     int i_regions;
1557
1558     for( i_regions = 0, p_region = p_subpic->p_region; p_region;
1559          p_region = p_region->p_next, i_regions++ )
1560     {
1561         video_palette_t *p_pal = p_region->fmt.p_palette;
1562
1563         bs_write( s, 8, 0x0f ); /* Sync byte */
1564         bs_write( s, 8, DVBSUB_ST_REGION_COMPOSITION ); /* Segment type */
1565         bs_write( s, 16, 1 ); /* Page id */
1566
1567         bs_write( s, 16, 10 + 6 ); /* Segment length */
1568         bs_write( s, 8, i_regions );
1569         bs_write( s, 4, p_sys->i_region_ver++ );
1570
1571         /* Region attributes */
1572         bs_write( s, 1, 0 ); /* Fill */
1573         bs_write( s, 3, 0 ); /* Reserved */
1574         bs_write( s, 16, p_region->fmt.i_visible_width );
1575         bs_write( s, 16, p_region->fmt.i_visible_height );
1576         bs_write( s, 3, p_pal->i_entries ); /* Region level of compatibility */
1577         bs_write( s, 3, p_pal->i_entries  ); /* Region depth */
1578         bs_write( s, 2, 0 ); /* Reserved */
1579         bs_write( s, 8, 1 ); /* Clut id */
1580         bs_write( s, 8, 0 /*p_region->i_8bp_code*/ );
1581         bs_write( s, 4, 0 /*p_region->i_4bp_code*/ );
1582         bs_write( s, 2, 0 /*p_region->i_2bp_code*/ );
1583         bs_write( s, 2, 0 ); /* Reserved */
1584
1585         /* In our implementation we only have 1 object per region */
1586         bs_write( s, 16, i_regions );
1587         bs_write( s, 2, DVBSUB_OT_BASIC_BITMAP );
1588         bs_write( s, 2, 0 /*p_obj->i_provider*/ );
1589         bs_write( s, 12, 0 /*p_obj->i_x*/ );
1590         bs_write( s, 4, 0 ); /* Reserved */
1591         bs_write( s, 12, 0 /*p_obj->i_y*/ );
1592     }
1593 }
1594
1595 static void encode_pixel_data( encoder_t *p_enc, bs_t *s,
1596                                subpicture_region_t *p_region,
1597                                vlc_bool_t b_top );
1598
1599 static void encode_object( encoder_t *p_enc, bs_t *s, subpicture_t *p_subpic )
1600 {
1601     encoder_sys_t   *p_sys = p_enc->p_sys;
1602     subpicture_region_t *p_region;
1603     int i_regions;
1604
1605     int i_update_pos;
1606     int i_pixel_data_pos;
1607
1608     for( i_regions = 0, p_region = p_subpic->p_region; p_region;
1609          p_region = p_region->p_next, i_regions++ )
1610     {
1611         bs_write( s, 8, 0x0f ); /* Sync byte */
1612         bs_write( s, 8, DVBSUB_ST_OBJECT_DATA ); /* Segment type */
1613         bs_write( s, 16, 1 ); /* Page id */
1614
1615         bs_write( s, 16, 8 ); /* Segment length */
1616         bs_write( s, 16, i_regions ); /* Object id */
1617         bs_write( s, 4, p_sys->i_region_ver++ );
1618         bs_write( s, 2, 0 /*i_coding_method*/ );
1619
1620         bs_write( s, 1, 0 /*p_obj->b_non_modify_color*/ );
1621         bs_write( s, 1, 0 ); /* Reserved */
1622
1623         i_update_pos = bs_pos( s );
1624         bs_write( s, 16, 0 /*i_topfield_length*/ );
1625         bs_write( s, 16, 0 /*i_bottomfield_length*/ );
1626
1627         /* Top field */
1628         i_pixel_data_pos = bs_pos( s );
1629         encode_pixel_data( p_enc, s, p_region, VLC_TRUE );
1630         i_pixel_data_pos = ( bs_pos( s ) - i_pixel_data_pos ) / 8;
1631         SetWBE( &s->p_start[i_update_pos/8], i_pixel_data_pos );
1632
1633         /* Bottom field */
1634         i_pixel_data_pos = bs_pos( s );
1635         encode_pixel_data( p_enc, s, p_region, VLC_FALSE );
1636         i_pixel_data_pos = ( bs_pos( s ) - i_pixel_data_pos ) / 8;
1637         SetWBE( &s->p_start[i_update_pos/8+2], i_pixel_data_pos );
1638
1639         /* Stuffing for word alignment */
1640         bs_align_0( s );
1641         if( bs_pos( s ) % 16 ) bs_write( s, 8, 0 );
1642     }
1643 }
1644
1645 static void encode_pixel_line_2bp( encoder_t *p_enc, bs_t *s,
1646                                    subpicture_region_t *p_region,
1647                                    int i_line );
1648 static void encode_pixel_line_4bp( encoder_t *p_enc, bs_t *s,
1649                                    subpicture_region_t *p_region,
1650                                    int i_line );
1651 static void encode_pixel_data( encoder_t *p_enc, bs_t *s,
1652                                subpicture_region_t *p_region,
1653                                vlc_bool_t b_top )
1654 {
1655     unsigned int i_line;
1656
1657     /* Sanity check */
1658     if( p_region->fmt.i_chroma != VLC_FOURCC('Y','U','V','P') ) return;
1659
1660     /* Encode line by line */
1661     for( i_line = !b_top; i_line < p_region->fmt.i_visible_height;
1662          i_line += 2 )
1663     {
1664         switch( p_region->fmt.p_palette->i_entries )
1665         {
1666         case 4:
1667             bs_write( s, 8, 0x10 ); /* 2 bit/pixel code string */
1668             encode_pixel_line_2bp( p_enc, s, p_region, i_line );
1669             break;
1670
1671         case 16:
1672             bs_write( s, 8, 0x11 ); /* 4 bit/pixel code string */
1673             encode_pixel_line_4bp( p_enc, s, p_region, i_line );
1674             break;
1675
1676         default:
1677             msg_Err( p_enc, "subpicture palette (%i) not handled",
1678                      p_region->fmt.p_palette->i_entries );
1679             break;
1680         }
1681
1682         bs_write( s, 8, 0xf0 ); /* End of object line code */
1683     }
1684 }
1685
1686 static void encode_pixel_line_2bp( encoder_t *p_enc, bs_t *s,
1687                                    subpicture_region_t *p_region,
1688                                    int i_line )
1689 {
1690     unsigned int i, i_length = 0;
1691     int i_pitch = p_region->picture.p->i_pitch;
1692     uint8_t *p_data = &p_region->picture.p->p_pixels[ i_pitch * i_line ];
1693     int i_last_pixel = p_data[0];
1694
1695     for( i = 0; i <= p_region->fmt.i_visible_width; i++ )
1696     {
1697         if( i != p_region->fmt.i_visible_width &&
1698             p_data[i] == i_last_pixel && i_length != 284 )
1699         {
1700             i_length++;
1701             continue;
1702         }
1703
1704         if( i_length == 1 || i_length == 11 || i_length == 28 )
1705         {
1706             /* 2bit/pixel code */
1707             if( i_last_pixel ) bs_write( s, 2, i_last_pixel );
1708             else
1709             {
1710                 bs_write( s, 2, 0 );
1711                 bs_write( s, 1, 0 );
1712                 bs_write( s, 1, 1 ); /* pseudo color 0 */
1713             }
1714             i_length--;
1715         }
1716
1717         if( i_length == 2 )
1718         {
1719             if( i_last_pixel )
1720             {
1721                 bs_write( s, 2, i_last_pixel );
1722                 bs_write( s, 2, i_last_pixel );
1723             }
1724             else
1725             {
1726                 bs_write( s, 2, 0 );
1727                 bs_write( s, 1, 0 );
1728                 bs_write( s, 1, 0 );
1729                 bs_write( s, 2, 1 ); /* 2 * pseudo color 0 */
1730             }
1731         }
1732         else if( i_length > 2 )
1733         {
1734             bs_write( s, 2, 0 );
1735             if( i_length <= 10 )
1736             {
1737                 bs_write( s, 1, 1 );
1738                 bs_write( s, 3, i_length - 3 );
1739                 bs_write( s, 2, i_last_pixel );
1740             }
1741             else
1742             {
1743                 bs_write( s, 1, 0 );
1744                 bs_write( s, 1, 0 );
1745
1746                 if( i_length <= 27 )
1747                 {
1748                     bs_write( s, 2, 2 );
1749                     bs_write( s, 4, i_length - 12 );
1750                     bs_write( s, 2, i_last_pixel );
1751                 }
1752                 else
1753                 {
1754                     bs_write( s, 2, 3 );
1755                     bs_write( s, 8, i_length - 29 );
1756                     bs_write( s, 2, i_last_pixel );
1757                 }
1758             }
1759         }
1760
1761         if( i == p_region->fmt.i_visible_width ) break;
1762
1763         i_last_pixel = p_data[i];
1764         i_length = 1;
1765     }
1766
1767     /* Stop */
1768     bs_write( s, 2, 0 );
1769     bs_write( s, 1, 0 );
1770     bs_write( s, 1, 0 );
1771     bs_write( s, 2, 0 );
1772
1773     /* Stuffing */
1774     bs_align_0( s );
1775 }
1776
1777 static void encode_pixel_line_4bp( encoder_t *p_enc, bs_t *s,
1778                                    subpicture_region_t *p_region,
1779                                    int i_line )
1780 {
1781     unsigned int i, i_length = 0;
1782     int i_pitch = p_region->picture.p->i_pitch;
1783     uint8_t *p_data = &p_region->picture.p->p_pixels[ i_pitch * i_line ];
1784     int i_last_pixel = p_data[0];
1785
1786     for( i = 0; i <= p_region->fmt.i_visible_width; i++ )
1787     {
1788         if( i != p_region->fmt.i_visible_width &&
1789             p_data[i] == i_last_pixel && i_length != 1 )
1790         {
1791             i_length++;
1792             continue;
1793         }
1794
1795         if( i_length == 1 )
1796         {
1797             /* 4bit/pixel code */
1798             if( i_last_pixel ) bs_write( s, 4, i_last_pixel );
1799             else
1800             {
1801                 bs_write( s, 4, 0 );
1802                 bs_write( s, 1, 1 );
1803                 bs_write( s, 1, 1 );
1804                 bs_write( s, 2, 0 ); /* pseudo color 0 */
1805             }
1806         }
1807
1808         if( i == p_region->fmt.i_visible_width ) break;
1809
1810         i_last_pixel = p_data[i];
1811         i_length = 1;
1812     }
1813
1814     /* Stop */
1815     bs_write( s, 8, 0 );
1816
1817     /* Stuffing */
1818     bs_align_0( s );
1819 }