summaryrefslogtreecommitdiffstats
path: root/libhb/decvobsub.c
blob: fcada87d1f3f56b77c144ebd3b03cca5a95d4743 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
/* $Id: decsub.c,v 1.12 2005/04/14 17:37:54 titer Exp $

   This file is part of the HandBrake source code.
   Homepage: <http://handbrake.fr/>.
   It may be used under the terms of the GNU General Public License. */

/*
 * Decoder for DVD bitmap subtitles, also known as "VOB subtitles" within the HandBrake source code.
 * 
 * Input format of the subtitle packets is described here:
 *   http://sam.zoy.org/writings/dvd/subtitles/
 *
 * An auxiliary input is the color palette lookup table, in 'subtitle->palette'.
 * The demuxer implementation must fill out this table appropriately.
 * - In the case of a true DVD input, the palette is read from the IFO file.
 * - In the case of an MKV file input, the palette is read from the codec private data of the subtitle track.
 *
 * Output format of this decoder is PICTURESUB, which is:
 *   struct PictureSubPacket {
 *       uint8_t lum[pixelCount];       // Y
 *       uint8_t alpha[pixelCount];     // alpha (max = 16)
 *       uint8_t chromaU[pixelCount];   // Cb
 *       uint8_t chromaV[pixelCount];   // Cr
 *   }
 */

#include "hb.h"

struct hb_work_private_s
{
    hb_job_t    * job;

    hb_buffer_t * buf;
    int           size_sub;
    int           size_got;
    int           size_rle;
    int64_t       pts;
    int64_t       pts_start;
    int64_t       pts_stop;
    int           pts_forced;
    int           x;
    int           y;
    int           width;
    int           height;
    int           stream_id;

    int           offsets[2];
    uint8_t       lum[4];
    uint8_t       chromaU[4];
    uint8_t       chromaV[4];
    uint8_t       alpha[4];
};

static hb_buffer_t * Decode( hb_work_object_t * );

int decsubInit( hb_work_object_t * w, hb_job_t * job )
{
    hb_work_private_t * pv;

    pv              = calloc( 1, sizeof( hb_work_private_t ) );
    w->private_data = pv;

    pv->job = job;
    pv->pts = 0;
    
    // Warn if the input color palette is empty
    int paletteEmpty = 1;
    int i;
    for (i=0; i<16; i++)
    {
        if (w->subtitle->palette[i])
        {
            paletteEmpty = 0;
            break;
        }
    }
    if (paletteEmpty) {
        hb_log( "decvobsub: input color palette is empty; not demuxed properly?" );
    }

    return 0;
}

int decsubWork( hb_work_object_t * w, hb_buffer_t ** buf_in,
                hb_buffer_t ** buf_out )
{
    hb_work_private_t * pv = w->private_data;
    hb_buffer_t * in = *buf_in;
    int size_sub, size_rle;

    if ( in->size <= 0 )
    {
        /* EOF on input stream - send it downstream & say that we're done */
        *buf_out = in;
        *buf_in = NULL;
        return HB_WORK_DONE;
    }

    pv->stream_id = in->id;

    size_sub = ( in->data[0] << 8 ) | in->data[1];
    size_rle = ( in->data[2] << 8 ) | in->data[3];

    if( !pv->size_sub )
    {
        /* We are looking for the start of a new subtitle */
        if( size_sub && size_rle && size_sub > size_rle &&
            in->size <= size_sub )
        {
            /* Looks all right so far */
            pv->size_sub = size_sub;
            pv->size_rle = size_rle;

            pv->buf      = hb_buffer_init( 0xFFFF );
            memcpy( pv->buf->data, in->data, in->size );
            pv->buf->id = in->id;
            pv->buf->sequence = in->sequence;
            pv->size_got = in->size;
            if( in->start >= 0 )
            {
                pv->pts      = in->start;
            }
        }
    }
    else
    {
        /* We are waiting for the end of the current subtitle */
        if( in->size <= pv->size_sub - pv->size_got )
        {
            memcpy( pv->buf->data + pv->size_got, in->data, in->size );
            pv->buf->id = in->id;
            pv->buf->sequence = in->sequence;
            pv->size_got += in->size;
            if( in->start >= 0 )
            {
                pv->pts = in->start;
            }
        }
        else
        {
            // bad size, must have lost sync
            // force re-sync
            if ( pv->buf != NULL )
                hb_buffer_close( &pv->buf );
            pv->size_sub = 0;
        }

    }

    *buf_out = NULL;

    if( pv->size_sub && pv->size_sub == pv->size_got )
    {
        pv->buf->size = pv->size_sub;

        /* We got a complete subtitle, decode it */
        *buf_out = Decode( w );

        if( buf_out && *buf_out )
        {
            (*buf_out)->id = in->id;
            (*buf_out)->sequence = in->sequence;
        }

        /* Wait for the next one */
        pv->size_sub = 0;
        pv->size_got = 0;
        pv->size_rle = 0;

        // If we don't get a valid next timestamp, use the stop time
        // of the current sub as the start of the next.
        // This can happen if reader invalidates timestamps while 
        // waiting for an audio to update the SCR.
        pv->pts      = pv->pts_stop;
    }

    return HB_WORK_OK;
}

