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