libass.c 22.4 KB
Newer Older
1 2 3
/*****************************************************************************
 * SSA/ASS subtitle decoder using libass.
 *****************************************************************************
Jean-Baptiste Kempf's avatar
LGPL  
Jean-Baptiste Kempf committed
4
 * Copyright (C) 2008-2009 VLC authors and VideoLAN
5 6 7 8
 * $Id$
 *
 * Authors: Laurent Aimar <fenrir@videolan.org>
 *
Jean-Baptiste Kempf's avatar
LGPL  
Jean-Baptiste Kempf committed
9 10 11
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
12 13 14 15
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
Jean-Baptiste Kempf's avatar
LGPL  
Jean-Baptiste Kempf committed
16 17
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
18
 *
Jean-Baptiste Kempf's avatar
LGPL  
Jean-Baptiste Kempf committed
19 20 21
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
 *****************************************************************************/

/*****************************************************************************
 * Preamble
 *****************************************************************************/

#ifdef HAVE_CONFIG_H
#   include "config.h"
#endif

#include <string.h>
#include <limits.h>
#include <assert.h>
#include <math.h>

#include <vlc_common.h>
#include <vlc_plugin.h>
#include <vlc_codec.h>
#include <vlc_input.h>
41
#include <vlc_dialog.h>
42 43 44

#include <ass/ass.h>

45
#if defined(_WIN32)
46 47 48
#   include <vlc_charset.h>
#endif

49 50 51 52 53 54
/*****************************************************************************
 * Module descriptor
 *****************************************************************************/
static int  Create ( vlc_object_t * );
static void Destroy( vlc_object_t * );

55 56 57 58 59 60 61 62
vlc_module_begin ()
    set_shortname( N_("Subtitles (advanced)"))
    set_description( N_("Subtitle renderers using libass") )
    set_capability( "decoder", 100 )
    set_category( CAT_INPUT )
    set_subcategory( SUBCAT_INPUT_SCODEC )
    set_callbacks( Create, Destroy )
vlc_module_end ()
63 64 65 66 67

/*****************************************************************************
 * Local prototypes
 *****************************************************************************/
static subpicture_t *DecodeBlock( decoder_t *, block_t ** );
68
static void Flush( decoder_t * );
69 70 71 72

/* */
struct decoder_sys_t
{
73
    mtime_t        i_max_stop;
74

75 76 77
    /* The following fields of decoder_sys_t are shared between decoder and spu units */
    vlc_mutex_t    lock;
    int            i_refcount;
78 79

    /* */
80 81 82
    ASS_Library    *p_library;
    ASS_Renderer   *p_renderer;
    video_format_t fmt;
83 84

    /* */
85
    ASS_Track      *p_track;
86 87
};
static void DecSysRelease( decoder_sys_t *p_sys );
88
static void DecSysHold( decoder_sys_t *p_sys );
89

90 91 92 93 94 95 96 97 98 99 100 101
/* */
static int SubpictureValidate( subpicture_t *,
                               bool, const video_format_t *,
                               bool, const video_format_t *,
                               mtime_t );
static void SubpictureUpdate( subpicture_t *,
                              const video_format_t *,
                              const video_format_t *,
                              mtime_t );
static void SubpictureDestroy( subpicture_t * );

struct subpicture_updater_sys_t
102 103
{
    decoder_sys_t *p_dec_sys;
104 105
    void          *p_subs_data;
    int           i_subs_len;
Laurent Aimar's avatar
Laurent Aimar committed
106
    mtime_t       i_pts;
107 108

    ASS_Image     *p_img;
109 110 111 112 113 114 115 116 117 118
};

typedef struct
{
    int x0;
    int y0;
    int x1;
    int y1;
} rectangle_t;

119
static int BuildRegions( rectangle_t *p_region, int i_max_region, ASS_Image *p_img_list, int i_width, int i_height );
120
static void RegionDraw( subpicture_region_t *p_region, ASS_Image *p_img );
121 122 123 124

//#define DEBUG_REGION