void decsubClose( hb_work_object_t * w )
{
    hb_work_private_t * pv = w->private_data;

    if ( pv->buf )
        hb_buffer_close( &pv->buf );
    free( w->private_data );
}

hb_work_object_t hb_decvobsub =
{
    WORK_DECVOBSUB,
    "VOBSUB decoder",
    decsubInit,
    decsubWork,
    decsubClose
};


/***********************************************************************
 * ParseControls
 ***********************************************************************
 * Get the start and end dates (relative to the PTS from the PES
 * header), the width and height of the subpicture and the colors and
 * alphas used in it
 **********************************************************************/
static void ParseControls( hb_work_object_t * w )
{
    hb_work_private_t * pv = w->private_data;
    hb_job_t * job = pv->job;
    hb_title_t * title = job->title;
    hb_subtitle_t * subtitle;
    uint8_t * buf = pv->buf->data;

    int i, n;
    int command;
    int date, next;

    pv->pts_start = -1;
    pv->pts_stop  = -1;
    pv->pts_forced  = 0;

    pv->alpha[3] = 0;
    pv->alpha[2] = 0;
    pv->alpha[1] = 0;
    pv->alpha[0] = 0;

    for( i = pv->size_rle; ; )
    {
        date = ( buf[i] << 8 ) | buf[i+1]; i += 2;
        next = ( buf[i] << 8 ) | buf[i+1]; i += 2;

        for( ;; )
        {
            command = buf[i++];

            /*
             * There are eight commands available for
             * Sub-Pictures. The first SP_DCSQ should contain, as a
             * minimum, SET_COLOR, SET_CONTR, SET_DAREA, and
             * SET_DSPXA
             */

            if( command == 0xFF ) // 0xFF - CMD_END - ends one SP_DCSQ
            {
                break;
            }

            switch( command )
            {
                case 0x00: // 0x00 - FSTA_DSP - Forced Start Display, no arguments
                    pv->pts_start = pv->pts + date * 1024;
                    pv->pts_forced = 1;

                    /*
                     * If we are doing a subtitle scan then note down
                     */
                    if( job->indepth_scan )
                    {
                        for( n=0; n < hb_list_count(title->list_subtitle); n++ )
                        {
                            subtitle = hb_list_item( title->list_subtitle, n);
                            if( pv->stream_id == subtitle->id ) {
                                /*
                                 * A hit, count it.
                                 */
                                subtitle->forced_hits++;
                            }
                        }
                    }
                    break;

                case 0x01: // 0x01 - STA_DSP - Start Display, no arguments
                    pv->pts_start = pv->pts + date * 1024;
                    pv->pts_forced  = 0;
                    break;

                case 0x02: // 0x02 - STP_DSP - Stop Display, no arguments
                    if(pv->pts_stop == -1)
                        pv->pts_stop = pv->pts + date * 1024;
                    break;

                case 0x03: // 0x03 - SET_COLOR - Set Colour indices
                {
                    /*
                     * SET_COLOR - provides four indices into the CLUT
                     * for the current PGC to associate with the four
                     * pixel values
                     */
                    int colors[4];
                    int j;

                    colors[0] = (buf[i+0]>>4)&0x0f;
                    colors[1] = (buf[i+0])&0x0f;
                    colors[2] = (buf[i+1]>>4)&0x0f;
                    colors[3] = (buf[i+1])&0x0f;

                    for( j = 0; j < 4; j++ )
                    {
                        /*
                         * Not sure what is happening here, in theory
                         * the palette is in YCbCr. And we want YUV.
                         *
                         * However it looks more like YCrCb (according
                         * to pgcedit). And the scalers for YCrCb don't
                         * work, but I get the right colours by doing
                         * no conversion.
                         */
                        uint32_t color = w->subtitle->palette[colors[j]];
                        uint8_t Cr, Cb, y;
                        y = (color>>16) & 0xff;
                        Cr = (color>>8) & 0xff;
                        Cb = (color) & 0xff;
                        pv->lum[3-j] = y;
                        pv->chromaU[3-j] = Cb;
                        pv->chromaV[3-j] = Cr;
                        /* hb_log("color[%d] y = %d, u = %d, v = %d",
                               3-j,
                               pv->lum[3-j],
                               pv->chromaU[3-j],
                               pv->chromaV[3-j]);
                        */
                    }
                    i += 2;
                    break;
                }
                case 0x04: // 0x04 - SET_CONTR - Set Contrast
                {
                    /*
                     * SET_CONTR - directly provides the four contrast
                     * (alpha blend) values to associate with the four
                     * pixel values
                     */
                    uint8_t    alpha[4];

                    alpha[3] = (buf[i+0]>>4)&0x0f;
                    alpha[2] = (buf[i+0])&0x0f;
                    alpha[1] = (buf[i+1]>>4)&0x0f;
                    alpha[0] = (buf[i+1])&0x0f;


                    int lastAlpha = pv->alpha[3] + pv->alpha[2] + pv->alpha[1] + pv->alpha[0];
                    int currAlpha = alpha[3] + alpha[2] + alpha[1] + alpha[0];

                    // fading-in, save the highest alpha value
                    if( currAlpha > lastAlpha )
                    {
                        pv->alpha[3] = alpha[3];
                        pv->alpha[2] = alpha[2];
                        pv->alpha[1] = alpha[1];
                        pv->alpha[0] = alpha[0];
                    }

                    // fading-out
                    if( currAlpha < lastAlpha && pv->pts_stop == -1 )
                    {
                        pv->pts_stop = pv->pts + date * 1024;
                    }

                    i += 2;
                    break;
                }
                case 0x05: // 0x05 - SET_DAREA - defines the display area
                {
                    pv->x     = (buf[i+0]<<4) | ((buf[i+1]>>4)&0x0f);
                    pv->width = (((buf[i+1]&0x0f)<<8)| buf[i+2]) - pv->x + 1;
                    pv->y     = (buf[i+3]<<4)| ((buf[i+4]>>4)&0x0f);
                    pv->height = (((buf[i+4]&0x0f)<<8)| buf[i+5]) - pv->y + 1;
                    i += 6;
                    break;
                }
                case 0x06: // 0x06 - SET_DSPXA - defines the pixel data addresses
                {
                    pv->offsets[0] = ( buf[i] << 8 ) | buf[i+1]; i += 2;
                    pv->offsets[1] = ( buf[i] << 8 ) | buf[i+1]; i += 2;
                    break;
                }
            }
        }



        if( i > next )
        {
            break;
        }
        i = next;
    }
    // Generate timestamps if they are not set
    if( pv->pts_start == -1 )
    {
        // Set pts to end of last sub if the start time is unknown.
        pv->pts_start = pv->pts;
    }
    if( pv->pts_stop == -1 )
    {
        // Set durtion to 10 sec if unknown.
        pv->pts_stop = pv->pts + 90000L * 10;
    }
}

