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