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