/*****************************************************************************
125
 * Create: Open libass decoder.
126 127 128 129 130 131
 *****************************************************************************/
static int Create( vlc_object_t *p_this )
{
    decoder_t *p_dec = (decoder_t *)p_this;
    decoder_sys_t *p_sys;

132
    if( p_dec->fmt_in.i_codec != VLC_CODEC_SSA )
133 134 135
        return VLC_EGENERIC;

    p_dec->pf_decode_sub = DecodeBlock;
136
    p_dec->pf_flush      = Flush;
137 138 139 140 141 142

    p_dec->p_sys = p_sys = malloc( sizeof( decoder_sys_t ) );
    if( !p_sys )
        return VLC_ENOMEM;

    /* */
143 144 145
    vlc_mutex_init( &p_sys->lock );
    p_sys->i_refcount = 1;
    memset( &p_sys->fmt, 0, sizeof(p_sys->fmt) );
146
    p_sys->i_max_stop = VLC_TS_INVALID;
147 148 149 150 151 152 153
    p_sys->p_library  = NULL;
    p_sys->p_renderer = NULL;
    p_sys->p_track    = NULL;

    /* Create libass library */
    ASS_Library *p_library = p_sys->p_library = ass_library_init();
    if( !p_library )
154
    {
155 156
        msg_Warn( p_dec, "Libass library creation failed" );
        DecSysRelease( p_sys );
157 158
        return VLC_EGENERIC;
    }
159 160 161 162 163 164 165 166 167 168 169 170 171

    /* load attachments */
    input_attachment_t  **pp_attachments;
    int                   i_attachments;
    if( decoder_GetInputAttachments( p_dec, &pp_attachments, &i_attachments ))
    {
        i_attachments = 0;
        pp_attachments = NULL;
    }
    for( int k = 0; k < i_attachments; k++ )
    {
        input_attachment_t *p_attach = pp_attachments[k];

172 173 174
        bool found = false;

        /* Check mimetype*/
175
        if( !strcasecmp( p_attach->psz_mime, "application/x-truetype-font" ) )
176 177 178 179 180 181 182 183 184 185 186
            found = true;
        /* Then extension */
        else if( !found && strlen( p_attach->psz_name ) > 4 )
        {
            char *ext = p_attach->psz_name + strlen( p_attach->psz_name ) - 4;

            if( !strcasecmp( ext, ".ttf" ) || !strcasecmp( ext, ".otf" ) || !strcasecmp( ext, ".ttc" ) )
                found = true;
        }

        if( found )
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
        {
            msg_Dbg( p_dec, "adding embedded font %s", p_attach->psz_name );

            ass_add_font( p_sys->p_library, p_attach->psz_name, p_attach->p_data, p_attach->i_data );
        }
        vlc_input_attachment_Delete( p_attach );
    }
    free( pp_attachments );

    ass_set_extract_fonts( p_library, true );
    ass_set_style_overrides( p_library, NULL );

    /* Create the renderer */
    ASS_Renderer *p_renderer = p_sys->p_renderer = ass_renderer_init( p_library );
    if( !p_renderer )
    {
        msg_Warn( p_dec, "Libass renderer creation failed" );
        DecSysRelease( p_sys );
        return VLC_EGENERIC;
    }

    ass_set_use_margins( p_renderer, false);
    //if( false )
    //    ass_set_margins( p_renderer, int t, int b, int l, int r);
    ass_set_hinting( p_renderer, ASS_HINTING_LIGHT );
    ass_set_font_scale( p_renderer, 1.0 );
    ass_set_line_spacing( p_renderer, 0.0 );

215 216 217
#if defined( __ANDROID__ )
    const char *psz_font = "/system/fonts/DroidSans-Bold.ttf";
    const char *psz_family = "Droid Sans Bold";
218 219 220
#elif defined( __APPLE__ )
    const char *psz_font = NULL; /* We don't ship a default font with VLC */
    const char *psz_family = "Helvetica Neue"; /* Use HN if we can't find anything more suitable - Arial is not on all Apple platforms */
221
#else
222 223
    const char *psz_font = NULL; /* We don't ship a default font with VLC */
    const char *psz_family = "Arial"; /* Use Arial if we can't find anything more suitable */
224
#endif
225 226

#ifdef HAVE_FONTCONFIG
227
#if defined(_WIN32)
Thomas Guillem's avatar
Thomas Guillem committed
228
    vlc_dialog_id *p_dialog_id =
Thomas Guillem's avatar
Thomas Guillem committed
229 230 231 232
        vlc_dialog_display_progress( p_dec, true, 0.0, NULL,
                                    _("Building font cache"),
                                    _( "Please wait while your font cache is rebuilt.\n"
                                    "This should take less than a minute." ) );
233
#endif
234
    ass_set_fonts( p_renderer, psz_font, psz_family, 1, NULL, 1 );  // setup default font/family
235
#if defined(_WIN32)
Thomas Guillem's avatar
Thomas Guillem committed
236 237
    if( p_dialog_id != 0 )
        vlc_dialog_release( p_dec, p_dialog_id );
238 239
#endif
#else
240
    ass_set_fonts( p_renderer, psz_font, psz_family, 1, NULL, 1 );
241
#endif
242 243

    /* Add a track */
244
    ASS_Track *p_track = p_sys->p_track = ass_new_track( p_sys->p_library );
245 246 247 248 249
    if( !p_track )
    {
        DecSysRelease( p_sys );
        return VLC_EGENERIC;
    }
250 251
    ass_process_codec_private( p_track, p_dec->fmt_in.p_extra, p_dec->fmt_in.i_extra );

252
    p_dec->fmt_out.i_cat = SPU_ES;
253
    p_dec->fmt_out.i_codec = VLC_CODEC_RGBA;
254

255 256 257 258 259 260 261 262 263 264 265 266 267
    return VLC_SUCCESS;
}

