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