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