/*****************************************************************************
 * Destroy: finish
 *****************************************************************************/
static void Destroy( vlc_object_t *p_this )
{
    decoder_t *p_dec = (decoder_t *)p_this;

    DecSysRelease( p_dec->p_sys );
}

268
static void DecSysHold( decoder_sys_t *p_sys )
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
{
    vlc_mutex_lock( &p_sys->lock );
    p_sys->i_refcount++;
    vlc_mutex_unlock( &p_sys->lock );
}
static void DecSysRelease( decoder_sys_t *p_sys )
{
    /* */
    vlc_mutex_lock( &p_sys->lock );
    p_sys->i_refcount--;
    if( p_sys->i_refcount > 0 )
    {
        vlc_mutex_unlock( &p_sys->lock );
        return;
    }
    vlc_mutex_unlock( &p_sys->lock );
    vlc_mutex_destroy( &p_sys->lock );

287 288
    if( p_sys->p_track )
        ass_free_track( p_sys->p_track );
289 290 291 292
    if( p_sys->p_renderer )
        ass_renderer_done( p_sys->p_renderer );
    if( p_sys->p_library )
        ass_library_done( p_sys->p_library );
293 294 295 296

    free( p_sys );
}

297 298 299 300 301 302 303 304 305 306
/*****************************************************************************
 * Flush:
 *****************************************************************************/
static void Flush( decoder_t *p_dec )
{
    decoder_sys_t *p_sys = p_dec->p_sys;

    p_sys->i_max_stop = VLC_TS_INVALID;
}

307
/****************************************************************************
308
 * DecodeBlock:
309 310 311 312 313 314 315 316 317 318 319 320
 ****************************************************************************/
