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