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