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