static subpicture_t *DecodeBlock( decoder_t *p_dec, block_t **pp_block )
{
    decoder_sys_t *p_sys = p_dec->p_sys;

    subpicture_t *p_spu = NULL;
    block_t *p_block;

    if( !pp_block || *pp_block == NULL )
        return NULL;

    p_block = *pp_block;
321 322 323
    *pp_block = NULL;

    if( p_block->i_flags & BLOCK_FLAG_CORRUPTED )
324
    {
325
        Flush( p_dec );
326 327 328
        block_Release( p_block );
        return NULL;
    }
329 330 331 332 333 334 335

    if( p_block->i_buffer == 0 || p_block->p_buffer[0] == '\0' )
    {
        block_Release( p_block );
        return NULL;
    }

336 337
    subpicture_updater_sys_t *p_spu_sys = malloc( sizeof(*p_spu_sys) );
    if( !p_spu_sys )
338 339 340 341 342
    {
        block_Release( p_block );
        return NULL;
    }

343 344 345 346 347 348 349 350
    subpicture_updater_t updater = {
        .pf_validate = SubpictureValidate,
        .pf_update   = SubpictureUpdate,
        .pf_destroy  = SubpictureDestroy,
        .p_sys       = p_spu_sys,
    };
    p_spu = decoder_NewSubpicture( p_dec, &updater );
    if( !p_spu )
351
    {
352 353
        msg_Warn( p_dec, "can't get spu buffer" );
        free( p_spu_sys );
354 355 356 357
        block_Release( p_block );
        return NULL;
    }

358 359 360 361 362 363
    p_spu_sys->p_img = NULL;
    p_spu_sys->p_dec_sys = p_sys;
    p_spu_sys->i_subs_len = p_block->i_buffer;
    p_spu_sys->p_subs_data = malloc( p_block->i_buffer );
    p_spu_sys->i_pts = p_block->i_pts;
    if( !p_spu_sys->p_subs_data )
364
    {
365
        subpicture_Delete( p_spu );
366 367 368
        block_Release( p_block );
        return NULL;
    }
369
    memcpy( p_spu_sys->p_subs_data, p_block->p_buffer,
370 371 372
            p_block->i_buffer );

    p_spu->i_start = p_block->i_pts;
373
    p_spu->i_stop = __MAX( p_sys->i_max_stop, p_block->i_pts + p_block->i_length );
374 375 376
    p_spu->b_ephemer = true;
    p_spu->b_absolute = true;

377 378
    p_sys->i_max_stop = p_spu->i_stop;

379
    vlc_mutex_lock( &p_sys->lock );
380 381
    if( p_sys->p_track )
    {
382
        ass_process_chunk( p_sys->p_track, p_spu_sys->p_subs_data, p_spu_sys->i_subs_len,
383
                           p_block->i_pts / 1000, p_block->i_length / 1000 );
384
    }
385
    vlc_mutex_unlock( &p_sys->lock );
386

387
    DecSysHold( p_sys ); /* Keep a reference for the returned subpicture */
388 389 390 391 392 393

    block_Release( p_block );

    return p_spu;
}

394 395 396
/****************************************************************************
 *
 ****************************************************************************/
397 398 399 400
static int SubpictureValidate( subpicture_t *p_subpic,
                               bool b_fmt_src, const video_format_t *p_fmt_src,
                               bool b_fmt_dst, const video_format_t *p_fmt_dst,
                               mtime_t i_ts )
401
{
402
    decoder_sys_t *p_sys = p_subpic->updater.p_sys->p_dec_sys;
403

404
    vlc_mutex_lock( &p_sys->lock );
405

406 407
    video_format_t fmt = *p_fmt_dst;
    fmt.i_chroma         = VLC_CODEC_RGBA;
408
    fmt.i_bits_per_pixel = 0;
409
    fmt.i_x_offset       = 0;
410 411
    fmt.i_y_offset       = 0;
    if( b_fmt_src || b_fmt_dst )
412
    {
413 414 415
        ass_set_frame_size( p_sys->p_renderer, fmt.i_visible_width, fmt.i_visible_height );
        const double src_ratio = (double)p_fmt_src->i_visible_width / p_fmt_src->i_visible_height;
        const double dst_ratio = (double)p_fmt_dst->i_visible_width / p_fmt_dst->i_visible_height;
416 417
        ass_set_aspect_ratio( p_sys->p_renderer, dst_ratio / src_ratio, 1 );
        p_sys->fmt = fmt;
418 419 420
    }

    /* */
421
    const mtime_t i_stream_date = p_subpic->updater.p_sys->i_pts + (i_ts - p_subpic->i_start);
422
    int i_changed;
423
    ASS_Image *p_img = ass_render_frame( p_sys->p_renderer, p_sys->p_track,
424
                                         i_stream_date/1000, &i_changed );
425

426
    if( !i_changed && !b_fmt_src && !b_fmt_dst &&
427
        (p_img != NULL) == (p_subpic->p_region != NULL) )
428
    {
429
        vlc_mutex_unlock( &p_sys->lock );
430
        return VLC_SUCCESS;
431
    }
432 433 434 435 436 437 438 439 440 441 442
    p_subpic->updater.p_sys->p_img = p_img;

    /* The lock is released by SubpictureUpdate */
    return VLC_EGENERIC;
}

