]> git.sesse.net Git - vlc/blob - src/video_output/video_output.c
Fixed vout reuse regression.
[vlc] / src / video_output / video_output.c
1 /*****************************************************************************
2  * video_output.c : video output thread
3  *
4  * This module describes the programming interface for video output threads.
5  * It includes functions allowing to open a new thread, send pictures to a
6  * thread, and destroy a previously oppened video output thread.
7  *****************************************************************************
8  * Copyright (C) 2000-2007 the VideoLAN team
9  * $Id$
10  *
11  * Authors: Vincent Seguin <seguin@via.ecp.fr>
12  *          Gildas Bazin <gbazin@videolan.org>
13  *          Laurent Aimar <fenrir _AT_ videolan _DOT_ org>
14  *
15  * This program is free software; you can redistribute it and/or modify
16  * it under the terms of the GNU General Public License as published by
17  * the Free Software Foundation; either version 2 of the License, or
18  * (at your option) any later version.
19  *
20  * This program is distributed in the hope that it will be useful,
21  * but WITHOUT ANY WARRANTY; without even the implied warranty of
22  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23  * GNU General Public License for more details.
24  *
25  * You should have received a copy of the GNU General Public License
26  * along with this program; if not, write to the Free Software
27  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
28  *****************************************************************************/
29
30 /*****************************************************************************
31  * Preamble
32  *****************************************************************************/
33 #ifdef HAVE_CONFIG_H
34 # include "config.h"
35 #endif
36
37 #include <vlc_common.h>
38
39 #include <stdlib.h>                                                /* free() */
40 #include <string.h>
41 #include <assert.h>
42
43 #include <vlc_vout.h>
44
45 #include <vlc_filter.h>
46 #include <vlc_vout_osd.h>
47
48 #include <libvlc.h>
49 #include "vout_internal.h"
50 #include "interlacing.h"
51 #include "postprocessing.h"
52 #include "display.h"
53
54 /*****************************************************************************
55  * Local prototypes
56  *****************************************************************************/
57 static void *Thread(void *);
58 static void VoutDestructor(vlc_object_t *);
59
60 /* Maximum delay between 2 displayed pictures.
61  * XXX it is needed for now but should be removed in the long term.
62  */
63 #define VOUT_REDISPLAY_DELAY (INT64_C(80000))
64
65 /**
66  * Late pictures having a delay higher than this value are thrashed.
67  */
68 #define VOUT_DISPLAY_LATE_THRESHOLD (INT64_C(20000))
69
70 /* Better be in advance when awakening than late... */
71 #define VOUT_MWAIT_TOLERANCE (INT64_C(1000))
72
73 /* */
74 static int VoutValidateFormat(video_format_t *dst,
75                               const video_format_t *src)
76 {
77     if (src->i_width <= 0 || src->i_height <= 0)
78         return VLC_EGENERIC;
79     if (src->i_sar_num <= 0 || src->i_sar_den <= 0)
80         return VLC_EGENERIC;
81
82     /* */
83     video_format_Copy(dst, src);
84     dst->i_chroma = vlc_fourcc_GetCodec(VIDEO_ES, src->i_chroma);
85     vlc_ureduce( &dst->i_sar_num, &dst->i_sar_den,
86                  src->i_sar_num,  src->i_sar_den, 50000 );
87     if (dst->i_sar_num <= 0 || dst->i_sar_den <= 0) {
88         dst->i_sar_num = 1;
89         dst->i_sar_den = 1;
90     }
91     video_format_FixRgb(dst);
92     return VLC_SUCCESS;
93 }
94
95 static vout_thread_t *VoutCreate(vlc_object_t *object,
96                                  const vout_configuration_t *cfg)
97 {
98     video_format_t original;
99     if (VoutValidateFormat(&original, cfg->fmt))
100         return NULL;
101
102     /* Allocate descriptor */
103     vout_thread_t *vout = vlc_custom_create(object,
104                                             sizeof(*vout) + sizeof(*vout->p),
105                                             VLC_OBJECT_VOUT, "video output");
106     if (!vout) {
107         video_format_Clean(&original);
108         return NULL;
109     }
110
111     /* */
112     vout->p = (vout_thread_sys_t*)&vout[1];
113
114     vout->p->original = original;
115     vout->p->dpb_size = cfg->dpb_size;
116
117     vout_control_Init(&vout->p->control);
118     vout_control_PushVoid(&vout->p->control, VOUT_CONTROL_INIT);
119
120     vout_statistic_Init(&vout->p->statistic);
121     vout->p->i_par_num =
122     vout->p->i_par_den = 1;
123
124     vout_snapshot_Init(&vout->p->snapshot);
125
126     /* Initialize locks */
127     vlc_mutex_init(&vout->p->picture_lock);
128     vlc_mutex_init(&vout->p->vfilter_lock);
129
130     /* Attach the new object now so we can use var inheritance below */
131     vlc_object_attach(vout, object);
132
133     /* Initialize subpicture unit */
134     vout->p->p_spu = spu_Create(vout);
135
136     /* Take care of some "interface/control" related initialisations */
137     vout_IntfInit(vout);
138
139     /* Get splitter name if present */
140     char *splitter_name = var_GetNonEmptyString(vout, "vout-filter");
141     if (splitter_name) {
142         if (asprintf(&vout->p->splitter_name, "%s,none", splitter_name) < 0)
143             vout->p->splitter_name = NULL;
144         free(splitter_name);
145     } else {
146         vout->p->splitter_name = NULL;
147     }
148
149     /* */
150     vout_InitInterlacingSupport(vout, vout->p->displayed.is_interlaced);
151
152     /* */
153     vlc_object_set_destructor(vout, VoutDestructor);
154
155     /* */
156     if (vlc_clone(&vout->p->thread, Thread, vout,
157                   VLC_THREAD_PRIORITY_OUTPUT)) {
158         vlc_object_release(vout);
159         return NULL;
160     }
161
162     vout_control_WaitEmpty(&vout->p->control);
163
164     if (vout->p->dead) {
165         msg_Err(vout, "video output creation failed");
166         vout_CloseAndRelease(vout);
167         return NULL;
168     }
169
170     vout->p->input = cfg->input;
171     if (vout->p->input)
172         spu_Attach(vout->p->p_spu, vout->p->input, true);
173
174     return vout;
175 }
176
177 vout_thread_t *(vout_Request)(vlc_object_t *object,
178                               const vout_configuration_t *cfg)
179 {
180     vout_thread_t *vout = cfg->vout;
181     if (cfg->change_fmt && !cfg->fmt) {
182         if (vout)
183             vout_CloseAndRelease(vout);
184         return NULL;
185     }
186
187     /* If a vout is provided, try reusing it */
188     if (vout) {
189         vlc_object_detach(vout);
190         vlc_object_attach(vout, object);
191
192         if (vout->p->input != cfg->input) {
193             if (vout->p->input)
194                 spu_Attach(vout->p->p_spu, vout->p->input, false);
195             vout->p->input = cfg->input;
196             if (vout->p->input)
197                 spu_Attach(vout->p->p_spu, vout->p->input, true);
198         }
199
200         if (cfg->change_fmt) {
201             vout_control_cmd_t cmd;
202             vout_control_cmd_Init(&cmd, VOUT_CONTROL_REINIT);
203             cmd.u.cfg = cfg;
204
205             vout_control_Push(&vout->p->control, &cmd);
206             vout_control_WaitEmpty(&vout->p->control);
207         }
208
209         if (!vout->p->dead) {
210             msg_Dbg(object, "reusing provided vout");
211             return vout;
212         }
213         vout_CloseAndRelease(vout);
214
215         msg_Warn(object, "cannot reuse provided vout");
216     }
217     return VoutCreate(object, cfg);
218 }
219
220 /*****************************************************************************
221  * vout_Close: Close a vout created by VoutCreate.
222  *****************************************************************************
223  * You HAVE to call it on vout created by VoutCreate before vlc_object_release.
224  * You should NEVER call it on vout not obtained through VoutCreate
225  * (like with vout_Request or vlc_object_find.)
226  * You can use vout_CloseAndRelease() as a convenience method.
227  *****************************************************************************/
228 void vout_Close(vout_thread_t *vout)
229 {
230     assert(vout);
231
232     if (vout->p->input)
233         spu_Attach(vout->p->p_spu, vout->p->input, false);
234     vlc_object_detach(vout->p->p_spu);
235
236     vout_snapshot_End(&vout->p->snapshot);
237
238     vout_control_PushVoid(&vout->p->control, VOUT_CONTROL_CLEAN);
239     vlc_join(vout->p->thread, NULL);
240 }
241
242 /* */
243 static void VoutDestructor(vlc_object_t *object)
244 {
245     vout_thread_t *vout = (vout_thread_t *)object;
246
247     /* Make sure the vout was stopped first */
248     //assert(!vout->p_module);
249
250     free(vout->p->splitter_name);
251
252     /* */
253     spu_Destroy(vout->p->p_spu);
254
255     /* Destroy the locks */
256     vlc_mutex_destroy(&vout->p->picture_lock);
257     vlc_mutex_destroy(&vout->p->vfilter_lock);
258     vout_control_Clean(&vout->p->control);
259
260     /* */
261     vout_statistic_Clean(&vout->p->statistic);
262
263     /* */
264     vout_snapshot_Clean(&vout->p->snapshot);
265
266     video_format_Clean(&vout->p->original);
267 }
268
269 /* */
270 void vout_ChangePause(vout_thread_t *vout, bool is_paused, mtime_t date)
271 {
272     vout_control_cmd_t cmd;
273     vout_control_cmd_Init(&cmd, VOUT_CONTROL_PAUSE);
274     cmd.u.pause.is_on = is_paused;
275     cmd.u.pause.date  = date;
276     vout_control_Push(&vout->p->control, &cmd);
277
278     vout_control_WaitEmpty(&vout->p->control);
279 }
280
281 void vout_GetResetStatistic(vout_thread_t *vout, int *displayed, int *lost)
282 {
283     vout_statistic_GetReset( &vout->p->statistic, displayed, lost );
284 }
285
286 void vout_Flush(vout_thread_t *vout, mtime_t date)
287 {
288     vout_control_PushTime(&vout->p->control, VOUT_CONTROL_FLUSH, date);
289     vout_control_WaitEmpty(&vout->p->control);
290 }
291
292 void vout_Reset(vout_thread_t *vout)
293 {
294     vout_control_PushVoid(&vout->p->control, VOUT_CONTROL_RESET);
295     vout_control_WaitEmpty(&vout->p->control);
296 }
297
298 bool vout_IsEmpty(vout_thread_t *vout)
299 {
300     vlc_mutex_lock(&vout->p->picture_lock);
301
302     picture_t *picture = picture_fifo_Peek(vout->p->decoder_fifo);
303     if (picture)
304         picture_Release(picture);
305
306     vlc_mutex_unlock(&vout->p->picture_lock);
307
308     return !picture;
309 }
310
311 void vout_FixLeaks( vout_thread_t *vout )
312 {
313     vlc_mutex_lock(&vout->p->picture_lock);
314
315     picture_t *picture = picture_fifo_Peek(vout->p->decoder_fifo);
316     if (!picture) {
317         picture = picture_pool_Get(vout->p->decoder_pool);
318     }
319
320     if (picture) {
321         picture_Release(picture);
322         /* Not all pictures has been displayed yet or some are
323          * free */
324         vlc_mutex_unlock(&vout->p->picture_lock);
325         return;
326     }
327
328     /* There is no reason that no pictures are available, force one
329      * from the pool, becarefull with it though */
330     msg_Err(vout, "pictures leaked, trying to workaround");
331
332     /* */
333     picture_pool_NonEmpty(vout->p->decoder_pool, false);
334
335     vlc_mutex_unlock(&vout->p->picture_lock);
336 }
337 void vout_NextPicture(vout_thread_t *vout, mtime_t *duration)
338 {
339     vout_control_cmd_t cmd;
340     vout_control_cmd_Init(&cmd, VOUT_CONTROL_STEP);
341     cmd.u.time_ptr = duration;
342
343     vout_control_Push(&vout->p->control, &cmd);
344     vout_control_WaitEmpty(&vout->p->control);
345 }
346
347 void vout_DisplayTitle(vout_thread_t *vout, const char *title)
348 {
349     assert(title);
350     vout_control_PushString(&vout->p->control, VOUT_CONTROL_OSD_TITLE, title);
351 }
352
353 void vout_PutSubpicture( vout_thread_t *vout, subpicture_t *subpic )
354 {
355     spu_DisplaySubpicture(vout->p->p_spu, subpic);
356 }
357 int vout_RegisterSubpictureChannel( vout_thread_t *vout )
358 {
359     return spu_RegisterChannel(vout->p->p_spu);
360 }
361 void vout_FlushSubpictureChannel( vout_thread_t *vout, int channel )
362 {
363     spu_ClearChannel(vout->p->p_spu, channel);
364 }
365
366 /* vout_Control* are usable by anyone at anytime */
367 void vout_ControlChangeFullscreen(vout_thread_t *vout, bool fullscreen)
368 {
369     vout_control_PushBool(&vout->p->control, VOUT_CONTROL_FULLSCREEN,
370                           fullscreen);
371 }
372 void vout_ControlChangeOnTop(vout_thread_t *vout, bool is_on_top)
373 {
374     vout_control_PushBool(&vout->p->control, VOUT_CONTROL_ON_TOP,
375                           is_on_top);
376 }
377 void vout_ControlChangeDisplayFilled(vout_thread_t *vout, bool is_filled)
378 {
379     vout_control_PushBool(&vout->p->control, VOUT_CONTROL_DISPLAY_FILLED,
380                           is_filled);
381 }
382 void vout_ControlChangeZoom(vout_thread_t *vout, int num, int den)
383 {
384     vout_control_PushPair(&vout->p->control, VOUT_CONTROL_ZOOM,
385                           num, den);
386 }
387 void vout_ControlChangeSampleAspectRatio(vout_thread_t *vout,
388                                          unsigned num, unsigned den)
389 {
390     vout_control_PushPair(&vout->p->control, VOUT_CONTROL_ASPECT_RATIO,
391                           num, den);
392 }
393 void vout_ControlChangeCropRatio(vout_thread_t *vout,
394                                  unsigned num, unsigned den)
395 {
396     vout_control_PushPair(&vout->p->control, VOUT_CONTROL_CROP_RATIO,
397                           num, den);
398 }
399 void vout_ControlChangeCropWindow(vout_thread_t *vout,
400                                   int x, int y, int width, int height)
401 {
402     vout_control_cmd_t cmd;
403     vout_control_cmd_Init(&cmd, VOUT_CONTROL_CROP_WINDOW);
404     cmd.u.window.x      = x;
405     cmd.u.window.y      = y;
406     cmd.u.window.width  = width;
407     cmd.u.window.height = height;
408
409     vout_control_Push(&vout->p->control, &cmd);
410 }
411 void vout_ControlChangeCropBorder(vout_thread_t *vout,
412                                   int left, int top, int right, int bottom)
413 {
414     vout_control_cmd_t cmd;
415     vout_control_cmd_Init(&cmd, VOUT_CONTROL_CROP_BORDER);
416     cmd.u.border.left   = left;
417     cmd.u.border.top    = top;
418     cmd.u.border.right  = right;
419     cmd.u.border.bottom = bottom;
420
421     vout_control_Push(&vout->p->control, &cmd);
422 }
423 void vout_ControlChangeFilters(vout_thread_t *vout, const char *filters)
424 {
425     vout_control_PushString(&vout->p->control, VOUT_CONTROL_CHANGE_FILTERS,
426                             filters);
427 }
428 void vout_ControlChangeSubFilters(vout_thread_t *vout, const char *filters)
429 {
430     vout_control_PushString(&vout->p->control, VOUT_CONTROL_CHANGE_SUB_FILTERS,
431                             filters);
432 }
433
434 /* */
435 static void VoutGetDisplayCfg(vout_thread_t *vout, vout_display_cfg_t *cfg, const char *title)
436 {
437     /* Load configuration */
438     cfg->is_fullscreen = var_CreateGetBool(vout, "fullscreen");
439     cfg->display.title = title;
440     const int display_width = var_CreateGetInteger(vout, "width");
441     const int display_height = var_CreateGetInteger(vout, "height");
442     cfg->display.width   = display_width > 0  ? display_width  : 0;
443     cfg->display.height  = display_height > 0 ? display_height : 0;
444     cfg->is_display_filled  = var_CreateGetBool(vout, "autoscale");
445     cfg->display.sar.num = 1; /* TODO monitor AR */
446     cfg->display.sar.den = 1;
447     unsigned zoom_den = 1000;
448     unsigned zoom_num = zoom_den * var_CreateGetFloat(vout, "scale");
449     vlc_ureduce(&zoom_num, &zoom_den, zoom_num, zoom_den, 0);
450     cfg->zoom.num = zoom_num;
451     cfg->zoom.den = zoom_den;
452     cfg->align.vertical = VOUT_DISPLAY_ALIGN_CENTER;
453     cfg->align.horizontal = VOUT_DISPLAY_ALIGN_CENTER;
454     const int align_mask = var_CreateGetInteger(vout, "align");
455     if (align_mask & 0x1)
456         cfg->align.horizontal = VOUT_DISPLAY_ALIGN_LEFT;
457     else if (align_mask & 0x2)
458         cfg->align.horizontal = VOUT_DISPLAY_ALIGN_RIGHT;
459     if (align_mask & 0x4)
460         cfg->align.horizontal = VOUT_DISPLAY_ALIGN_TOP;
461     else if (align_mask & 0x8)
462         cfg->align.horizontal = VOUT_DISPLAY_ALIGN_BOTTOM;
463 }
464
465 vout_window_t * vout_NewDisplayWindow(vout_thread_t *vout, vout_display_t *vd,
466                                       const vout_window_cfg_t *cfg)
467 {
468     VLC_UNUSED(vd);
469     vout_window_cfg_t cfg_override = *cfg;
470
471     if (!var_InheritBool( vout, "embedded-video"))
472         cfg_override.is_standalone = true;
473
474     if (vout->p->window.is_unused && vout->p->window.object) {
475         assert(!vout->p->splitter_name);
476         if (!cfg_override.is_standalone == !vout->p->window.cfg.is_standalone &&
477             cfg_override.type           == vout->p->window.cfg.type) {
478             /* Reuse the stored window */
479             msg_Dbg(vout, "Reusing previous vout window");
480             vout_window_t *window = vout->p->window.object;
481             if (cfg_override.width  != vout->p->window.cfg.width ||
482                 cfg_override.height != vout->p->window.cfg.height)
483                 vout_window_SetSize(window,
484                                     cfg_override.width, cfg_override.height);
485             vout->p->window.is_unused = false;
486             vout->p->window.cfg       = cfg_override;
487             return window;
488         }
489
490         vout_window_Delete(vout->p->window.object);
491         vout->p->window.is_unused = true;
492         vout->p->window.object    = NULL;
493     }
494
495     vout_window_t *window = vout_window_New(VLC_OBJECT(vout), NULL,
496                                             &cfg_override);
497     if (!window)
498         return NULL;
499     if (!vout->p->splitter_name) {
500         vout->p->window.is_unused = false;
501         vout->p->window.cfg       = cfg_override;
502         vout->p->window.object    = window;
503     }
504     return window;
505 }
506
507 void vout_DeleteDisplayWindow(vout_thread_t *vout, vout_display_t *vd,
508                               vout_window_t *window)
509 {
510     VLC_UNUSED(vd);
511     if (!vout->p->window.is_unused && vout->p->window.object == window) {
512         vout->p->window.is_unused = true;
513     } else if (vout->p->window.is_unused && vout->p->window.object && !window) {
514         vout_window_Delete(vout->p->window.object);
515         vout->p->window.is_unused = true;
516         vout->p->window.object    = NULL;
517     } else if (window) {
518         vout_window_Delete(window);
519     }
520 }
521
522 /* */
523 static picture_t *VoutVideoFilterNewPicture(filter_t *filter)
524 {
525     vout_thread_t *vout = (vout_thread_t*)filter->p_owner;
526     return picture_pool_Get(vout->p->private_pool);
527 }
528 static void VoutVideoFilterDelPicture(filter_t *filter, picture_t *picture)
529 {
530     VLC_UNUSED(filter);
531     picture_Release(picture);
532 }
533 static int VoutVideoFilterAllocationSetup(filter_t *filter, void *data)
534 {
535     filter->pf_video_buffer_new = VoutVideoFilterNewPicture;
536     filter->pf_video_buffer_del = VoutVideoFilterDelPicture;
537     filter->p_owner             = data; /* vout */
538     return VLC_SUCCESS;
539 }
540
541 /* */
542 static int ThreadDisplayPicture(vout_thread_t *vout,
543                                 bool now, mtime_t *deadline)
544 {
545     vout_display_t *vd = vout->p->display.vd;
546     int displayed_count = 0;
547     int lost_count = 0;
548
549     for (;;) {
550         const mtime_t date = mdate();
551         const bool is_paused = vout->p->pause.is_on;
552         bool redisplay = is_paused && !now && vout->p->displayed.decoded;
553         bool is_forced;
554
555         /* FIXME/XXX we must redisplay the last decoded picture (because
556          * of potential vout updated, or filters update or SPU update)
557          * For now a high update period is needed but it coulmd be removed
558          * if and only if:
559          * - vout module emits events from theselves.
560          * - *and* SPU is modified to emit an event or a deadline when needed.
561          *
562          * So it will be done latter.
563          */
564         if (!redisplay) {
565             picture_t *peek = picture_fifo_Peek(vout->p->decoder_fifo);
566             if (peek) {
567                 is_forced = peek->b_force || is_paused || now;
568                 *deadline = (is_forced ? date : peek->date) - vout_chrono_GetHigh(&vout->p->render);
569                 picture_Release(peek);
570             } else {
571                 redisplay = true;
572             }
573         }
574         if (redisplay) {
575              /* FIXME a better way for this delay is needed */
576             const mtime_t date_update = vout->p->displayed.date + VOUT_REDISPLAY_DELAY;
577             if (date_update > date || !vout->p->displayed.decoded) {
578                 *deadline = vout->p->displayed.decoded ? date_update : VLC_TS_INVALID;
579                 break;
580             }
581             /* */
582             is_forced = true;
583             *deadline = date - vout_chrono_GetHigh(&vout->p->render);
584         }
585         if (*deadline > VOUT_MWAIT_TOLERANCE)
586             *deadline -= VOUT_MWAIT_TOLERANCE;
587
588         /* If we are too early and can wait, do it */
589         if (date < *deadline && !now)
590             break;
591
592         picture_t *decoded;
593         if (redisplay) {
594             decoded = vout->p->displayed.decoded;
595             vout->p->displayed.decoded = NULL;
596         } else {
597             decoded = picture_fifo_Pop(vout->p->decoder_fifo);
598             assert(decoded);
599             if (!is_forced && !vout->p->is_late_dropped) {
600                 const mtime_t predicted = date + vout_chrono_GetLow(&vout->p->render);
601                 const mtime_t late = predicted - decoded->date;
602                 if (late > 0) {
603                     msg_Dbg(vout, "picture might be displayed late (missing %d ms)", (int)(late/1000));
604                     if (late > VOUT_DISPLAY_LATE_THRESHOLD) {
605                         msg_Warn(vout, "rejected picture because of render time");
606                         /* TODO */
607                         picture_Release(decoded);
608                         lost_count++;
609                         break;
610                     }
611                 }
612             }
613
614             vout->p->displayed.is_interlaced = !decoded->b_progressive;
615             vout->p->displayed.qtype         = decoded->i_qtype;
616         }
617         vout->p->displayed.timestamp = decoded->date;
618
619         /* */
620         if (vout->p->displayed.decoded)
621             picture_Release(vout->p->displayed.decoded);
622         picture_Hold(decoded);
623         vout->p->displayed.decoded = decoded;
624
625         /* */
626         vout_chrono_Start(&vout->p->render);
627
628         picture_t *filtered = NULL;
629         if (decoded) {
630             vlc_mutex_lock(&vout->p->vfilter_lock);
631             filtered = filter_chain_VideoFilter(vout->p->vfilter_chain, decoded);
632             //assert(filtered == decoded); // TODO implement
633             vlc_mutex_unlock(&vout->p->vfilter_lock);
634             if (!filtered)
635                 continue;
636         }
637
638         /*
639          * Check for subpictures to display
640          */
641         const bool do_snapshot = vout_snapshot_IsRequested(&vout->p->snapshot);
642         mtime_t spu_render_time = is_forced ? mdate() : filtered->date;
643         if (vout->p->pause.is_on)
644             spu_render_time = vout->p->pause.date;
645         else
646             spu_render_time = filtered->date > 1 ? filtered->date : mdate();
647
648         subpicture_t *subpic = spu_SortSubpictures(vout->p->p_spu,
649                                                    spu_render_time,
650                                                    do_snapshot);
651         /*
652          * Perform rendering
653          *
654          * We have to:
655          * - be sure to end up with a direct buffer.
656          * - blend subtitles, and in a fast access buffer
657          */
658         picture_t *direct = NULL;
659         if (filtered &&
660             (vout->p->decoder_pool != vout->p->display_pool || subpic)) {
661             picture_t *render;
662             if (vout->p->is_decoder_pool_slow)
663                 render = picture_NewFromFormat(&vd->source);
664             else if (vout->p->decoder_pool != vout->p->display_pool)
665                 render = picture_pool_Get(vout->p->display_pool);
666             else
667                 render = picture_pool_Get(vout->p->private_pool);
668
669             if (render) {
670                 picture_Copy(render, filtered);
671
672                 spu_RenderSubpictures(vout->p->p_spu,
673                                       render, &vd->source,
674                                       subpic, &vd->source, spu_render_time);
675             }
676             if (vout->p->is_decoder_pool_slow) {
677                 direct = picture_pool_Get(vout->p->display_pool);
678                 if (direct)
679                     picture_Copy(direct, render);
680                 picture_Release(render);
681
682             } else {
683                 direct = render;
684             }
685             picture_Release(filtered);
686             filtered = NULL;
687         } else {
688             direct = filtered;
689         }
690
691         /*
692          * Take a snapshot if requested
693          */
694         if (direct && do_snapshot)
695             vout_snapshot_Set(&vout->p->snapshot, &vd->source, direct);
696
697         /* Render the direct buffer returned by vout_RenderPicture */
698         if (direct) {
699             vout_RenderWrapper(vout, direct);
700
701             vout_chrono_Stop(&vout->p->render);
702 #if 0
703             {
704             static int i = 0;
705             if (((i++)%10) == 0)
706                 msg_Info(vout, "render: avg %d ms var %d ms",
707                          (int)(vout->p->render.avg/1000), (int)(vout->p->render.var/1000));
708             }
709 #endif
710         }
711
712         /* Wait the real date (for rendering jitter) */
713         if (!is_forced)
714             mwait(decoded->date);
715
716         /* Display the direct buffer returned by vout_RenderPicture */
717         vout->p->displayed.date = mdate();
718         if (direct)
719             vout_DisplayWrapper(vout, direct);
720
721         displayed_count++;
722         break;
723     }
724
725     vout_statistic_Update(&vout->p->statistic, displayed_count, lost_count);
726     if (displayed_count <= 0)
727         return VLC_EGENERIC;
728     return VLC_SUCCESS;
729 }
730
731 static void ThreadManage(vout_thread_t *vout,
732                          mtime_t *deadline,
733                          vout_interlacing_support_t *interlacing,
734                          vout_postprocessing_support_t *postprocessing)
735 {
736     vlc_mutex_lock(&vout->p->picture_lock);
737
738     *deadline = VLC_TS_INVALID;
739     ThreadDisplayPicture(vout, false, deadline);
740
741     const int  picture_qtype      = vout->p->displayed.qtype;
742     const bool picture_interlaced = vout->p->displayed.is_interlaced;
743
744     vlc_mutex_unlock(&vout->p->picture_lock);
745
746     /* Post processing */
747     vout_SetPostProcessingState(vout, postprocessing, picture_qtype);
748
749     /* Deinterlacing */
750     vout_SetInterlacingState(vout, interlacing, picture_interlaced);
751
752     vout_ManageWrapper(vout);
753 }
754
755 static void ThreadDisplayOsdTitle(vout_thread_t *vout, const char *string)
756 {
757     if (!vout->p->title.show)
758         return;
759
760     vout_OSDText(vout, SPU_DEFAULT_CHANNEL,
761                  vout->p->title.position, INT64_C(1000) * vout->p->title.timeout,
762                  string);
763 }
764
765 static void ThreadChangeFilters(vout_thread_t *vout, const char *filters)
766 {
767     es_format_t fmt;
768     es_format_Init(&fmt, VIDEO_ES, vout->p->original.i_chroma);
769     fmt.video = vout->p->original;
770
771     vlc_mutex_lock(&vout->p->vfilter_lock);
772
773     filter_chain_Reset(vout->p->vfilter_chain, &fmt, &fmt);
774     if (filter_chain_AppendFromString(vout->p->vfilter_chain,
775                                       filters) < 0)
776         msg_Err(vout, "Video filter chain creation failed");
777
778     vlc_mutex_unlock(&vout->p->vfilter_lock);
779 }
780
781 static void ThreadChangeSubFilters(vout_thread_t *vout, const char *filters)
782 {
783     spu_ChangeFilters(vout->p->p_spu, filters);
784 }
785
786 static void ThreadChangePause(vout_thread_t *vout, bool is_paused, mtime_t date)
787 {
788     assert(!vout->p->pause.is_on || !is_paused);
789
790     if (vout->p->pause.is_on) {
791         const mtime_t duration = date - vout->p->pause.date;
792
793         if (vout->p->step.timestamp > VLC_TS_INVALID)
794             vout->p->step.timestamp += duration;
795         if (vout->p->step.last > VLC_TS_INVALID)
796             vout->p->step.last += duration;
797         picture_fifo_OffsetDate(vout->p->decoder_fifo, duration);
798         if (vout->p->displayed.decoded)
799             vout->p->displayed.decoded->date += duration;
800
801         spu_OffsetSubtitleDate(vout->p->p_spu, duration);
802     } else {
803         vout->p->step.timestamp = VLC_TS_INVALID;
804         vout->p->step.last      = VLC_TS_INVALID;
805     }
806     vout->p->pause.is_on = is_paused;
807     vout->p->pause.date  = date;
808 }
809
810 static void ThreadFlush(vout_thread_t *vout, bool below, mtime_t date)
811 {
812     vout->p->step.timestamp = VLC_TS_INVALID;
813     vout->p->step.last      = VLC_TS_INVALID;
814
815     picture_t *last = vout->p->displayed.decoded;
816     if (last) {
817         if (( below && last->date <= date) ||
818             (!below && last->date >= date)) {
819             picture_Release(last);
820
821             vout->p->displayed.decoded   = NULL;
822             vout->p->displayed.date      = VLC_TS_INVALID;
823             vout->p->displayed.timestamp = VLC_TS_INVALID;
824         }
825     }
826     picture_fifo_Flush(vout->p->decoder_fifo, date, below);
827 }
828
829 static void ThreadReset(vout_thread_t *vout)
830 {
831     ThreadFlush(vout, true, INT64_MAX);
832     if (vout->p->decoder_pool)
833         picture_pool_NonEmpty(vout->p->decoder_pool, true);
834     vout->p->pause.is_on = false;
835     vout->p->pause.date  = mdate();
836 }
837
838 static void ThreadStep(vout_thread_t *vout, mtime_t *duration)
839 {
840     *duration = 0;
841
842     if (vout->p->step.last <= VLC_TS_INVALID)
843         vout->p->step.last = vout->p->displayed.timestamp;
844
845     mtime_t dummy;
846     if (ThreadDisplayPicture(vout, true, &dummy))
847         return;
848
849     vout->p->step.timestamp = vout->p->displayed.timestamp;
850
851     if (vout->p->step.last > VLC_TS_INVALID &&
852         vout->p->step.timestamp > vout->p->step.last) {
853         *duration = vout->p->step.timestamp - vout->p->step.last;
854         vout->p->step.last = vout->p->step.timestamp;
855         /* TODO advance subpicture by the duration ... */
856     }
857 }
858
859 static void ThreadChangeFullscreen(vout_thread_t *vout, bool fullscreen)
860 {
861     /* FIXME not sure setting "fullscreen" is good ... */
862     var_SetBool(vout, "fullscreen", fullscreen);
863     vout_SetDisplayFullscreen(vout->p->display.vd, fullscreen);
864 }
865
866 static void ThreadChangeOnTop(vout_thread_t *vout, bool is_on_top)
867 {
868     vout_SetWindowState(vout->p->display.vd,
869                         is_on_top ? VOUT_WINDOW_STATE_ABOVE :
870                                     VOUT_WINDOW_STATE_NORMAL);
871 }
872
873 static void ThreadChangeDisplayFilled(vout_thread_t *vout, bool is_filled)
874 {
875     vout_SetDisplayFilled(vout->p->display.vd, is_filled);
876 }
877
878 static void ThreadChangeZoom(vout_thread_t *vout, int num, int den)
879 {
880     if (num * 10 < den) {
881         num = den;
882         den *= 10;
883     } else if (num > den * 10) {
884         num = den * 10;
885     }
886
887     vout_SetDisplayZoom(vout->p->display.vd, num, den);
888 }
889
890 static void ThreadChangeAspectRatio(vout_thread_t *vout,
891                                     unsigned num, unsigned den)
892 {
893     const video_format_t *source = &vout->p->original;
894
895     if (num > 0 && den > 0) {
896         num *= source->i_visible_height;
897         den *= source->i_visible_width;
898         vlc_ureduce(&num, &den, num, den, 0);
899     }
900     vout_SetDisplayAspect(vout->p->display.vd, num, den);
901 }
902
903
904 static void ThreadExecuteCropWindow(vout_thread_t *vout,
905                                     unsigned crop_num, unsigned crop_den,
906                                     unsigned x, unsigned y,
907                                     unsigned width, unsigned height)
908 {
909     const video_format_t *source = &vout->p->original;
910
911     vout_SetDisplayCrop(vout->p->display.vd,
912                         crop_num, crop_den,
913                         source->i_x_offset + x,
914                         source->i_y_offset + y,
915                         width, height);
916 }
917 static void ThreadExecuteCropBorder(vout_thread_t *vout,
918                                     unsigned left, unsigned top,
919                                     unsigned right, unsigned bottom)
920 {
921     const video_format_t *source = &vout->p->original;
922     ThreadExecuteCropWindow(vout, 0, 0,
923                             left,
924                             top,
925                             /* At worst, it becomes < 0 (but unsigned) and will be rejected */
926                             source->i_visible_width  - (left + right),
927                             source->i_visible_height - (top  + bottom));
928 }
929
930 static void ThreadExecuteCropRatio(vout_thread_t *vout,
931                                    unsigned num, unsigned den)
932 {
933     const video_format_t *source = &vout->p->original;
934     ThreadExecuteCropWindow(vout, num, den,
935                             0, 0,
936                             source->i_visible_width,
937                             source->i_visible_height);
938 }
939
940 static int ThreadStart(vout_thread_t *vout, const vout_display_state_t *state)
941 {
942     vlc_mouse_Init(&vout->p->mouse);
943     vout->p->decoder_fifo = picture_fifo_New();
944     vout->p->decoder_pool = NULL;
945     vout->p->display_pool = NULL;
946     vout->p->private_pool = NULL;
947
948     vout->p->vfilter_chain =
949         filter_chain_New( vout, "video filter2", false,
950                           VoutVideoFilterAllocationSetup, NULL, vout);
951
952     vout_display_state_t state_default;
953     if (!state) {
954         VoutGetDisplayCfg(vout, &state_default.cfg, vout->p->display.title);
955         state_default.wm_state = var_CreateGetBool(vout, "video-on-top") ? VOUT_WINDOW_STATE_ABOVE :
956                                                                            VOUT_WINDOW_STATE_NORMAL;
957         state_default.sar.num = 0;
958         state_default.sar.den = 0;
959
960         state = &state_default;
961     }
962
963     if (vout_OpenWrapper(vout, vout->p->splitter_name, state))
964         return VLC_EGENERIC;
965     if (vout_InitWrapper(vout))
966         return VLC_EGENERIC;
967     assert(vout->p->decoder_pool);
968
969     vout->p->displayed.decoded       = NULL;
970     vout->p->displayed.date          = VLC_TS_INVALID;
971     vout->p->displayed.decoded       = NULL;
972     vout->p->displayed.timestamp     = VLC_TS_INVALID;
973     vout->p->displayed.qtype         = QTYPE_NONE;
974     vout->p->displayed.is_interlaced = false;
975
976     vout->p->step.last               = VLC_TS_INVALID;
977     vout->p->step.timestamp          = VLC_TS_INVALID;
978
979     video_format_Print(VLC_OBJECT(vout), "original format", &vout->p->original);
980     return VLC_SUCCESS;
981 }
982
983 static void ThreadStop(vout_thread_t *vout, vout_display_state_t *state)
984 {
985     /* Destroy the video filters2 */
986     filter_chain_Delete(vout->p->vfilter_chain);
987
988     /* Destroy translation tables */
989     if (vout->p->display.vd) {
990         if (vout->p->decoder_pool) {
991             ThreadFlush(vout, true, INT64_MAX);
992             vout_EndWrapper(vout);
993         }
994         vout_CloseWrapper(vout, state);
995     }
996
997     if (vout->p->decoder_fifo)
998         picture_fifo_Delete(vout->p->decoder_fifo);
999     assert(!vout->p->decoder_pool);
1000 }
1001
1002 static void ThreadInit(vout_thread_t *vout)
1003 {
1004     vout->p->window.is_unused = true;
1005     vout->p->window.object    = NULL;
1006     vout->p->dead             = false;
1007     vout->p->is_late_dropped  = var_InheritBool(vout, "drop-late-frames");
1008     vout->p->pause.is_on      = false;
1009     vout->p->pause.date       = VLC_TS_INVALID;
1010
1011     vout_chrono_Init(&vout->p->render, 5, 10000); /* Arbitrary initial time */
1012 }
1013
1014 static void ThreadClean(vout_thread_t *vout)
1015 {
1016     if (vout->p->window.object) {
1017         assert(vout->p->window.is_unused);
1018         vout_window_Delete(vout->p->window.object);
1019     }
1020     vout_chrono_Clean(&vout->p->render);
1021     vout->p->dead = true;
1022     vout_control_Dead(&vout->p->control);
1023 }
1024
1025 static int ThreadReinit(vout_thread_t *vout,
1026                         const vout_configuration_t *cfg)
1027 {
1028     video_format_t original;
1029     if (VoutValidateFormat(&original, cfg->fmt)) {
1030         ThreadStop(vout, NULL);
1031         ThreadClean(vout);
1032         return VLC_EGENERIC;
1033     }
1034     if (video_format_IsSimilar(&original, &vout->p->original)) {
1035         if (cfg->dpb_size <= vout->p->dpb_size)
1036             return VLC_SUCCESS;
1037         msg_Warn(vout, "DPB need to be increased");
1038     }
1039
1040     vout_display_state_t state;
1041     memset(&state, 0, sizeof(state));
1042
1043     ThreadStop(vout, &state);
1044
1045     if (!state.cfg.is_fullscreen) {
1046         state.cfg.display.width  = 0;
1047         state.cfg.display.height = 0;
1048     }
1049     state.sar.num = 0;
1050     state.sar.den = 0;
1051     /* FIXME current vout "variables" are not in sync here anymore
1052      * and I am not sure what to do */
1053
1054     vout->p->original = original;
1055     vout->p->dpb_size = cfg->dpb_size;
1056     if (ThreadStart(vout, &state)) {
1057         ThreadClean(vout);
1058         return VLC_EGENERIC;
1059     }
1060     return VLC_SUCCESS;
1061 }
1062
1063 /*****************************************************************************
1064  * Thread: video output thread
1065  *****************************************************************************
1066  * Video output thread. This function does only returns when the thread is
1067  * terminated. It handles the pictures arriving in the video heap and the
1068  * display device events.
1069  *****************************************************************************/
1070 static void *Thread(void *object)
1071 {
1072     vout_thread_t *vout = object;
1073
1074     vout_interlacing_support_t interlacing = {
1075         .is_interlaced = false,
1076         .date = mdate(),
1077     };
1078     vout_postprocessing_support_t postprocessing = {
1079         .qtype = QTYPE_NONE,
1080     };
1081
1082     mtime_t deadline = VLC_TS_INVALID;
1083     for (;;) {
1084         vout_control_cmd_t cmd;
1085
1086         /* FIXME remove thoses ugly timeouts
1087          */
1088         while (!vout_control_Pop(&vout->p->control, &cmd, deadline, 100000)) {
1089             switch(cmd.type) {
1090             case VOUT_CONTROL_INIT:
1091                 ThreadInit(vout);
1092                 if (ThreadStart(vout, NULL)) {
1093                     ThreadStop(vout, NULL);
1094                     ThreadClean(vout);
1095                     return NULL;
1096                 }
1097                 break;
1098             case VOUT_CONTROL_CLEAN:
1099                 ThreadStop(vout, NULL);
1100                 ThreadClean(vout);
1101                 return NULL;
1102             case VOUT_CONTROL_REINIT:
1103                 if (ThreadReinit(vout, cmd.u.cfg))
1104                     return NULL;
1105                 break;
1106             case VOUT_CONTROL_OSD_TITLE:
1107                 ThreadDisplayOsdTitle(vout, cmd.u.string);
1108                 break;
1109             case VOUT_CONTROL_CHANGE_FILTERS:
1110                 ThreadChangeFilters(vout, cmd.u.string);
1111                 break;
1112             case VOUT_CONTROL_CHANGE_SUB_FILTERS:
1113                 ThreadChangeSubFilters(vout, cmd.u.string);
1114                 break;
1115             case VOUT_CONTROL_PAUSE:
1116                 ThreadChangePause(vout, cmd.u.pause.is_on, cmd.u.pause.date);
1117                 break;
1118             case VOUT_CONTROL_FLUSH:
1119                 ThreadFlush(vout, false, cmd.u.time);
1120                 break;
1121             case VOUT_CONTROL_RESET:
1122                 ThreadReset(vout);
1123                 break;
1124             case VOUT_CONTROL_STEP:
1125                 ThreadStep(vout, cmd.u.time_ptr);
1126                 break;
1127             case VOUT_CONTROL_FULLSCREEN:
1128                 ThreadChangeFullscreen(vout, cmd.u.boolean);
1129                 break;
1130             case VOUT_CONTROL_ON_TOP:
1131                 ThreadChangeOnTop(vout, cmd.u.boolean);
1132                 break;
1133             case VOUT_CONTROL_DISPLAY_FILLED:
1134                 ThreadChangeDisplayFilled(vout, cmd.u.boolean);
1135                 break;
1136             case VOUT_CONTROL_ZOOM:
1137                 ThreadChangeZoom(vout, cmd.u.pair.a, cmd.u.pair.b);
1138                 break;
1139             case VOUT_CONTROL_ASPECT_RATIO:
1140                 ThreadChangeAspectRatio(vout, cmd.u.pair.a, cmd.u.pair.b);
1141                 break;
1142            case VOUT_CONTROL_CROP_RATIO:
1143                 ThreadExecuteCropRatio(vout, cmd.u.pair.a, cmd.u.pair.b);
1144                 break;
1145             case VOUT_CONTROL_CROP_WINDOW:
1146                 ThreadExecuteCropWindow(vout, 0, 0,
1147                                         cmd.u.window.x, cmd.u.window.y,
1148                                         cmd.u.window.width, cmd.u.window.height);
1149                 break;
1150             case VOUT_CONTROL_CROP_BORDER:
1151                 ThreadExecuteCropBorder(vout,
1152                                         cmd.u.border.left,  cmd.u.border.top,
1153                                         cmd.u.border.right, cmd.u.border.bottom);
1154                 break;
1155             default:
1156                 break;
1157             }
1158             vout_control_cmd_Clean(&cmd);
1159         }
1160
1161         ThreadManage(vout, &deadline, &interlacing, &postprocessing);
1162     }
1163 }
1164