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