static void SubpictureUpdate( subpicture_t *p_subpic,
                              const video_format_t *p_fmt_src,
                              const video_format_t *p_fmt_dst,
                              mtime_t i_ts )
{
443 444
    VLC_UNUSED( p_fmt_src ); VLC_UNUSED( p_fmt_dst ); VLC_UNUSED( i_ts );

445 446
    decoder_sys_t *p_sys = p_subpic->updater.p_sys->p_dec_sys;

447
    video_format_t fmt = p_sys->fmt;
448
    ASS_Image *p_img = p_subpic->updater.p_sys->p_img;
449 450

    /* */
451 452
    p_subpic->i_original_picture_height = fmt.i_visible_height;
    p_subpic->i_original_picture_width = fmt.i_visible_width;
453

454
    /* XXX to improve efficiency we merge regions that are close minimizing
455 456 457 458 459 460 461
     * the lost surface.
     * libass tends to create a lot of small regions and thus spu engine
     * reinstanciate a lot the scaler, and as we do not support subpel blending
     * it looks ugly (text unaligned).
     */
    const int i_max_region = 4;
    rectangle_t region[i_max_region];
462
    const int i_region = BuildRegions( region, i_max_region, p_img, fmt.i_width, fmt.i_height );
463 464 465

    if( i_region <= 0 )
    {
466
        vlc_mutex_unlock( &p_sys->lock );
467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
        return;
    }

    /* Allocate the regions and draw them */
    subpicture_region_t **pp_region_last = &p_subpic->p_region;

    for( int i = 0; i < i_region; i++ )
    {
        subpicture_region_t *r;
        video_format_t fmt_region;

        /* */
        fmt_region = fmt;
        fmt_region.i_width =
        fmt_region.i_visible_width  = region[i].x1 - region[i].x0;
        fmt_region.i_height =
        fmt_region.i_visible_height = region[i].y1 - region[i].y0;

485
        r = subpicture_region_New( &fmt_region );
486 487 488 489 490 491 492 493 494 495 496 497 498
        if( !r )
            break;
        r->i_x = region[i].x0;
        r->i_y = region[i].y0;
        r->i_align = SUBPICTURE_ALIGN_TOP | SUBPICTURE_ALIGN_LEFT;

        /* */
        RegionDraw( r, p_img );

        /* */
        *pp_region_last = r;
        pp_region_last = &r->p_next;
    }
499
    vlc_mutex_unlock( &p_sys->lock );
500 501 502 503 504 505 506 507 508

}
static void SubpictureDestroy( subpicture_t *p_subpic )
{
    subpicture_updater_sys_t *p_sys = p_subpic->updater.p_sys;

    DecSysRelease( p_sys->p_dec_sys );
    free( p_sys->p_subs_data );
    free( p_sys );
509 510 511 512 513 514 515
}