/***********************************************************************
 * CropSubtitle
 ***********************************************************************
 * Given a raw decoded subtitle, detects transparent borders and
 * returns a cropped subtitle in a hb_buffer_t ready to be used by
 * the renderer, or NULL if the subtitle was completely transparent
 **********************************************************************/
static int LineIsTransparent( hb_work_object_t * w, uint8_t * p )
{
    hb_work_private_t * pv = w->private_data;
    int i;
    for( i = 0; i < pv->width; i++ )
    {
        if( p[i] )
        {
            return 0;
        }
    }
    return 1;
}
static int ColumnIsTransparent( hb_work_object_t * w, uint8_t * p )
{
    hb_work_private_t * pv = w->private_data;
    int i;
    for( i = 0; i < pv->height; i++ )
    {
        if( p[i*pv->width] )
        {
            return 0;
        }
    }
    return 1;
}
static hb_buffer_t * CropSubtitle( hb_work_object_t * w, uint8_t * raw )
{
    hb_work_private_t * pv = w->private_data;
    int i;
    int crop[4] = { -1,-1,-1,-1 };
    uint8_t * alpha;
    int realwidth, realheight;
    hb_buffer_t * buf;
    uint8_t * lum_in, * lum_out, * alpha_in, * alpha_out;
    uint8_t * u_in, * u_out, * v_in, * v_out;

    alpha = raw + pv->width * pv->height;

    /* Top */
    for( i = 0; i < pv->height; i++ )
    {
        if( !LineIsTransparent( w, &alpha[i*pv->width] ) )
        {
            crop[0] = i;
            break;
        }
    }

    if( crop[0] < 0 )
    {
        /* Empty subtitle */
        return NULL;
    }

    /* Bottom */
    for( i = pv->height - 1; i >= 0; i-- )
    {
        if( !LineIsTransparent( w, &alpha[i*pv->width] ) )
        {
            crop[1] = i;
            break;
        }
    }

    /* Left */
    for( i = 0; i < pv->width; i++ )
    {
        if( !ColumnIsTransparent( w, &alpha[i] ) )
        {
            crop[2] = i;
            break;
        }
    }

    /* Right */
    for( i = pv->width - 1; i >= 0; i-- )
    {
        if( !ColumnIsTransparent( w, &alpha[i] ) )
        {
            crop[3] = i;
            break;
        }
    }

    realwidth  = crop[3] - crop[2] + 1;
    realheight = crop[1] - crop[0] + 1;

    buf         = hb_buffer_init( realwidth * realheight * 4 );
    buf->start  = pv->pts_start;
    buf->stop   = pv->pts_stop;
    buf->x      = pv->x + crop[2];
    buf->y      = pv->y + crop[0];
    buf->width  = realwidth;
    buf->height = realheight;

    lum_in    = raw + crop[0] * pv->width + crop[2];
    alpha_in  = lum_in + pv->width * pv->height;
    u_in      = alpha_in + pv->width * pv->height;
    v_in      = u_in + pv->width * pv->height;

    lum_out   = buf->data;
    alpha_out = lum_out + realwidth * realheight;
    u_out     = alpha_out + realwidth * realheight;
    v_out     = u_out + realwidth * realheight;

    for( i = 0; i < realheight; i++ )
    {
        memcpy( lum_out, lum_in, realwidth );
        memcpy( alpha_out, alpha_in, realwidth );
        memcpy( u_out, u_in, realwidth );
        memcpy( v_out, v_in, realwidth );

        lum_in    += pv->width;
        alpha_in  += pv->width;
        u_in      += pv->width;
        v_in      += pv->width;

        lum_out   += realwidth;
        alpha_out += realwidth;
        u_out     += realwidth;
        v_out     += realwidth;
    }

    return buf;
}

