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