]> git.sesse.net Git - vlc/blob - src/video_output/vout_subpictures.c
Render subpictures in the right order to improve overlap support.
[vlc] / src / video_output / vout_subpictures.c
1 /*****************************************************************************
2  * vout_subpictures.c : subpicture management functions
3  *****************************************************************************
4  * Copyright (C) 2000-2007 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Vincent Seguin <seguin@via.ecp.fr>
8  *          Samuel Hocevar <sam@zoy.org>
9  *          Gildas Bazin <gbazin@videolan.org>
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
24  *****************************************************************************/
25
26 /*****************************************************************************
27  * Preamble
28  *****************************************************************************/
29 #ifdef HAVE_CONFIG_H
30 # include "config.h"
31 #endif
32
33 #include <vlc_common.h>
34 #include <vlc_vout.h>
35 #include <vlc_block.h>
36 #include <vlc_filter.h>
37 #include <vlc_osd.h>
38 #include "../libvlc.h"
39
40 #include <assert.h>
41 #include <limits.h>
42
43 /*****************************************************************************
44  * Local prototypes
45  *****************************************************************************/
46 static void UpdateSPU   ( spu_t *, vlc_object_t * );
47 static int  CropCallback( vlc_object_t *, char const *,
48                           vlc_value_t, vlc_value_t, void * );
49
50 static int spu_vaControlDefault( spu_t *, int, va_list );
51
52 static subpicture_t *sub_new_buffer( filter_t * );
53 static void sub_del_buffer( filter_t *, subpicture_t * );
54 static subpicture_t *spu_new_buffer( filter_t * );
55 static void spu_del_buffer( filter_t *, subpicture_t * );
56 static picture_t *spu_new_video_buffer( filter_t * );
57 static void spu_del_video_buffer( filter_t *, picture_t * );
58
59 static int spu_ParseChain( spu_t * );
60 static int SubFilterCallback( vlc_object_t *, char const *,
61                               vlc_value_t, vlc_value_t, void * );
62
63 static int SubFilterAllocationInit( filter_t *, void * );
64 static void SubFilterAllocationClean( filter_t * );
65 struct filter_owner_sys_t
66 {
67     spu_t *p_spu;
68     int i_channel;
69 };
70
71 #define SCALE_UNIT (1000)
72
73 /* */
74 static void SpuRenderCreateAndLoadText( spu_t *p_spu );
75 static void SpuRenderCreateAndLoadScale( spu_t *p_spu );
76 static void FilterRelease( filter_t *p_filter );
77
78 /**
79  * Creates the subpicture unit
80  *
81  * \param p_this the parent object which creates the subpicture unit
82  */
83 spu_t *__spu_Create( vlc_object_t *p_this )
84 {
85     int i_index;
86     spu_t *p_spu = vlc_custom_create( p_this, sizeof( spu_t ),
87                                       VLC_OBJECT_GENERIC, "subpicture" );
88     /* */
89     p_spu->i_subpicture_order = 1;
90     for( i_index = 0; i_index < VOUT_MAX_SUBPICTURES; i_index++)
91     {
92         p_spu->p_subpicture[i_index].i_status = FREE_SUBPICTURE;
93     }
94
95     p_spu->p_blend = NULL;
96     p_spu->p_text = NULL;
97     p_spu->p_scale = NULL;
98     p_spu->p_scale_yuvp = NULL;
99     p_spu->pf_control = spu_vaControlDefault;
100
101     /* Register the default subpicture channel */
102     p_spu->i_channel = 2;
103
104     vlc_mutex_init( &p_spu->subpicture_lock );
105
106     vlc_object_attach( p_spu, p_this );
107
108     p_spu->p_chain = filter_chain_New( p_spu, "sub filter", false,
109                                        SubFilterAllocationInit,
110                                        SubFilterAllocationClean,
111                                        p_spu );
112
113     /* Load text and scale module */
114     SpuRenderCreateAndLoadText( p_spu );
115     SpuRenderCreateAndLoadScale( p_spu );
116
117     return p_spu;
118 }
119
120 /**
121  * Initialise the subpicture unit
122  *
123  * \param p_spu the subpicture unit object
124  */
125 int spu_Init( spu_t *p_spu )
126 {
127     vlc_value_t val;
128
129     /* If the user requested a sub margin, we force the position. */
130     var_Create( p_spu, "sub-margin", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
131     var_Get( p_spu, "sub-margin", &val );
132     p_spu->i_margin = val.i_int;
133
134     var_Create( p_spu, "sub-filter", VLC_VAR_STRING | VLC_VAR_DOINHERIT );
135     var_AddCallback( p_spu, "sub-filter", SubFilterCallback, p_spu );
136
137     spu_ParseChain( p_spu );
138
139     return VLC_SUCCESS;
140 }
141
142 int spu_ParseChain( spu_t *p_spu )
143 {
144     char *psz_parser = var_GetString( p_spu, "sub-filter" );
145     if( filter_chain_AppendFromString( p_spu->p_chain, psz_parser ) < 0 )
146     {
147         free( psz_parser );
148         return VLC_EGENERIC;
149     }
150
151     free( psz_parser );
152     return VLC_SUCCESS;
153 }
154
155 /**
156  * Destroy the subpicture unit
157  *
158  * \param p_this the parent object which destroys the subpicture unit
159  */
160 void spu_Destroy( spu_t *p_spu )
161 {
162     int i_index;
163
164     /* Destroy all remaining subpictures */
165     for( i_index = 0; i_index < VOUT_MAX_SUBPICTURES; i_index++ )
166     {
167         if( p_spu->p_subpicture[i_index].i_status != FREE_SUBPICTURE )
168         {
169             spu_DestroySubpicture( p_spu, &p_spu->p_subpicture[i_index] );
170         }
171     }
172
173     if( p_spu->p_blend )
174         FilterRelease( p_spu->p_blend );
175
176     if( p_spu->p_text )
177         FilterRelease( p_spu->p_text );
178
179     if( p_spu->p_scale_yuvp )
180         FilterRelease( p_spu->p_scale_yuvp );
181
182     if( p_spu->p_scale )
183         FilterRelease( p_spu->p_scale );
184
185     filter_chain_Delete( p_spu->p_chain );
186
187     vlc_mutex_destroy( &p_spu->subpicture_lock );
188     vlc_object_release( p_spu );
189 }
190
191 /**
192  * Attach/Detach the SPU from any input
193  *
194  * \param p_this the object in which to destroy the subpicture unit
195  * \param b_attach to select attach or detach
196  */
197 void spu_Attach( spu_t *p_spu, vlc_object_t *p_this, bool b_attach )
198 {
199     vlc_object_t *p_input;
200
201     p_input = vlc_object_find( p_this, VLC_OBJECT_INPUT, FIND_PARENT );
202     if( !p_input ) return;
203
204     if( b_attach )
205     {
206         UpdateSPU( p_spu, VLC_OBJECT(p_input) );
207         var_AddCallback( p_input, "highlight", CropCallback, p_spu );
208         vlc_object_release( p_input );
209     }
210     else
211     {
212         /* Delete callback */
213         var_DelCallback( p_input, "highlight", CropCallback, p_spu );
214         vlc_object_release( p_input );
215     }
216 }
217
218
219 /* */
220 static void RegionPictureRelease( picture_t *p_picture )
221 {
222     if( --p_picture->i_refcount > 0 )
223         return;
224
225     assert( p_picture->i_refcount == 0 );
226     free( p_picture->p_q );
227     free( p_picture->p_data_orig );
228     free( p_picture->p_sys );
229 }
230
231 /**
232  * Create a subpicture region
233  *
234  * \param p_this vlc_object_t
235  * \param p_fmt the format that this subpicture region should have
236  */
237 subpicture_region_t *__spu_CreateRegion( vlc_object_t *p_this,
238                                          video_format_t *p_fmt )
239 {
240     subpicture_region_t *p_region = calloc( 1, sizeof(*p_region ) );
241     if( !p_region )
242         return NULL;
243
244     /* FIXME is that *really* wanted? */
245     if( p_fmt->i_chroma == VLC_FOURCC('Y','U','V','P') )
246         p_fmt->p_palette = calloc( 1, sizeof(video_palette_t) );
247     else
248         p_fmt->p_palette = NULL;    /* XXX and that above all? */
249
250     p_region->fmt = *p_fmt;
251     p_region->i_alpha = 0xff;
252     p_region->p_next = NULL;
253     p_region->p_cache = NULL;
254     p_region->psz_text = NULL;
255     p_region->p_style = NULL;
256
257     if( p_fmt->i_chroma == VLC_FOURCC('T','E','X','T') )
258         return p_region;
259
260     vout_AllocatePicture( p_this, &p_region->picture, p_fmt->i_chroma,
261                           p_fmt->i_width, p_fmt->i_height, p_fmt->i_aspect );
262
263     if( !p_region->picture.i_planes )
264     {
265         free( p_fmt->p_palette );
266         free( p_region );
267         return NULL;
268     }
269
270     p_region->picture.i_refcount = 1;
271     p_region->picture.pf_release = RegionPictureRelease;
272
273     return p_region;
274 }
275
276 /**
277  * Destroy a subpicture region
278  *
279  * \param p_this vlc_object_t
280  * \param p_region the subpicture region to destroy
281  */
282 void __spu_DestroyRegion( vlc_object_t *p_this, subpicture_region_t *p_region )
283 {
284     if( !p_region )
285         return;
286
287     picture_Release( &p_region->picture );
288
289     free( p_region->fmt.p_palette );
290     if( p_region->p_cache )
291         __spu_DestroyRegion( p_this, p_region->p_cache );
292
293     free( p_region->psz_text );
294     free( p_region->psz_html );
295     //free( p_region->p_style ); FIXME --fenrir plugin does not allocate the memory for it. I think it might lead to segfault, video renderer can live longer than the decoder
296     free( p_region );
297 }
298
299 /**
300  * Display a subpicture
301  *
302  * Remove the reservation flag of a subpicture, which will cause it to be
303  * ready for display.
304  * \param p_spu the subpicture unit object
305  * \param p_subpic the subpicture to display
306  */
307 void spu_DisplaySubpicture( spu_t *p_spu, subpicture_t *p_subpic )
308 {
309     /* Check if status is valid */
310     if( p_subpic->i_status != RESERVED_SUBPICTURE )
311     {
312         msg_Err( p_spu, "subpicture %p has invalid status #%d",
313                  p_subpic, p_subpic->i_status );
314     }
315
316     if( p_subpic->i_channel == DEFAULT_CHAN )
317     {
318         p_subpic->i_channel = 0xFFFF;
319         spu_Control( p_spu, SPU_CHANNEL_CLEAR, DEFAULT_CHAN );
320         p_subpic->i_channel = DEFAULT_CHAN;
321     }
322
323     /* Remove reservation flag */
324     p_subpic->i_status = READY_SUBPICTURE;
325 }
326
327 /**
328  * Allocate a subpicture in the spu heap.
329  *
330  * This function create a reserved subpicture in the spu heap.
331  * A null pointer is returned if the function fails. This method provides an
332  * already allocated zone of memory in the spu data fields. It needs locking
333  * since several pictures can be created by several producers threads.
334  * \param p_spu the subpicture unit in which to create the subpicture
335  * \return NULL on error, a reserved subpicture otherwise
336  */
337 subpicture_t *spu_CreateSubpicture( spu_t *p_spu )
338 {
339     int                 i_subpic;                        /* subpicture index */
340     subpicture_t *      p_subpic = NULL;            /* first free subpicture */
341
342     /* Get lock */
343     vlc_mutex_lock( &p_spu->subpicture_lock );
344
345     /*
346      * Look for an empty place
347      */
348     p_subpic = NULL;
349     for( i_subpic = 0; i_subpic < VOUT_MAX_SUBPICTURES; i_subpic++ )
350     {
351         if( p_spu->p_subpicture[i_subpic].i_status == FREE_SUBPICTURE )
352         {
353             /* Subpicture is empty and ready for allocation */
354             p_subpic = &p_spu->p_subpicture[i_subpic];
355             p_spu->p_subpicture[i_subpic].i_status = RESERVED_SUBPICTURE;
356             break;
357         }
358     }
359
360     /* If no free subpicture could be found */
361     if( p_subpic == NULL )
362     {
363         msg_Err( p_spu, "subpicture heap is full" );
364         vlc_mutex_unlock( &p_spu->subpicture_lock );
365         return NULL;
366     }
367
368     /* Copy subpicture information, set some default values */
369     memset( p_subpic, 0, sizeof(subpicture_t) );
370     p_subpic->i_order    = p_spu->i_subpicture_order++;
371     p_subpic->i_status   = RESERVED_SUBPICTURE;
372     p_subpic->b_absolute = true;
373     p_subpic->b_fade     = false;
374     p_subpic->b_subtitle = false;
375     p_subpic->i_alpha    = 0xFF;
376     p_subpic->p_region   = NULL;
377     p_subpic->pf_render  = NULL;
378     p_subpic->pf_destroy = NULL;
379     p_subpic->p_sys      = NULL;
380     vlc_mutex_unlock( &p_spu->subpicture_lock );
381
382     p_subpic->pf_create_region = __spu_CreateRegion;
383     p_subpic->pf_destroy_region = __spu_DestroyRegion;
384
385     return p_subpic;
386 }
387
388 /**
389  * Remove a subpicture from the heap
390  *
391  * This function frees a previously reserved subpicture.
392  * It is meant to be used when the construction of a picture aborted.
393  * This function does not need locking since reserved subpictures are ignored
394  * by the spu.
395  */
396 void spu_DestroySubpicture( spu_t *p_spu, subpicture_t *p_subpic )
397 {
398     /* Get lock */
399     vlc_mutex_lock( &p_spu->subpicture_lock );
400
401     /* There can be race conditions so we need to check the status */
402     if( p_subpic->i_status == FREE_SUBPICTURE )
403     {
404         vlc_mutex_unlock( &p_spu->subpicture_lock );
405         return;
406     }
407
408     /* Check if status is valid */
409     if( ( p_subpic->i_status != RESERVED_SUBPICTURE )
410            && ( p_subpic->i_status != READY_SUBPICTURE ) )
411     {
412         msg_Err( p_spu, "subpicture %p has invalid status %d",
413                          p_subpic, p_subpic->i_status );
414     }
415
416     while( p_subpic->p_region )
417     {
418         subpicture_region_t *p_region = p_subpic->p_region;
419         p_subpic->p_region = p_region->p_next;
420         spu_DestroyRegion( p_spu, p_region );
421     }
422
423     if( p_subpic->pf_destroy )
424     {
425         p_subpic->pf_destroy( p_subpic );
426     }
427
428     p_subpic->i_status = FREE_SUBPICTURE;
429
430     vlc_mutex_unlock( &p_spu->subpicture_lock );
431 }
432
433 static void FilterRelease( filter_t *p_filter )
434 {
435     if( p_filter->p_module )
436         module_Unneed( p_filter, p_filter->p_module );
437
438     vlc_object_detach( p_filter );
439     vlc_object_release( p_filter );
440 }
441
442 static void SpuRenderCreateBlend( spu_t *p_spu, vlc_fourcc_t i_chroma, int i_aspect )
443 {
444     filter_t *p_blend;
445
446     assert( !p_spu->p_blend );
447
448     p_spu->p_blend =
449     p_blend        = vlc_custom_create( p_spu, sizeof(filter_t),
450                                         VLC_OBJECT_GENERIC, "blend" );
451     if( !p_blend )
452         return;
453
454     es_format_Init( &p_blend->fmt_in, VIDEO_ES, 0 );
455
456     es_format_Init( &p_blend->fmt_out, VIDEO_ES, 0 );
457     p_blend->fmt_out.video.i_x_offset = 0;
458     p_blend->fmt_out.video.i_y_offset = 0;
459     p_blend->fmt_out.video.i_chroma = i_chroma;
460     p_blend->fmt_out.video.i_aspect = i_aspect;
461
462     /* The blend module will be loaded when needed with the real
463     * input format */
464     p_blend->p_module = NULL;
465
466     /* */
467     vlc_object_attach( p_blend, p_spu );
468 }
469 static void SpuRenderUpdateBlend( spu_t *p_spu, int i_out_width, int i_out_height, const video_format_t *p_in_fmt )
470 {
471     filter_t *p_blend = p_spu->p_blend;
472
473     assert( p_blend );
474
475     /* */
476     if( p_blend->p_module && p_blend->fmt_in.video.i_chroma != p_in_fmt->i_chroma )
477     {
478         /* The chroma is not the same, we need to reload the blend module
479          * XXX to match the old behaviour just test !p_blend->fmt_in.video.i_chroma */
480         module_Unneed( p_blend, p_blend->p_module );
481         p_blend->p_module = NULL;
482     }
483
484     /* */
485     p_blend->fmt_in.video = *p_in_fmt;
486
487     /* */
488     p_blend->fmt_out.video.i_width =
489     p_blend->fmt_out.video.i_visible_width = i_out_width;
490     p_blend->fmt_out.video.i_height =
491     p_blend->fmt_out.video.i_visible_height = i_out_height;
492
493     /* */
494     if( !p_blend->p_module )
495         p_blend->p_module = module_Need( p_blend, "video blending", 0, 0 );
496 }
497 static void SpuRenderCreateAndLoadText( spu_t *p_spu )
498 {
499     filter_t *p_text;
500
501     assert( !p_spu->p_text );
502
503     p_spu->p_text =
504     p_text        = vlc_custom_create( p_spu, sizeof(filter_t),
505                                        VLC_OBJECT_GENERIC, "spu text" );
506     if( !p_text )
507         return;
508
509     es_format_Init( &p_text->fmt_in, VIDEO_ES, 0 );
510
511     es_format_Init( &p_text->fmt_out, VIDEO_ES, 0 );
512     p_text->fmt_out.video.i_width =
513     p_text->fmt_out.video.i_visible_width = 32;
514     p_text->fmt_out.video.i_height =
515     p_text->fmt_out.video.i_visible_height = 32;
516
517     p_text->pf_sub_buffer_new = spu_new_buffer;
518     p_text->pf_sub_buffer_del = spu_del_buffer;
519
520     vlc_object_attach( p_text, p_spu );
521
522     /* FIXME TOCHECK shouldn't module_Need( , , psz_modulename, false ) do the
523      * same than these 2 calls ? */
524     char *psz_modulename = var_CreateGetString( p_spu, "text-renderer" );
525     if( psz_modulename && *psz_modulename )
526     {
527         p_text->p_module = module_Need( p_text, "text renderer",
528                                         psz_modulename, true );
529     }
530     free( psz_modulename );
531
532     if( !p_text->p_module )
533         p_text->p_module = module_Need( p_text, "text renderer", NULL, false );
534 }
535
536 static filter_t *CreateAndLoadScale( vlc_object_t *p_obj, vlc_fourcc_t i_chroma )
537 {
538     filter_t *p_scale;
539
540     p_scale = vlc_custom_create( p_obj, sizeof(filter_t),
541                                  VLC_OBJECT_GENERIC, "scale" );
542     if( !p_scale )
543         return NULL;
544
545     es_format_Init( &p_scale->fmt_in, VIDEO_ES, 0 );
546     p_scale->fmt_in.video.i_chroma = i_chroma;
547     p_scale->fmt_in.video.i_width =
548     p_scale->fmt_in.video.i_height = 32;
549
550     es_format_Init( &p_scale->fmt_out, VIDEO_ES, 0 );
551     p_scale->fmt_out.video.i_chroma = i_chroma;
552     p_scale->fmt_out.video.i_width =
553     p_scale->fmt_out.video.i_height = 16;
554
555     p_scale->pf_vout_buffer_new = spu_new_video_buffer;
556     p_scale->pf_vout_buffer_del = spu_del_video_buffer;
557
558     vlc_object_attach( p_scale, p_obj );
559     p_scale->p_module = module_Need( p_scale, "video filter2", 0, 0 );
560
561     return p_scale;
562 }
563 static void SpuRenderCreateAndLoadScale( spu_t *p_spu )
564 {
565     /* FIXME: We'll also be using it for YUVA and RGBA blending ... */
566
567     assert( !p_spu->p_scale );
568     assert( !p_spu->p_scale_yuvp );
569     p_spu->p_scale = CreateAndLoadScale( VLC_OBJECT(p_spu), VLC_FOURCC('Y','U','V','A') );
570     p_spu->p_scale_yuvp = p_spu->p_scale_yuvp = CreateAndLoadScale( VLC_OBJECT(p_spu), VLC_FOURCC('Y','U','V','P') );
571 }
572
573 static void SpuRenderText( spu_t *p_spu, bool *pb_rerender_text,
574                            subpicture_t *p_subpic, subpicture_region_t *p_region, int i_min_scale_ratio )
575 {
576     assert( p_region->fmt.i_chroma == VLC_FOURCC('T','E','X','T') );
577
578     if( !p_spu->p_text || !p_spu->p_text->p_module )
579         goto exit;
580
581     /* Setup 3 variables which can be used to render
582      * time-dependent text (and effects). The first indicates
583      * the total amount of time the text will be on screen,
584      * the second the amount of time it has already been on
585      * screen (can be a negative value as text is layed out
586      * before it is rendered) and the third is a feedback
587      * variable from the renderer - if the renderer sets it
588      * then this particular text is time-dependent, eg. the
589      * visual progress bar inside the text in karaoke and the
590      * text needs to be rendered multiple times in order for
591      * the effect to work - we therefore need to return the
592      * region to its original state at the end of the loop,
593      * instead of leaving it in YUVA or YUVP.
594      * Any renderer which is unaware of how to render
595      * time-dependent text can happily ignore the variables
596      * and render the text the same as usual - it should at
597      * least show up on screen, but the effect won't change
598      * the text over time.
599      */
600
601     /* FIXME why these variables are recreated every time and not
602      * when text renderer module was created ? */
603     var_Create( p_spu->p_text, "spu-duration", VLC_VAR_TIME );
604     var_Create( p_spu->p_text, "spu-elapsed", VLC_VAR_TIME );
605     var_Create( p_spu->p_text, "text-rerender", VLC_VAR_BOOL );
606     var_Create( p_spu->p_text, "scale", VLC_VAR_INTEGER );
607
608     var_SetTime( p_spu->p_text, "spu-duration", p_subpic->i_stop - p_subpic->i_start );
609     var_SetTime( p_spu->p_text, "spu-elapsed", mdate() - p_subpic->i_start );
610     var_SetBool( p_spu->p_text, "text-rerender", false );
611     var_SetInteger( p_spu->p_text, "scale", i_min_scale_ratio );
612
613     if( p_spu->p_text->pf_render_html && p_region->psz_html )
614     {
615         p_spu->p_text->pf_render_html( p_spu->p_text,
616                                        p_region, p_region );
617     }
618     else if( p_spu->p_text->pf_render_text )
619     {
620         p_spu->p_text->pf_render_text( p_spu->p_text,
621                                        p_region, p_region );
622     }
623     *pb_rerender_text = var_GetBool( p_spu->p_text, "text-rerender" );
624
625     var_Destroy( p_spu->p_text, "spu-duration" );
626     var_Destroy( p_spu->p_text, "spu-elapsed" );
627     var_Destroy( p_spu->p_text, "text-rerender" );
628     var_Destroy( p_spu->p_text, "scale" );
629
630 exit:
631     p_region->i_align |= SUBPICTURE_RENDERED;
632 }
633
634 /**
635  * A few scale functions helpers.
636  */
637 typedef struct
638 {
639     int w;
640     int h;
641 } spu_scale_t;
642
643 static spu_scale_t spu_scale_create( int w, int h )
644 {
645     spu_scale_t s = { .w = w, .h = h };
646     if( s.w <= 0 )
647         s.w = SCALE_UNIT;
648     if( s.h <= 0 )
649         s.h = SCALE_UNIT;
650     return s;
651 }
652 static spu_scale_t spu_scale_unit(void )
653 {
654     return spu_scale_create( SCALE_UNIT, SCALE_UNIT );
655 }
656 static spu_scale_t spu_scale_createq( int wn, int wd, int hn, int hd )
657 {
658     return spu_scale_create( wn * SCALE_UNIT / wd,
659                              hn * SCALE_UNIT / hd );
660 }
661 static int spu_scale_w( int v, const spu_scale_t s )
662 {
663     return v * s.w / SCALE_UNIT;
664 }
665 static int spu_scale_h( int v, const spu_scale_t s )
666 {
667     return v * s.h / SCALE_UNIT;
668 }
669 static int spu_invscale_w( int v, const spu_scale_t s )
670 {
671     return v * SCALE_UNIT / s.w;
672 }
673 static int spu_invscale_h( int v, const spu_scale_t s )
674 {
675     return v * SCALE_UNIT / s.h;
676 }
677
678 /**
679  * A few area functions helpers
680  */
681
682 typedef struct
683 {
684     int i_x;
685     int i_y;
686     int i_width;
687     int i_height;
688
689     spu_scale_t scale;
690 } spu_area_t;
691
692 static spu_area_t spu_area_create( int x, int y, int w, int h, spu_scale_t s )
693 {
694     spu_area_t a = { .i_x = x, .i_y = y, .i_width = w, .i_height = h, .scale = s };
695     return a;
696 }
697 static spu_area_t spu_area_scaled( spu_area_t a )
698 {
699     if( a.scale.w == SCALE_UNIT && a.scale.h == SCALE_UNIT )
700         return a;
701
702     a.i_x = spu_scale_w( a.i_x, a.scale );
703     a.i_y = spu_scale_h( a.i_y, a.scale );
704
705     a.i_width  = spu_scale_w( a.i_width,  a.scale );
706     a.i_height = spu_scale_h( a.i_height, a.scale );
707
708     a.scale = spu_scale_unit();
709     return a;
710 }
711 static spu_area_t spu_area_unscaled( spu_area_t a, spu_scale_t s )
712 {
713     if( a.scale.w == s.w && a.scale.h == s.h )
714         return a;
715
716     a = spu_area_scaled( a );
717
718     a.i_x = spu_invscale_w( a.i_x, s );
719     a.i_y = spu_invscale_h( a.i_y, s );
720
721     a.i_width  = spu_invscale_w( a.i_width, s );
722     a.i_height = spu_invscale_h( a.i_height, s );
723
724     a.scale = s;
725     return a;
726 }
727 static bool spu_area_overlap( spu_area_t a, spu_area_t b )
728 {
729     const int i_dx = 0;
730     const int i_dy = 0;
731
732     a = spu_area_scaled( a );
733     b = spu_area_scaled( b );
734
735     return  __MAX( a.i_x-i_dx, b.i_x ) < __MIN( a.i_x+a.i_width +i_dx, b.i_x+b.i_width  ) &&
736             __MAX( a.i_y-i_dy, b.i_y ) < __MIN( a.i_y+a.i_height+i_dy, b.i_y+b.i_height );
737 }
738
739 /**
740  * Avoid area overlapping
741  */
742 static void SpuAreaFixOverlap( spu_area_t *p_dst,
743                                const spu_area_t *p_master,
744                                const spu_area_t *p_sub, int i_sub, int i_align )
745 {
746     spu_area_t a = spu_area_scaled( *p_dst );
747     bool b_moved = false;
748     bool b_ok;
749
750     assert( p_master->i_x == 0 && p_master->i_y == 0 );
751
752     /* Check for overlap
753      * XXX It is not fast O(n^2) but we should not have a lot of region */
754     do
755     {
756         b_ok = true;
757         for( int i = 0; i < i_sub; i++ )
758         {
759             spu_area_t sub = spu_area_scaled( p_sub[i] );
760
761             if( !spu_area_overlap( a, sub ) )
762                 continue;
763
764             if( i_align & SUBPICTURE_ALIGN_TOP )
765             {
766                 /* We go down */
767                 int i_y = sub.i_y + sub.i_height;
768                 if( i_y + a.i_height > p_master->i_height )
769                     break;
770                 a.i_y = i_y;
771                 b_moved = true;
772             }
773             else if( i_align & SUBPICTURE_ALIGN_BOTTOM )
774             {
775                 /* We go up */
776                 int i_y = sub.i_y - a.i_height;
777                 if( i_y < 0 )
778                     break;
779                 a.i_y = i_y;
780                 b_moved = true;
781             }
782             else
783             {
784                 /* TODO what to do in this case? */
785                 //fprintf( stderr, "Overlap with unsupported alignment\n" );
786                 break;
787             }
788
789             b_ok = false;
790             break;
791         }
792     } while( !b_ok );
793
794     if( b_moved )
795         *p_dst = spu_area_unscaled( a, p_dst->scale );
796 }
797
798
799 /**
800  * Place a region
801  */
802 static void SpuRegionPlace( int *pi_x, int *pi_y,
803                             const subpicture_t *p_subpic,
804                             const subpicture_region_t *p_region,
805                             int i_margin_y )
806 {
807     const int i_delta_x = p_region->i_x;
808     const int i_delta_y = p_region->i_y;
809     int i_x, i_y;
810
811     assert( p_region->i_x != INT_MAX && p_region->i_y != INT_MAX );
812     if( p_region->i_align & SUBPICTURE_ALIGN_TOP )
813     {
814         i_y = i_delta_y;
815     }
816     else if( p_region->i_align & SUBPICTURE_ALIGN_BOTTOM )
817     {
818         i_y = p_subpic->i_original_picture_height - p_region->fmt.i_height - i_delta_y;
819     }
820     else
821     {
822         i_y = p_subpic->i_original_picture_height / 2 - p_region->fmt.i_height / 2;
823     }
824
825     if( p_region->i_align & SUBPICTURE_ALIGN_LEFT )
826     {
827         i_x = i_delta_x;
828     }
829     else if( p_region->i_align & SUBPICTURE_ALIGN_RIGHT )
830     {
831         i_x = p_subpic->i_original_picture_width - p_region->fmt.i_width - i_delta_x;
832     }
833     else
834     {
835         i_x = p_subpic->i_original_picture_width / 2 - p_region->fmt.i_width / 2;
836     }
837
838     if( p_subpic->b_absolute )
839     {
840         i_x = i_delta_x;
841         i_y = i_delta_y;
842     }
843
844     /* Margin shifts all subpictures */
845     if( i_margin_y != 0 )
846         i_y -= i_margin_y;
847
848     /* Clamp offset to not go out of the screen (when possible) */
849     const int i_error_x = (i_x + p_region->fmt.i_width) - p_subpic->i_original_picture_width;
850     if( i_error_x > 0 )
851         i_x -= i_error_x;
852     if( i_x < 0 )
853         i_x = 0;
854
855     const int i_error_y = (i_y + p_region->fmt.i_height) - p_subpic->i_original_picture_height;
856     if( i_error_y > 0 )
857         i_y -= i_error_y;
858     if( i_y < 0 )
859         i_y = 0;
860
861     *pi_x = i_x;
862     *pi_y = i_y;
863 }
864
865 /**
866  * This function computes the current alpha value for a given region.
867  */
868 static int SpuRegionAlpha( subpicture_t *p_subpic, subpicture_region_t *p_region )
869 {
870     /* Compute alpha blend value */
871     int i_fade_alpha = 255;
872     if( p_subpic->b_fade )
873     {
874         mtime_t i_fade_start = ( p_subpic->i_stop +
875                                  p_subpic->i_start ) / 2;
876         mtime_t i_now = mdate();
877
878         if( i_now >= i_fade_start && p_subpic->i_stop > i_fade_start )
879         {
880             i_fade_alpha = 255 * ( p_subpic->i_stop - i_now ) /
881                            ( p_subpic->i_stop - i_fade_start );
882         }
883     }
884     return i_fade_alpha * p_subpic->i_alpha * p_region->i_alpha / 65025;
885 }
886
887 /**
888  * It will render the provided region onto p_pic_dst.
889  */
890
891 static void SpuRenderRegion( spu_t *p_spu,
892                              picture_t *p_pic_dst, spu_area_t *p_area,
893                              subpicture_t *p_subpic, subpicture_region_t *p_region,
894                              const spu_scale_t scale_size,
895                              const video_format_t *p_fmt,
896                              const spu_area_t *p_subtitle_area, int i_subtitle_area )
897 {
898     video_format_t fmt_original = p_region->fmt;
899     bool b_rerender_text = false;
900     bool b_restore_format = false;
901     int i_x_offset;
902     int i_y_offset;
903     filter_t *p_scale;
904
905     vlc_assert_locked( &p_spu->subpicture_lock );
906
907     /* Invalidate area by default */
908     *p_area = spu_area_create( 0,0, 0,0, scale_size );
909
910     /* Render text region */
911     if( p_region->fmt.i_chroma == VLC_FOURCC('T','E','X','T') )
912     {
913         const int i_min_scale_ratio = SCALE_UNIT; /* FIXME what is the right value? (scale_size is not) */
914         SpuRenderText( p_spu, &b_rerender_text, p_subpic, p_region, i_min_scale_ratio );
915         b_restore_format = b_rerender_text;
916
917         /* Check if the rendering has failed ... */
918         if( p_region->fmt.i_chroma == VLC_FOURCC('T','E','X','T') )
919             goto exit;
920     }
921
922     /* Force palette if requested
923      * FIXME b_force_palette and b_force_crop are applied to all subpictures using palette
924      * instead of only the right one (being the dvd spu).
925      */
926     const bool b_using_palette = p_region->fmt.i_chroma == VLC_FOURCC('Y','U','V','P');
927     const bool b_force_palette = b_using_palette && p_spu->b_force_palette;
928     const bool b_force_crop    = b_force_palette && p_spu->b_force_crop;
929
930
931     /* Compute the margin which is expressed in destination pixel unit
932      * The margin is applied only to subtitle and when no forced crop is
933      * requested (dvd menu) */
934     int i_margin_y = 0;
935     if( !b_force_crop && p_subpic->b_subtitle )
936         i_margin_y = spu_invscale_h( p_spu->i_margin, scale_size );
937
938     /* Place the picture
939      * We compute the position in the rendered size */
940     SpuRegionPlace( &i_x_offset, &i_y_offset,
941                     p_subpic, p_region, i_margin_y );
942
943     /* Save this position for subtitle overlap support
944      * it is really important that there are given without scale_size applied */
945     *p_area = spu_area_create( i_x_offset, i_y_offset,
946                                p_region->fmt.i_width, p_region->fmt.i_height,
947                                scale_size );
948
949     /* Handle overlapping subtitles when possible */
950     if( p_subpic->b_subtitle && !p_subpic->b_absolute )
951     {
952         spu_area_t display = spu_area_create( 0, 0, p_fmt->i_width, p_fmt->i_height, spu_scale_unit() );
953
954         SpuAreaFixOverlap( p_area, &display, p_subtitle_area, i_subtitle_area, p_region->i_align );
955     }
956
957     /* Fix the position for the current scale_size */
958     i_x_offset = spu_scale_w( p_area->i_x, p_area->scale );
959     i_y_offset = spu_scale_h( p_area->i_y, p_area->scale );
960
961     if( b_force_palette )
962     {
963         /* It looks so wrong I won't comment
964          * p_palette->palette is [256][4] with a int i_entries
965          * p_spu->palette is [4][4]
966          * */
967         p_region->fmt.p_palette->i_entries = 4;
968         memcpy( p_region->fmt.p_palette->palette, p_spu->palette, 4*sizeof(uint32_t) );
969     }
970
971     if( b_using_palette )
972         p_scale = p_spu->p_scale_yuvp;
973     else
974         p_scale = p_spu->p_scale;
975
976     /* Scale from rendered size to destination size */
977     if( p_scale &&
978         ( scale_size.w != SCALE_UNIT || scale_size.h != SCALE_UNIT || b_force_palette ) )
979     {
980         const unsigned i_dst_width  = spu_scale_w( p_region->fmt.i_width, scale_size );
981         const unsigned i_dst_height = spu_scale_h( p_region->fmt.i_height, scale_size );
982
983         /* TODO when b_using_palette is true, we should first convert it to YUVA to allow
984          * a proper rescaling */
985
986         /* Destroy if cache is unusable */
987         if( p_region->p_cache )
988         {
989             if( p_region->p_cache->fmt.i_width  != i_dst_width ||
990                 p_region->p_cache->fmt.i_height != i_dst_height ||
991                 b_force_palette )
992             {
993                 p_subpic->pf_destroy_region( VLC_OBJECT(p_spu),
994                                              p_region->p_cache );
995                 p_region->p_cache = NULL;
996             }
997         }
998
999         /* Scale if needed into cache */
1000         if( !p_region->p_cache )
1001         {
1002             picture_t *p_pic;
1003
1004             p_scale->fmt_in.video = p_region->fmt;
1005             p_scale->fmt_out.video = p_region->fmt;
1006
1007             p_scale->fmt_out.video.i_width = i_dst_width;
1008             p_scale->fmt_out.video.i_height = i_dst_height;
1009
1010             p_scale->fmt_out.video.i_visible_width =
1011                 spu_scale_w( p_region->fmt.i_visible_width, scale_size );
1012             p_scale->fmt_out.video.i_visible_height =
1013                 spu_scale_h( p_region->fmt.i_visible_height, scale_size );
1014
1015             p_region->p_cache =
1016                 p_subpic->pf_create_region( VLC_OBJECT(p_spu),
1017                                             &p_scale->fmt_out.video );
1018
1019             p_pic = NULL;
1020             if( p_scale->p_module )
1021             {
1022                 picture_Yield( &p_region->picture );
1023                 p_pic = p_scale->pf_video_filter( p_scale, &p_region->picture );
1024             }
1025             if( p_pic )
1026             {
1027                 picture_CopyPixels( &p_region->p_cache->picture, p_pic );
1028                 picture_Release( p_pic );
1029
1030                 if( p_region->p_cache->fmt.p_palette )
1031                     *p_region->p_cache->fmt.p_palette = *p_region->fmt.p_palette;
1032
1033                 /* i_x/i_y of cached region should NOT be used. I set them to
1034                  * an invalid value to catch it (assert) */
1035                 p_region->p_cache->i_x = INT_MAX;
1036                 p_region->p_cache->i_y = INT_MAX;
1037                 p_region->p_cache->i_align = p_region->i_align;
1038                 p_region->p_cache->i_alpha = p_region->i_alpha;
1039             }
1040             else
1041             {
1042                 msg_Err( p_spu, "scaling failed (module not loaded)" );
1043                 p_subpic->pf_destroy_region( VLC_OBJECT(p_spu),
1044                                              p_region->p_cache );
1045                 p_region->p_cache = NULL;
1046             }
1047         }
1048
1049         /* And use the scaled picture */
1050         if( p_region->p_cache )
1051         {
1052             p_region = p_region->p_cache;
1053             fmt_original = p_region->fmt;
1054         }
1055     }
1056
1057     /* Force cropping if requested */
1058     if( b_force_crop )
1059     {
1060         video_format_t *p_fmt = &p_region->fmt;
1061         int i_crop_x = spu_scale_w( p_spu->i_crop_x, scale_size );
1062         int i_crop_y = spu_scale_h( p_spu->i_crop_y, scale_size );
1063         int i_crop_width = spu_scale_w( p_spu->i_crop_width, scale_size );
1064         int i_crop_height= spu_scale_h( p_spu->i_crop_height,scale_size );
1065
1066         /* Find the intersection */
1067         if( i_crop_x + i_crop_width <= i_x_offset ||
1068             i_x_offset + (int)p_fmt->i_visible_width < i_crop_x ||
1069             i_crop_y + i_crop_height <= i_y_offset ||
1070             i_y_offset + (int)p_fmt->i_visible_height < i_crop_y )
1071         {
1072             /* No intersection */
1073             p_fmt->i_visible_width = p_fmt->i_visible_height = 0;
1074         }
1075         else
1076         {
1077             int i_x, i_y, i_x_end, i_y_end;
1078             i_x = __MAX( i_crop_x, i_x_offset );
1079             i_y = __MAX( i_crop_y, i_y_offset );
1080             i_x_end = __MIN( i_crop_x + i_crop_width,
1081                            i_x_offset + (int)p_fmt->i_visible_width );
1082             i_y_end = __MIN( i_crop_y + i_crop_height,
1083                            i_y_offset + (int)p_fmt->i_visible_height );
1084
1085             p_fmt->i_x_offset = i_x - i_x_offset;
1086             p_fmt->i_y_offset = i_y - i_y_offset;
1087             p_fmt->i_visible_width = i_x_end - i_x;
1088             p_fmt->i_visible_height = i_y_end - i_y;
1089
1090             i_x_offset = __MAX( i_x, 0 );
1091             i_y_offset = __MAX( i_y, 0 );
1092         }
1093         b_restore_format = true;
1094     }
1095
1096     /* Update the blender */
1097     SpuRenderUpdateBlend( p_spu, p_fmt->i_width, p_fmt->i_height, &p_region->fmt );
1098
1099     if( p_spu->p_blend->p_module )
1100     {
1101         const int i_alpha = SpuRegionAlpha( p_subpic, p_region );
1102
1103         p_spu->p_blend->pf_video_blend( p_spu->p_blend, p_pic_dst,
1104             &p_region->picture, i_x_offset, i_y_offset, i_alpha );
1105     }
1106     else
1107     {
1108         msg_Err( p_spu, "blending %4.4s to %4.4s failed",
1109                  (char *)&p_spu->p_blend->fmt_out.video.i_chroma,
1110                  (char *)&p_spu->p_blend->fmt_out.video.i_chroma );
1111     }
1112
1113 exit:
1114     if( b_rerender_text )
1115     {
1116         /* Some forms of subtitles need to be re-rendered more than
1117          * once, eg. karaoke. We therefore restore the region to its
1118          * pre-rendered state, so the next time through everything is
1119          * calculated again.
1120          */
1121         p_region->picture.pf_release( &p_region->picture );
1122         memset( &p_region->picture, 0, sizeof( picture_t ) );
1123         p_region->i_align &= ~SUBPICTURE_RENDERED;
1124     }
1125     if( b_restore_format )
1126         p_region->fmt = fmt_original;
1127 }
1128
1129 /**
1130  * This function compares two 64 bits integers.
1131  * It can be used by qsort.
1132  */
1133 static int IntegerCmp( int64_t i0, int64_t i1 )
1134 {
1135     return i0 < i1 ? -1 : i0 > i1 ? 1 : 0;
1136 }
1137 /**
1138  * This function compares 2 subpictures using the following properties 
1139  * (ordered by priority)
1140  * 1. absolute positionning
1141  * 2. start time
1142  * 3. creation order
1143  *
1144  * It can be used by qsort.
1145  *
1146  * XXX spu_RenderSubpictures depends heavily on this order.
1147  */
1148 static int SubpictureCmp( const void *s0, const void *s1 )
1149 {
1150     subpicture_t *p_subpic0 = *(subpicture_t**)s0;
1151     subpicture_t *p_subpic1 = *(subpicture_t**)s1;
1152     int r;
1153
1154     r = IntegerCmp( !p_subpic0->b_absolute, !p_subpic1->b_absolute );
1155     if( !r )
1156         r = IntegerCmp( p_subpic0->i_start, p_subpic1->i_start );
1157     if( !r )
1158         r = IntegerCmp( p_subpic0->i_order, p_subpic1->i_order );
1159     return r;
1160 }
1161 /**
1162  * This function renders all sub picture units in the list.
1163  */
1164 void spu_RenderSubpictures( spu_t *p_spu,
1165                             picture_t *p_pic_dst, const video_format_t *p_fmt_dst,
1166                             subpicture_t *p_subpic_list,
1167                             const video_format_t *p_fmt_src )
1168 {
1169     const int i_source_video_width  = p_fmt_src->i_width;
1170     const int i_source_video_height = p_fmt_src->i_height;
1171     const mtime_t i_current_date = mdate();
1172
1173     unsigned int i_subpicture;
1174     subpicture_t *pp_subpicture[VOUT_MAX_SUBPICTURES];
1175
1176     unsigned int i_subtitle_region_count;
1177     spu_area_t p_subtitle_area_buffer[VOUT_MAX_SUBPICTURES];
1178     spu_area_t *p_subtitle_area;
1179     int i_subtitle_area;
1180
1181     /* Get lock */
1182     vlc_mutex_lock( &p_spu->subpicture_lock );
1183
1184     /* Preprocess subpictures */
1185     i_subpicture = 0;
1186     i_subtitle_region_count = 0;
1187     for( subpicture_t * p_subpic = p_subpic_list;
1188             p_subpic != NULL && p_subpic->i_status != FREE_SUBPICTURE; /* Check again status (as we where unlocked) */
1189                 p_subpic = p_subpic->p_next )
1190     {
1191         /* */
1192         if( p_subpic->pf_pre_render )
1193             p_subpic->pf_pre_render( p_spu, p_subpic, p_fmt_dst );
1194
1195         if( p_subpic->pf_update_regions )
1196         {
1197             video_format_t fmt_org = *p_fmt_dst;
1198             fmt_org.i_width =
1199             fmt_org.i_visible_width = i_source_video_width;
1200             fmt_org.i_height =
1201             fmt_org.i_visible_height = i_source_video_height;
1202
1203             p_subpic->pf_update_regions( p_spu, p_subpic, &fmt_org, i_current_date );
1204         }
1205
1206         /* */
1207         if( p_subpic->b_subtitle )
1208         {
1209             for( subpicture_region_t *r = p_subpic->p_region; r != NULL; r = r->p_next )
1210                 i_subtitle_region_count++;
1211         }
1212
1213         /* */
1214         pp_subpicture[i_subpicture++] = p_subpic;
1215     }
1216
1217     /* Be sure we have at least 1 picture to process */
1218     if( i_subpicture <= 0 )
1219     {
1220         vlc_mutex_unlock( &p_spu->subpicture_lock );
1221         return;
1222     }
1223
1224     /* Now order subpicture array
1225      * XXX The order is *really* important for overlap subtitles positionning */
1226     qsort( pp_subpicture, i_subpicture, sizeof(*pp_subpicture), SubpictureCmp );
1227
1228     /* Allocate area array for subtitle overlap */
1229     i_subtitle_area = 0;
1230     p_subtitle_area = p_subtitle_area_buffer;
1231     if( i_subtitle_region_count > sizeof(p_subtitle_area_buffer)/sizeof(*p_subtitle_area_buffer) )
1232         p_subtitle_area = calloc( i_subtitle_region_count, sizeof(*p_subtitle_area) );
1233
1234     /* Create the blending module */
1235     if( !p_spu->p_blend )
1236         SpuRenderCreateBlend( p_spu, p_fmt_dst->i_chroma, p_fmt_dst->i_aspect );
1237
1238     /* Process all subpictures and regions (in the right order) */
1239     for( unsigned int i_index = 0; i_index < i_subpicture; i_index++ )
1240     {
1241         subpicture_t *p_subpic = pp_subpicture[i_index];
1242         subpicture_region_t *p_region;
1243
1244         if( !p_subpic->p_region )
1245             continue;
1246
1247         /* FIXME when possible use a better rendering size than source size
1248          * (max of display size and source size for example) FIXME */
1249         int i_render_width  = p_subpic->i_original_picture_width;
1250         int i_render_height = p_subpic->i_original_picture_height;
1251         if( !i_render_width || !i_render_height )
1252         {
1253             if( i_render_width != 0 || i_render_height != 0 )
1254                 msg_Err( p_spu, "unsupported original picture size %dx%d",
1255                          i_render_width, i_render_height );
1256
1257             p_subpic->i_original_picture_width  = i_render_width = i_source_video_width;
1258             p_subpic->i_original_picture_height = i_render_height = i_source_video_height;
1259         }
1260
1261         if( p_spu->p_text )
1262         {
1263             p_spu->p_text->fmt_out.video.i_width          =
1264             p_spu->p_text->fmt_out.video.i_visible_width  = i_render_width;
1265
1266             p_spu->p_text->fmt_out.video.i_height         =
1267             p_spu->p_text->fmt_out.video.i_visible_height = i_render_height;
1268         }
1269
1270         /* Compute scaling from picture to source size */
1271         spu_scale_t scale = spu_scale_createq( i_source_video_width,  i_render_width,
1272                                                i_source_video_height, i_render_height );
1273
1274         /* Update scaling from source size to display size(p_fmt_dst) */
1275         scale.w = scale.w * p_fmt_dst->i_width  / i_source_video_width;
1276         scale.h = scale.h * p_fmt_dst->i_height / i_source_video_height;
1277
1278         /* Set default subpicture aspect ratio
1279          * FIXME if we only handle 1 aspect ratio per picture, why is it set per
1280          * region ? */
1281         p_region = p_subpic->p_region;
1282         if( !p_region->fmt.i_sar_num || !p_region->fmt.i_sar_den )
1283         {
1284             if( p_region->fmt.i_aspect != 0 )
1285             {
1286                 p_region->fmt.i_sar_den = p_region->fmt.i_aspect;
1287                 p_region->fmt.i_sar_num = VOUT_ASPECT_FACTOR;
1288             }
1289             else
1290             {
1291                 p_region->fmt.i_sar_den = p_fmt_dst->i_sar_den;
1292                 p_region->fmt.i_sar_num = p_fmt_dst->i_sar_num;
1293             }
1294         }
1295
1296         /* Take care of the aspect ratio */
1297         if( p_region->fmt.i_sar_num * p_fmt_dst->i_sar_den !=
1298             p_region->fmt.i_sar_den * p_fmt_dst->i_sar_num )
1299         {
1300             /* FIXME FIXME what about region->i_x/i_y ? */
1301             scale.w = scale.w *
1302                 (int64_t)p_region->fmt.i_sar_num * p_fmt_dst->i_sar_den /
1303                 p_region->fmt.i_sar_den / p_fmt_dst->i_sar_num;
1304         }
1305
1306         /* Render all regions
1307          * We always transform non absolute subtitle into absolute one on the
1308          * first rendering to allow good subtitle overlap support.
1309          */
1310         for( p_region = p_subpic->p_region; p_region != NULL; p_region = p_region->p_next )
1311         {
1312             spu_area_t area;
1313
1314             /* Check scale validity */
1315             if( scale.w <= 0 || scale.h <= 0 )
1316                 continue;
1317
1318             /* */
1319             SpuRenderRegion( p_spu, p_pic_dst, &area,
1320                              p_subpic, p_region, scale, p_fmt_dst,
1321                              p_subtitle_area, i_subtitle_area );
1322
1323             if( p_subpic->b_subtitle )
1324             {
1325                 area = spu_area_unscaled( area, scale );
1326                 if( !p_subpic->b_absolute && area.i_width > 0 && area.i_height > 0 )
1327                 {
1328                     p_region->i_x = area.i_x;
1329                     p_region->i_y = area.i_y;
1330                 }
1331                 if( p_subtitle_area )
1332                     p_subtitle_area[i_subtitle_area++] = area;
1333             }
1334         }
1335         if( p_subpic->b_subtitle )
1336             p_subpic->b_absolute = true;
1337     }
1338
1339     /* */
1340     if( p_subtitle_area != p_subtitle_area_buffer )
1341         free( p_subtitle_area );
1342
1343     vlc_mutex_unlock( &p_spu->subpicture_lock );
1344 }
1345
1346 /*****************************************************************************
1347  * spu_SortSubpictures: find the subpictures to display
1348  *****************************************************************************
1349  * This function parses all subpictures and decides which ones need to be
1350  * displayed. This operation does not need lock, since only READY_SUBPICTURE
1351  * are handled. If no picture has been selected, display_date will depend on
1352  * the subpicture.
1353  * We also check for ephemer DVD subpictures (subpictures that have
1354  * to be removed if a newer one is available), which makes it a lot
1355  * more difficult to guess if a subpicture has to be rendered or not.
1356  *****************************************************************************/
1357 subpicture_t *spu_SortSubpictures( spu_t *p_spu, mtime_t display_date,
1358                                    bool b_paused, bool b_subtitle_only )
1359 {
1360     int i_channel;
1361     subpicture_t *p_subpic = NULL;
1362
1363     /* Run subpicture filters */
1364     filter_chain_SubFilter( p_spu->p_chain, display_date );
1365
1366     /* We get an easily parsable chained list of subpictures which
1367      * ends with NULL since p_subpic was initialized to NULL. */
1368     for( i_channel = 0; i_channel < p_spu->i_channel; i_channel++ )
1369     {
1370         subpicture_t *p_ephemer = NULL;
1371         mtime_t      ephemer_date = 0;
1372         int i_index;
1373
1374         for( i_index = 0; i_index < VOUT_MAX_SUBPICTURES; i_index++ )
1375         {
1376             subpicture_t *p_current = &p_spu->p_subpicture[i_index];
1377
1378             if( p_current->i_channel != i_channel ||
1379                 p_current->i_status != READY_SUBPICTURE ||
1380                 ( b_subtitle_only && !p_current->b_subtitle ) )
1381             {
1382                 continue;
1383             }
1384             if( display_date &&
1385                 display_date < p_current->i_start )
1386             {
1387                 /* Too early, come back next monday */
1388                 continue;
1389             }
1390
1391             if( p_current->i_start > ephemer_date )
1392                 ephemer_date = p_current->i_start;
1393
1394             if( display_date > p_current->i_stop &&
1395                 ( !p_current->b_ephemer || p_current->i_stop > p_current->i_start ) &&
1396                 !( p_current->b_subtitle && b_paused ) ) /* XXX Assume that subtitle are pausable */
1397             {
1398                 /* Too late, destroy the subpic */
1399                 spu_DestroySubpicture( p_spu, &p_spu->p_subpicture[i_index] );
1400                 continue;
1401             }
1402
1403             /* If this is an ephemer subpic, add it to our list */
1404             if( p_current->b_ephemer )
1405             {
1406                 p_current->p_next = p_ephemer;
1407                 p_ephemer = p_current;
1408
1409                 continue;
1410             }
1411
1412             p_current->p_next = p_subpic;
1413             p_subpic = p_current;
1414         }
1415
1416         /* If we found ephemer subpictures, check if they have to be
1417          * displayed or destroyed */
1418         while( p_ephemer != NULL )
1419         {
1420             subpicture_t *p_tmp = p_ephemer;
1421             p_ephemer = p_ephemer->p_next;
1422
1423             if( p_tmp->i_start < ephemer_date )
1424             {
1425                 /* Ephemer subpicture has lived too long */
1426                 spu_DestroySubpicture( p_spu, p_tmp );
1427             }
1428             else
1429             {
1430                 /* Ephemer subpicture can still live a bit */
1431                 p_tmp->p_next = p_subpic;
1432                 p_subpic = p_tmp;
1433             }
1434         }
1435     }
1436
1437     return p_subpic;
1438 }
1439
1440 /*****************************************************************************
1441  * SpuClearChannel: clear an spu channel
1442  *****************************************************************************
1443  * This function destroys the subpictures which belong to the spu channel
1444  * corresponding to i_channel_id.
1445  *****************************************************************************/
1446 static void SpuClearChannel( spu_t *p_spu, int i_channel, bool b_locked )
1447 {
1448     int          i_subpic;                               /* subpicture index */
1449     subpicture_t *p_subpic = NULL;                  /* first free subpicture */
1450
1451     if( !b_locked )
1452         vlc_mutex_lock( &p_spu->subpicture_lock );
1453
1454     for( i_subpic = 0; i_subpic < VOUT_MAX_SUBPICTURES; i_subpic++ )
1455     {
1456         p_subpic = &p_spu->p_subpicture[i_subpic];
1457         if( p_subpic->i_status == FREE_SUBPICTURE
1458             || ( p_subpic->i_status != RESERVED_SUBPICTURE
1459                  && p_subpic->i_status != READY_SUBPICTURE ) )
1460         {
1461             continue;
1462         }
1463
1464         if( p_subpic->i_channel == i_channel )
1465         {
1466             while( p_subpic->p_region )
1467             {
1468                 subpicture_region_t *p_region = p_subpic->p_region;
1469                 p_subpic->p_region = p_region->p_next;
1470                 spu_DestroyRegion( p_spu, p_region );
1471             }
1472
1473             if( p_subpic->pf_destroy ) p_subpic->pf_destroy( p_subpic );
1474             p_subpic->i_status = FREE_SUBPICTURE;
1475         }
1476     }
1477
1478     if( !b_locked )
1479         vlc_mutex_unlock( &p_spu->subpicture_lock );
1480 }
1481
1482 /*****************************************************************************
1483  * spu_ControlDefault: default methods for the subpicture unit control.
1484  *****************************************************************************/
1485 static int spu_vaControlDefault( spu_t *p_spu, int i_query, va_list args )
1486 {
1487     int *pi, i;
1488
1489     switch( i_query )
1490     {
1491     case SPU_CHANNEL_REGISTER:
1492         pi = (int *)va_arg( args, int * );
1493         vlc_mutex_lock( &p_spu->subpicture_lock );
1494         if( pi )
1495             *pi = p_spu->i_channel++;
1496         vlc_mutex_unlock( &p_spu->subpicture_lock );
1497         break;
1498
1499     case SPU_CHANNEL_CLEAR:
1500         i = (int)va_arg( args, int );
1501         SpuClearChannel( p_spu, i, false );
1502         break;
1503
1504     default:
1505         msg_Dbg( p_spu, "control query not supported" );
1506         return VLC_EGENERIC;
1507     }
1508
1509     return VLC_SUCCESS;
1510 }
1511
1512 /*****************************************************************************
1513  * Object variables callbacks
1514  *****************************************************************************/
1515
1516 /*****************************************************************************
1517  * UpdateSPU: update subpicture settings
1518  *****************************************************************************
1519  * This function is called from CropCallback and at initialization time, to
1520  * retrieve crop information from the input.
1521  *****************************************************************************/
1522 static void UpdateSPU( spu_t *p_spu, vlc_object_t *p_object )
1523 {
1524     vlc_value_t val;
1525
1526     vlc_mutex_lock( &p_spu->subpicture_lock );
1527
1528     p_spu->b_force_palette = false;
1529     p_spu->b_force_crop = false;
1530
1531     if( var_Get( p_object, "highlight", &val ) || !val.b_bool )
1532     {
1533         vlc_mutex_unlock( &p_spu->subpicture_lock );
1534         return;
1535     }
1536
1537     p_spu->b_force_crop = true;
1538     var_Get( p_object, "x-start", &val );
1539     p_spu->i_crop_x = val.i_int;
1540     var_Get( p_object, "y-start", &val );
1541     p_spu->i_crop_y = val.i_int;
1542     var_Get( p_object, "x-end", &val );
1543     p_spu->i_crop_width = val.i_int - p_spu->i_crop_x;
1544     var_Get( p_object, "y-end", &val );
1545     p_spu->i_crop_height = val.i_int - p_spu->i_crop_y;
1546
1547     if( var_Get( p_object, "menu-palette", &val ) == VLC_SUCCESS )
1548     {
1549         memcpy( p_spu->palette, val.p_address, 16 );
1550         p_spu->b_force_palette = true;
1551     }
1552     vlc_mutex_unlock( &p_spu->subpicture_lock );
1553
1554     msg_Dbg( p_object, "crop: %i,%i,%i,%i, palette forced: %i",
1555              p_spu->i_crop_x, p_spu->i_crop_y,
1556              p_spu->i_crop_width, p_spu->i_crop_height,
1557              p_spu->b_force_palette );
1558 }
1559
1560 /*****************************************************************************
1561  * CropCallback: called when the highlight properties are changed
1562  *****************************************************************************
1563  * This callback is called from the input thread when we need cropping
1564  *****************************************************************************/
1565 static int CropCallback( vlc_object_t *p_object, char const *psz_var,
1566                          vlc_value_t oldval, vlc_value_t newval, void *p_data )
1567 {
1568     (void)psz_var; (void)oldval; (void)newval;
1569     UpdateSPU( (spu_t *)p_data, p_object );
1570     return VLC_SUCCESS;
1571 }
1572
1573 /*****************************************************************************
1574  * Buffers allocation callbacks for the filters
1575  *****************************************************************************/
1576 static subpicture_t *sub_new_buffer( filter_t *p_filter )
1577 {
1578     filter_owner_sys_t *p_sys = p_filter->p_owner;
1579     subpicture_t *p_subpicture = spu_CreateSubpicture( p_sys->p_spu );
1580     if( p_subpicture ) p_subpicture->i_channel = p_sys->i_channel;
1581     return p_subpicture;
1582 }
1583
1584 static void sub_del_buffer( filter_t *p_filter, subpicture_t *p_subpic )
1585 {
1586     filter_owner_sys_t *p_sys = p_filter->p_owner;
1587     spu_DestroySubpicture( p_sys->p_spu, p_subpic );
1588 }
1589
1590 static subpicture_t *spu_new_buffer( filter_t *p_filter )
1591 {
1592     subpicture_t *p_subpic = calloc( 1, sizeof(subpicture_t) );
1593     if( !p_subpic )
1594         return NULL;
1595
1596     p_subpic->b_absolute = true;
1597     p_subpic->i_alpha    = 0xFF;
1598
1599     p_subpic->pf_create_region = __spu_CreateRegion;
1600     p_subpic->pf_destroy_region = __spu_DestroyRegion;
1601
1602     VLC_UNUSED(p_filter);
1603     return p_subpic;
1604 }
1605
1606 static void spu_del_buffer( filter_t *p_filter, subpicture_t *p_subpic )
1607 {
1608     while( p_subpic->p_region )
1609     {
1610         subpicture_region_t *p_region = p_subpic->p_region;
1611         p_subpic->p_region = p_region->p_next;
1612         p_subpic->pf_destroy_region( VLC_OBJECT(p_filter), p_region );
1613     }
1614
1615     free( p_subpic );
1616 }
1617
1618 static picture_t *spu_new_video_buffer( filter_t *p_filter )
1619 {
1620     const video_format_t *p_fmt = &p_filter->fmt_out.video;
1621
1622     VLC_UNUSED(p_filter);
1623     return picture_New( p_fmt->i_chroma,
1624                         p_fmt->i_width, p_fmt->i_height, p_fmt->i_aspect );
1625 }
1626
1627 static void spu_del_video_buffer( filter_t *p_filter, picture_t *p_picture )
1628 {
1629     VLC_UNUSED(p_filter);
1630     picture_Release( p_picture );
1631 }
1632
1633 static int SubFilterCallback( vlc_object_t *p_object, char const *psz_var,
1634                          vlc_value_t oldval, vlc_value_t newval, void *p_data )
1635 {
1636     spu_t *p_spu = p_data;
1637
1638     VLC_UNUSED(p_object); VLC_UNUSED(oldval);
1639     VLC_UNUSED(newval); VLC_UNUSED(psz_var);
1640
1641     vlc_mutex_lock( &p_spu->subpicture_lock );
1642     filter_chain_Reset( p_spu->p_chain, NULL, NULL );
1643     spu_ParseChain( p_spu );
1644     vlc_mutex_unlock( &p_spu->subpicture_lock );
1645     return VLC_SUCCESS;
1646 }
1647
1648 static int SubFilterAllocationInit( filter_t *p_filter, void *p_data )
1649 {
1650     spu_t *p_spu = p_data;
1651
1652     filter_owner_sys_t *p_sys = malloc( sizeof(filter_owner_sys_t) );
1653     if( !p_sys )
1654         return VLC_EGENERIC;
1655
1656     p_filter->pf_sub_buffer_new = sub_new_buffer;
1657     p_filter->pf_sub_buffer_del = sub_del_buffer;
1658
1659     p_filter->p_owner = p_sys;
1660     spu_Control( p_spu, SPU_CHANNEL_REGISTER, &p_sys->i_channel );
1661     p_sys->p_spu = p_spu;
1662
1663     return VLC_SUCCESS;
1664 }
1665
1666 static void SubFilterAllocationClean( filter_t *p_filter )
1667 {
1668     filter_owner_sys_t *p_sys = p_filter->p_owner;
1669
1670     SpuClearChannel( p_sys->p_spu, p_sys->i_channel, true );
1671     free( p_filter->p_owner );
1672 }
1673