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