static rectangle_t r_create( int x0, int y0, int x1, int y1 )
{
    rectangle_t r = { x0, y0, x1, y1 };
    return r;
}
516
static rectangle_t r_img( const ASS_Image *p_img )
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536
{
    return r_create( p_img->dst_x, p_img->dst_y, p_img->dst_x+p_img->w, p_img->dst_y+p_img->h );
}
static void r_add( rectangle_t *r, const rectangle_t *n )
{
    r->x0 = __MIN( r->x0, n->x0 );
    r->y0 = __MIN( r->y0, n->y0 );
    r->x1 = __MAX( r->x1, n->x1 );
    r->y1 = __MAX( r->y1, n->y1 );
}
static int r_surface( const rectangle_t *r )
{
    return (r->x1-r->x0) * (r->y1-r->y0);
}
static bool r_overlap( const rectangle_t *a, const rectangle_t *b, int i_dx, int i_dy )
{
    return  __MAX(a->x0-i_dx, b->x0) < __MIN( a->x1+i_dx, b->x1 ) &&
            __MAX(a->y0-i_dy, b->y0) < __MIN( a->y1+i_dy, b->y1 );
}

537
static int BuildRegions( rectangle_t *p_region, int i_max_region, ASS_Image *p_img_list, int i_width, int i_height )
538
{
539
    ASS_Image *p_tmp;
540 541
    int i_count;

542
#ifdef DEBUG_REGION
543
    int64_t i_ck_start = mdate();
544
#endif
545 546

    for( p_tmp = p_img_list, i_count = 0; p_tmp != NULL; p_tmp = p_tmp->next )
547 548
        if( p_tmp->w > 0 && p_tmp->h > 0 )
            i_count++;
549 550 551
    if( i_count <= 0 )
        return 0;

552
    ASS_Image **pp_img = calloc( i_count, sizeof(*pp_img) );
553 554 555
    if( !pp_img )
        return 0;

556 557 558
    for( p_tmp = p_img_list, i_count = 0; p_tmp != NULL; p_tmp = p_tmp->next )
        if( p_tmp->w > 0 && p_tmp->h > 0 )
            pp_img[i_count++] = p_tmp;
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

    /* */
    const int i_w_inc = __MAX( ( i_width + 49 ) / 50, 32 );
    const int i_h_inc = __MAX( ( i_height + 99 ) / 100, 32 );
    int i_maxh = i_w_inc;
    int i_maxw = i_h_inc;
    int i_region;
    rectangle_t region[i_max_region+1];

    i_region = 0;
    for( int i_used = 0; i_used < i_count; )
    {
        int n;
        for( n = 0; n < i_count; n++ )
        {
            if( pp_img[n] )
                break;
        }
        assert( i_region < i_max_region + 1 );
        region[i_region++] = r_img( pp_img[n] );
        pp_img[n] = NULL; i_used++;

        bool b_ok;
        do {
            b_ok = false;
            for( n = 0; n < i_count; n++ )
            {
586
                ASS_Image *p_img = pp_img[n];
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
                if( !p_img )
                    continue;
                rectangle_t r = r_img( p_img );

                int k;
                int i_best = -1;
                int i_best_s = INT_MAX;
                for( k = 0; k < i_region; k++ )
                {
                    if( !r_overlap( &region[k], &r, i_maxw, i_maxh ) )
                        continue;
                    int s = r_surface( &r );
                    if( s < i_best_s )
                    {
                        i_best_s = s;
                        i_best = k;
                    }
                }
                if( i_best >= 0 )
                {
                    r_add( &region[i_best], &r );
                    pp_img[n] = NULL; i_used++;
                    b_ok = true;
                }
            }
        } while( b_ok );

        if( i_region > i_max_region )
        {
            int i_best_i = -1;
            int i_best_j = -1;
            int i_best_ds = INT_MAX;

            /* merge best */
            for( int i = 0; i < i_region; i++ )
            {
                for( int j = i+1; j < i_region; j++ )
                {
                    rectangle_t n = region[i];
                    r_add( &n, &region[j] );
                    int ds = r_surface( &n ) - r_surface( &region[i] ) - r_surface( &region[j] );

                    if( ds < i_best_ds )
                    {
                        i_best_i = i;
                        i_best_j = j;
                        i_best_ds = ds;
                    }
                }
            }
637
#ifdef DEBUG_REGION
638
            msg_Err( p_spu, "Merging %d and %d", i_best_i, i_best_j );
639
#endif
640 641 642
            if( i_best_j >= 0 && i_best_i >= 0 )
            {
                r_add( &region[i_best_i], &region[i_best_j] );
643

644 645 646 647
                if( i_best_j+1 < i_region )
                    memmove( &region[i_best_j], &region[i_best_j+1], sizeof(*region) * ( i_region - (i_best_j+1)  ) );
                i_region--;
            }
648 649 650 651 652 653 654
        }
    }

    /* */
    for( int n = 0; n < i_region; n++ )
        p_region[n] = region[n];

655
#ifdef DEBUG_REGION
656 657
    int64_t i_ck_time = mdate() - i_ck_start;
    msg_Err( p_spu, "ASS: %d objects merged into %d region in %d micros", i_count, i_region, (int)(i_ck_time) );
658
#endif
659

660 661
    free( pp_img );

662 663 664
    return i_region;
}

