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