static hb_buffer_t * Decode( hb_work_object_t * w )
{
    hb_work_private_t * pv = w->private_data;
    int code, line, col;
    int offsets[2];
    int * offset;
    hb_buffer_t * buf;
    uint8_t * buf_raw = NULL;
    hb_job_t * job = pv->job;

    /* Get infos about the subtitle */
    ParseControls( w );

    if( job->indepth_scan || ( w->subtitle->config.force && pv->pts_forced == 0 ) )
    {
        /*
         * Don't encode subtitles when doing a scan.
         *
         * When forcing subtitles, ignore all those that don't
         * have the forced flag set.
         */
        hb_buffer_close( &pv->buf );
        return NULL;
    }

    if (w->subtitle->config.dest == PASSTHRUSUB)
    {
        pv->buf->start  = pv->pts_start;
        pv->buf->stop   = pv->pts_stop;
        buf = pv->buf;
        pv->buf = NULL;
        return buf;
    }

    /* Do the actual decoding now */
    buf_raw = malloc( ( pv->width * pv->height ) * 4 );

#define GET_NEXT_NIBBLE code = ( code << 4 ) | ( ( ( *offset & 1 ) ? \
( pv->buf->data[((*offset)>>1)] & 0xF ) : ( pv->buf->data[((*offset)>>1)] >> 4 ) ) ); \
(*offset)++

    offsets[0] = pv->offsets[0] * 2;
    offsets[1] = pv->offsets[1] * 2;

    for( line = 0; line < pv->height; line++ )
    {
        /* Select even or odd field */
        offset = ( line & 1 ) ? &offsets[1] : &offsets[0];

        for( col = 0; col < pv->width; col += code >> 2 )
        {
            uint8_t * lum, * alpha,  * chromaU, * chromaV;

            code = 0;
            GET_NEXT_NIBBLE;
            if( code < 0x4 )
            {
                GET_NEXT_NIBBLE;
                if( code < 0x10 )
                {
                    GET_NEXT_NIBBLE;
                    if( code < 0x40 )
                    {
                        GET_NEXT_NIBBLE;
                        if( code < 0x100 )
                        {
                            /* End of line */
                            code |= ( pv->width - col ) << 2;
                        }
                    }
                }
            }

            lum   = buf_raw;
            alpha = lum + pv->width * pv->height;
            chromaU = alpha + pv->width * pv->height;
            chromaV = chromaU + pv->width * pv->height;

            memset( lum + line * pv->width + col,
                    pv->lum[code & 3], code >> 2 );
            memset( alpha + line * pv->width + col,
                    pv->alpha[code & 3], code >> 2 );
            memset( chromaU + line * pv->width + col,
                    pv->chromaU[code & 3], code >> 2 );
            memset( chromaV + line * pv->width + col,
                    pv->chromaV[code & 3], code >> 2 );
        }

        /* Byte-align */
        if( *offset & 1 )
        {
            (*offset)++;
        }
    }

    hb_buffer_close( &pv->buf );

    /* Crop subtitle (remove transparent borders) */
    buf = CropSubtitle( w, buf_raw );

    free( buf_raw );

    return buf;
}