665
static void RegionDraw( subpicture_region_t *p_region, ASS_Image *p_img )
666
{
667
    const plane_t *p = &p_region->p_picture->p[0];
668 669 670 671 672 673 674 675 676 677 678 679
    const int i_x = p_region->i_x;
    const int i_y = p_region->i_y;
    const int i_width  = p_region->fmt.i_width;
    const int i_height = p_region->fmt.i_height;

    memset( p->p_pixels, 0x00, p->i_pitch * p->i_lines );
    for( ; p_img != NULL; p_img = p_img->next )
    {
        if( p_img->dst_x < i_x || p_img->dst_x + p_img->w > i_x + i_width ||
            p_img->dst_y < i_y || p_img->dst_y + p_img->h > i_y + i_height )
            continue;

680 681 682 683
        const unsigned r = (p_img->color >> 24)&0xff;
        const unsigned g = (p_img->color >> 16)&0xff;
        const unsigned b = (p_img->color >>  8)&0xff;
        const unsigned a = (p_img->color      )&0xff;
684 685 686 687 688 689
        int x, y;

        for( y = 0; y < p_img->h; y++ )
        {
            for( x = 0; x < p_img->w; x++ )
            {
690 691
                const unsigned alpha = p_img->bitmap[y*p_img->stride+x];
                const unsigned an = (255 - a) * alpha / 255;
692 693

                uint8_t *p_rgba = &p->p_pixels[(y+p_img->dst_y-i_y) * p->i_pitch + 4 * (x+p_img->dst_x-i_x)];
694
                const unsigned ao = p_rgba[3];
695 696

                /* Native endianness, but RGBA ordering */
697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714
                if( ao == 0 )
                {
                    /* Optimized but the else{} will produce the same result */
                    p_rgba[0] = r;
                    p_rgba[1] = g;
                    p_rgba[2] = b;
                    p_rgba[3] = an;
                }
                else
                {
                    p_rgba[3] = 255 - ( 255 - p_rgba[3] ) * ( 255 - an ) / 255;
                    if( p_rgba[3] != 0 )
                    {
                        p_rgba[0] = ( p_rgba[0] * ao * (255-an) / 255 + r * an ) / p_rgba[3];
                        p_rgba[1] = ( p_rgba[1] * ao * (255-an) / 255 + g * an ) / p_rgba[3];
                        p_rgba[2] = ( p_rgba[2] * ao * (255-an) / 255 + b * an ) / p_rgba[3];
                    }
                }
715 716 717 718 719 720 721 722 723 724 725 726 727 728 729
            }
        }
    }

#ifdef DEBUG_REGION
    /* XXX Draw a box for debug */
#define P(x,y) ((uint32_t*)&p->p_pixels[(y)*p->i_pitch + 4*(x)])
    for( int y = 0; y < p->i_lines; y++ )
        *P(0,y) = *P(p->i_visible_pitch/4-1,y) = 0xff000000;
    for( int x = 0; x < p->i_visible_pitch; x++ )
        *P(x/4,0) = *P(x/4,p->i_visible_lines-1) = 0xff000000;
#undef P
#endif
}