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