forked from jojo61/vdr-plugin-softhdcuvid
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvideo.c
7366 lines (6417 loc) · 230 KB
/
video.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
///
/// @file video.c @brief Video module
///
/// Copyright (c) 2009 - 2015 by Johns. All Rights Reserved.
///
/// Contributor(s):
///
/// License: AGPLv3
///
/// This program is free software: you can redistribute it and/or modify
/// it under the terms of the GNU Affero General Public License as
/// published by the Free Software Foundation, either version 3 of the
/// License.
///
/// This program is distributed in the hope that it will be useful,
/// but WITHOUT ANY WARRANTY; without even the implied warranty of
/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
/// GNU Affero General Public License for more details.
///
/// $Id: bacf89f24503be74d113a83139a277ff2290014a $
//////////////////////////////////////////////////////////////////////////////
///
/// @defgroup Video The video module.
///
/// This module contains all video rendering functions.
///
/// @todo disable screen saver support
///
/// Uses Xlib where it is needed for VA-API or cuvid. XCB is used for
/// everything else.
///
/// - X11
/// - OpenGL rendering
/// - OpenGL rendering with GLX texture-from-pixmap
/// - Xrender rendering
///
/// @todo FIXME: use vaErrorStr for all VA-API errors.
///
#define USE_XLIB_XCB ///< use xlib/xcb backend
#define noUSE_SCREENSAVER ///< support disable screensaver
#define USE_GRAB ///< experimental grab code
// #define USE_GLX ///< outdated GLX code
#define USE_DOUBLEBUFFER ///< use GLX double buffers
#define USE_CUVID ///< enable cuvid support
// #define AV_INFO ///< log a/v sync informations
#ifndef AV_INFO_TIME
#define AV_INFO_TIME (50 * 60) ///< a/v info every minute
#endif
#define USE_VIDEO_THREAD ///< run decoder in an own thread
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/prctl.h>
#include <sys/shm.h>
#include <sys/time.h>
#include <errno.h> /* ERROR Number Definitions */
#include <fcntl.h> /* File Control Definitions */
#include <sys/ioctl.h> /* ioctl() */
#include <termios.h> /* POSIX Terminal Control Definitions */
#include <unistd.h> /* UNIX Standard Definitions */
#include <math.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <libintl.h>
#define _(str) gettext(str) ///< gettext shortcut
#define _N(str) str ///< gettext_noop shortcut
#ifdef USE_VIDEO_THREAD
#ifndef __USE_GNU
#define __USE_GNU
#endif
#include <pthread.h>
#include <signal.h>
#include <time.h>
#ifndef HAVE_PTHREAD_NAME
/// only available with newer glibc
#define pthread_setname_np(thread, name)
#endif
#endif
#ifdef USE_XLIB_XCB
#include <X11/Xlib-xcb.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/keysym.h>
#include <xcb/xcb.h>
#ifdef USE_SCREENSAVER
#include <xcb/dpms.h>
#include <xcb/screensaver.h>
#endif
// #include <xcb/shm.h>
// #include <xcb/xv.h>
// #include <xcb/xcb_image.h>
// #include <xcb/xcb_event.h>
// #include <xcb/xcb_atom.h>
#include <xcb/xcb_icccm.h>
#ifdef XCB_ICCCM_NUM_WM_SIZE_HINTS_ELEMENTS
#include <xcb/xcb_ewmh.h>
#else // compatibility hack for old xcb-util
/**
* @brief Action on the _NET_WM_STATE property
*/
typedef enum {
/* Remove/unset property */
XCB_EWMH_WM_STATE_REMOVE = 0,
/* Add/set property */
XCB_EWMH_WM_STATE_ADD = 1,
/* Toggle property */
XCB_EWMH_WM_STATE_TOGGLE = 2
} xcb_ewmh_wm_state_action_t;
#endif
#endif
#ifdef USE_GLX
#ifndef PLACEBO_GL
#include <GL/glew.h>
#else
#include <epoxy/egl.h>
#endif
// clang-format off
#include <GL/glu.h>
#include <GL/glut.h>
#include <GL/freeglut_ext.h>
// clang-format on
#endif
#include <libavcodec/avcodec.h>
#include <libavutil/hwcontext.h>
#include <libavutil/mastering_display_metadata.h>
#include <libavutil/pixdesc.h>
#ifdef CUVID
// clang-format off
#include <ffnvcodec/dynlink_cuda.h>
#include <ffnvcodec/dynlink_loader.h>
#include <libavutil/hwcontext_cuda.h>
#include "drvapi_error_string.h"
// clang-format on
#define __DEVICE_TYPES_H__
#endif
#ifdef VAAPI
#if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(57, 74, 100)
#include <libavcodec/vaapi.h>
#endif
#include <libavutil/hwcontext_vaapi.h>
#include <libdrm/drm_fourcc.h>
#include <va/va_drmcommon.h>
#define TO_AVHW_DEVICE_CTX(x) ((AVHWDeviceContext *)x->data)
#define TO_AVHW_FRAMES_CTX(x) ((AVHWFramesContext *)x->data)
#define TO_VAAPI_DEVICE_CTX(x) ((AVVAAPIDeviceContext *)TO_AVHW_DEVICE_CTX(x)->hwctx)
#define TO_VAAPI_FRAMES_CTX(x) ((AVVAAPIFramesContext *)TO_AVHW_FRAMES_CTX(x)->hwctx)
#endif
#include <assert.h>
// #define EGL_EGLEXT_PROTOTYPES
#if !defined PLACEBO_GL
#include <EGL/egl.h>
#include <EGL/eglext.h>
#endif
#ifndef GL_OES_EGL_image
typedef void *GLeglImageOES;
#endif
#ifndef EGL_KHR_image
typedef void *EGLImageKHR;
#endif
#ifdef PLACEBO
#ifdef PLACEBO_GL
#include <libplacebo/opengl.h>
#else
#define VK_USE_PLATFORM_XCB_KHR
#include <libplacebo/vulkan.h>
#endif
#if PL_API_VER >= 113
#include <libplacebo/shaders/lut.h>
#endif
#include <libplacebo/renderer.h>
#endif
#include <libswscale/swscale.h>
#if defined(YADIF) || defined(VAAPI)
#include <libavfilter/buffersink.h>
#include <libavfilter/buffersrc.h>
#include <libavutil/opt.h>
#endif
// clang-format off
#include "iatomic.h" // portable atomic_t
#include "misc.h"
#include "video.h"
#include "audio.h"
#include "codec.h"
// clang-format on
#if defined(APIVERSNUM) && APIVERSNUM < 20400
#error "VDR 2.4.0 or greater is required!"
#endif
#define HAS_FFMPEG_3_4_API (LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(57, 107, 100))
#define HAS_FFMPEG_4_API (LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(58, 18, 100))
#if !HAS_FFMPEG_3_4_API
#error "FFmpeg 3.4 or greater is required!"
#endif
//----------------------------------------------------------------------------
// Declarations
//----------------------------------------------------------------------------
///
/// Video resolutions selector.
///
typedef enum _video_resolutions_ {
VideoResolution576i, ///< ...x576 interlaced
VideoResolution720p, ///< ...x720 progressive
VideoResolutionFake1080i, ///< 1280x1080 1440x1080 interlaced
VideoResolution1080i, ///< 1920x1080 interlaced
VideoResolutionUHD, /// UHD progressive
VideoResolutionMax ///< number of resolution indexs
} VideoResolutions;
///
/// Video deinterlace modes.
///
typedef enum _video_deinterlace_modes_ {
VideoDeinterlaceCuda, ///< Cuda build in deinterlace
VideoDeinterlaceYadif, ///< Yadif deinterlace
} VideoDeinterlaceModes;
///
/// Video scaleing modes.
///
typedef enum _video_scaling_modes_ {
VideoScalingNormal, ///< normal scaling
VideoScalingFast, ///< fastest scaling
VideoScalingHQ, ///< high quality scaling
VideoScalingAnamorphic, ///< anamorphic scaling
} VideoScalingModes;
///
/// Video zoom modes.
///
typedef enum _video_zoom_modes_ {
VideoNormal, ///< normal
VideoStretch, ///< stretch to all edges
VideoCenterCutOut, ///< center and cut out
VideoNone, ///< no scaling
} VideoZoomModes;
///
/// Video color space conversions.
///
typedef enum _video_color_space_ {
VideoColorSpaceNone, ///< no conversion
VideoColorSpaceBt601, ///< ITU.BT-601 Y'CbCr
VideoColorSpaceBt709, ///< ITU.BT-709 HDTV Y'CbCr
VideoColorSpaceSmpte240 ///< SMPTE-240M Y'PbPr
} VideoColorSpace;
///
/// Video output module structure and typedef.
///
typedef struct _video_module_ {
const char *Name; ///< video output module name
char Enabled; ///< flag output module enabled
/// allocate new video hw decoder
VideoHwDecoder *(*const NewHwDecoder)(VideoStream *);
void (*const DelHwDecoder)(VideoHwDecoder *);
unsigned (*const GetSurface)(VideoHwDecoder *, const AVCodecContext *);
void (*const ReleaseSurface)(VideoHwDecoder *, unsigned);
enum AVPixelFormat (*const get_format)(VideoHwDecoder *, AVCodecContext *, const enum AVPixelFormat *);
void (*const RenderFrame)(VideoHwDecoder *, const AVCodecContext *, const AVFrame *);
void *(*const GetHwAccelContext)(VideoHwDecoder *);
void (*const SetClock)(VideoHwDecoder *, int64_t);
int64_t (*const GetClock)(const VideoHwDecoder *);
void (*const SetClosing)(const VideoHwDecoder *);
void (*const ResetStart)(const VideoHwDecoder *);
void (*const SetTrickSpeed)(const VideoHwDecoder *, int);
uint8_t *(*const GrabOutput)(int *, int *, int *, int);
void (*const GetStats)(VideoHwDecoder *, int *, int *, int *, int *, float *, int *, int *, int *, int *);
void (*const SetBackground)(uint32_t);
void (*const SetVideoMode)(void);
/// module display handler thread
void (*const DisplayHandlerThread)(void);
void (*const OsdClear)(void); ///< clear OSD
/// draw OSD ARGB area
void (*const OsdDrawARGB)(int, int, int, int, int, const uint8_t *, int, int);
void (*const OsdInit)(int, int); ///< initialize OSD
void (*const OsdExit)(void); ///< cleanup OSD
int (*const Init)(const char *); ///< initialize video output module
void (*const Exit)(void); ///< cleanup video output module
} VideoModule;
typedef struct {
/** Left X co-ordinate. Inclusive. */
uint32_t x0;
/** Top Y co-ordinate. Inclusive. */
uint32_t y0;
/** Right X co-ordinate. Exclusive. */
uint32_t x1;
/** Bottom Y co-ordinate. Exclusive. */
uint32_t y1;
} VdpRect;
//----------------------------------------------------------------------------
// Defines
//----------------------------------------------------------------------------
#define CODEC_SURFACES_MAX 12 //
#define VIDEO_SURFACES_MAX 6 ///< video output surfaces for queue
#define NUM_SHADERS 5 // Number of supported user shaders with placebo
#if defined VAAPI
#define PIXEL_FORMAT AV_PIX_FMT_VAAPI
#define SWAP_BUFFER_SIZE 3
#endif
#ifdef CUVID
#define PIXEL_FORMAT AV_PIX_FMT_CUDA
#define SWAP_BUFFER_SIZE 3
#endif
//----------------------------------------------------------------------------
// Variables
//----------------------------------------------------------------------------
AVBufferRef *HwDeviceContext; ///< ffmpeg HW device context
char VideoIgnoreRepeatPict; ///< disable repeat pict warning
int Planes = 2;
unsigned char *posd;
static const char *VideoDriverName = "cuvid"; ///< video output device
static Display *XlibDisplay; ///< Xlib X11 display
static xcb_connection_t *Connection; ///< xcb connection
static xcb_colormap_t VideoColormap; ///< video colormap
static xcb_window_t VideoWindow; ///< video window
static xcb_screen_t const *VideoScreen; ///< video screen
static uint32_t VideoBlankTick; ///< blank cursor timer
static xcb_pixmap_t VideoCursorPixmap; ///< blank curosr pixmap
static xcb_cursor_t VideoBlankCursor; ///< empty invisible cursor
static int VideoWindowX; ///< video output window x coordinate
static int VideoWindowY; ///< video outout window y coordinate
static unsigned VideoWindowWidth; ///< video output window width
static unsigned VideoWindowHeight; ///< video output window height
static const VideoModule NoopModule; ///< forward definition of noop module
/// selected video module
static const VideoModule *VideoUsedModule = &NoopModule;
signed char VideoHardwareDecoder = -1; ///< flag use hardware decoder
static char VideoSurfaceModesChanged; ///< flag surface modes changed
/// flag use transparent OSD.
static const char VideoTransparentOsd = 1;
static uint32_t VideoBackground; ///< video background color
char VideoStudioLevels; ///< flag use studio levels
/// Default deinterlace mode.
static VideoDeinterlaceModes VideoDeinterlace[VideoResolutionMax];
/// Default number of deinterlace surfaces
static const int VideoDeinterlaceSurfaces = 4;
/// Default skip chroma deinterlace flag (CUVID only).
static char VideoSkipChromaDeinterlace[VideoResolutionMax];
/// Default inverse telecine flag (CUVID only).
static char VideoInverseTelecine[VideoResolutionMax];
/// Default amount of noise reduction algorithm to apply (0 .. 1000).
static int VideoDenoise[VideoResolutionMax];
/// Default amount of sharpening, or blurring, to apply (-1000 .. 1000).
static int VideoSharpen[VideoResolutionMax];
/// Default cut top and bottom in pixels
static int VideoCutTopBottom[VideoResolutionMax];
/// Default cut left and right in pixels
static int VideoCutLeftRight[VideoResolutionMax];
/// Default scaling mode
static VideoScalingModes VideoScaling[VideoResolutionMax];
/// Default audio/video delay
int VideoAudioDelay;
/// Default zoom mode for 4:3
static VideoZoomModes Video4to3ZoomMode;
/// Default zoom mode for 16:9 and others
static VideoZoomModes VideoOtherZoomMode;
/// Default Value for DRM Connector
static char *DRMConnector = NULL;
/// Default Value for DRM Refreshrate
static int DRMRefresh = 50;
static char Video60HzMode; ///< handle 60hz displays
static char VideoSoftStartSync; ///< soft start sync audio/video
static const int VideoSoftStartFrames = 100; ///< soft start frames
static char VideoShowBlackPicture; ///< flag show black picture
static float VideoBrightness = 0.0f;
static float VideoContrast = 1.0f;
static float VideoSaturation = 1.0f;
static float VideoHue = 0.0f;
static float VideoGamma = 1.0f;
static float VideoTemperature = 0.0f;
static int VulkanTargetColorSpace = 0;
static int VideoScalerTest = 0;
static int VideoColorBlindness = 0;
static float VideoColorBlindnessFaktor = 1.0f;
static char *shadersp[NUM_SHADERS];
char MyConfigDir[200];
static int num_shaders = 0;
static int LUTon = -1;
static xcb_atom_t WmDeleteWindowAtom; ///< WM delete message atom
static xcb_atom_t NetWmState; ///< wm-state message atom
static xcb_atom_t NetWmStateFullscreen; ///< fullscreen wm-state message atom
static xcb_atom_t NetWmStateAbove;
#ifdef DEBUG
extern uint32_t VideoSwitch; ///< ticks for channel switch
#endif
extern void AudioVideoReady(int64_t); ///< tell audio video is ready
#ifdef USE_VIDEO_THREAD
static pthread_t VideoThread; ///< video decode thread
static pthread_cond_t VideoWakeupCond; ///< wakeup condition variable
static pthread_mutex_t VideoMutex; ///< video condition mutex
pthread_mutex_t VideoLockMutex; ///< video lock mutex
pthread_mutex_t OSDMutex; ///< OSD update mutex
#endif
static pthread_t VideoDisplayThread; ///< video display thread
// static pthread_cond_t VideoDisplayWakeupCond; ///< wakeup condition variable
// static pthread_mutex_t VideoDisplayMutex; ///< video condition mutex
// static pthread_mutex_t VideoDisplayLockMutex; ///< video lock mutex
static int OsdConfigWidth; ///< osd configured width
static int OsdConfigHeight; ///< osd configured height
static char OsdShown; ///< flag show osd
static char Osd3DMode; ///< 3D OSD mode
static int OsdWidth; ///< osd width
static int OsdHeight; ///< osd height
static int OsdDirtyX; ///< osd dirty area x
static int OsdDirtyY; ///< osd dirty area y
static int OsdDirtyWidth; ///< osd dirty area width
static int OsdDirtyHeight; ///< osd dirty area height
static void (*VideoEventCallback)(void) = NULL; /// callback function to notify VDR about Video Events
static int64_t VideoDeltaPTS; ///< FIXME: fix pts
#ifdef USE_SCREENSAVER
static char DPMSDisabled; ///< flag we have disabled dpms
static char EnableDPMSatBlackScreen; ///< flag we should enable dpms at black screen
#endif
static unsigned int Count;
static int EglEnabled; ///< use EGL
static int GlxVSyncEnabled = 1; ///< enable/disable v-sync
#ifdef CUVID
static GLXContext glxSharedContext; ///< shared gl context
static GLXContext glxContext; ///< our gl context
static GLXContext glxThreadContext; ///< our gl context for the thread
static XVisualInfo *GlxVisualInfo; ///< our gl visual
static void GlxSetupWindow(xcb_window_t window, int width, int height, GLXContext context);
GLXContext OSDcontext;
#else
static EGLContext eglSharedContext; ///< shared gl context
static EGLContext eglOSDContext = NULL; ///< our gl context for the thread
static EGLContext eglContext; ///< our gl context
static EGLConfig eglConfig;
static EGLDisplay eglDisplay;
static EGLSurface eglSurface, eglOSDSurface;
static EGLint eglAttrs[10];
static int eglVersion = 2;
static EGLImageKHR(EGLAPIENTRY *CreateImageKHR)(EGLDisplay, EGLContext, EGLenum, EGLClientBuffer, const EGLint *);
static EGLBoolean(EGLAPIENTRY *DestroyImageKHR)(EGLDisplay, EGLImageKHR);
static void(EGLAPIENTRY *EGLImageTargetTexture2DOES)(GLenum, GLeglImageOES);
PFNEGLCREATESYNCKHRPROC eglCreateSyncKHR;
PFNEGLDESTROYSYNCKHRPROC eglDestroySyncKHR;
PFNEGLWAITSYNCKHRPROC eglWaitSyncKHR;
PFNEGLCLIENTWAITSYNCKHRPROC eglClientWaitSyncKHR;
PFNEGLDUPNATIVEFENCEFDANDROIDPROC eglDupNativeFenceFDANDROID;
static EGLContext eglThreadContext; ///< our gl context for the thread
static void GlxSetupWindow(xcb_window_t window, int width, int height, EGLContext context);
EGLContext OSDcontext;
#endif
static GLuint OsdGlTextures[2]; ///< gl texture for OSD
static int OsdIndex = 0; ///< index into OsdGlTextures
//----------------------------------------------------------------------------
// Common Functions
//----------------------------------------------------------------------------
void VideoThreadLock(void); ///< lock video thread
void VideoThreadUnlock(void); ///< unlock video thread
static void VideoThreadExit(void); ///< exit/kill video thread
#ifdef USE_SCREENSAVER
static void X11SuspendScreenSaver(xcb_connection_t *, int);
static int X11HaveDPMS(xcb_connection_t *);
static void X11DPMSReenable(xcb_connection_t *);
static void X11DPMSDisable(xcb_connection_t *);
#endif
char *eglErrorString(EGLint error) {
switch (error) {
case EGL_SUCCESS:
return "No error";
case EGL_NOT_INITIALIZED:
return "EGL not initialized or failed to initialize";
case EGL_BAD_ACCESS:
return "Resource inaccessible";
case EGL_BAD_ALLOC:
return "Cannot allocate resources";
case EGL_BAD_ATTRIBUTE:
return "Unrecognized attribute or attribute value";
case EGL_BAD_CONTEXT:
return "Invalid EGL context";
case EGL_BAD_CONFIG:
return "Invalid EGL frame buffer configuration";
case EGL_BAD_CURRENT_SURFACE:
return "Current surface is no longer valid";
case EGL_BAD_DISPLAY:
return "Invalid EGL display";
case EGL_BAD_SURFACE:
return "Invalid surface";
case EGL_BAD_MATCH:
return "Inconsistent arguments";
case EGL_BAD_PARAMETER:
return "Invalid argument";
case EGL_BAD_NATIVE_PIXMAP:
return "Invalid native pixmap";
case EGL_BAD_NATIVE_WINDOW:
return "Invalid native window";
case EGL_CONTEXT_LOST:
return "Context lost";
}
return "Unknown error ";
}
///
/// egl check error.
///
#define EglCheck(void) \
{ \
EGLint err; \
\
if ((err = eglGetError()) != EGL_SUCCESS) { \
Debug(3, "video/egl: %s:%d error %d %s\n", __FILE__, __LINE__, err, eglErrorString(err)); \
} \
}
//----------------------------------------------------------------------------
// DRM Helper Functions
//----------------------------------------------------------------------------
#ifdef USE_DRM
#include "drm.c"
#include "hdr.c"
#endif
///
/// Update video pts.
///
/// @param pts_p pointer to pts
/// @param interlaced interlaced flag (frame isn't right)
/// @param frame frame to display
///
/// @note frame->interlaced_frame can't be used for interlace detection
///
static void VideoSetPts(int64_t *pts_p, int interlaced, const AVCodecContext *video_ctx, const AVFrame *frame) {
int64_t pts;
int duration;
static int64_t lastpts;
//
// Get duration for this frame.
// FIXME: using framerate as workaround for av_frame_get_pkt_duration
//
// if (video_ctx->framerate.num && video_ctx->framerate.den) {
// duration = 1000 * video_ctx->framerate.den / video_ctx->framerate.num;
// } else {
duration = interlaced ? 40 : 20; // 50Hz -> 20ms default
// }
// Debug(4, "video: %d/%d %" PRIx64 " -> %d\n", video_ctx->framerate.den,
// video_ctx->framerate.num, av_frame_get_pkt_duration(frame), duration);
// update video clock
if (*pts_p != (int64_t)AV_NOPTS_VALUE) {
*pts_p += duration * 90;
// Info("video: %s +pts\n", Timestamp2String(*pts_p));
}
// av_opt_ptr(avcodec_get_frame_class(), frame, "best_effort_timestamp");
// pts = frame->best_effort_timestamp;
// pts = frame->pkt_pts;
pts = frame->pts;
if (pts == (int64_t)AV_NOPTS_VALUE || !pts) {
// libav: 0.8pre didn't set pts
pts = frame->pkt_dts;
}
// libav: sets only pkt_dts which can be 0
if (pts && pts != (int64_t)AV_NOPTS_VALUE) {
// build a monotonic pts
if (*pts_p != (int64_t)AV_NOPTS_VALUE) {
int64_t delta;
delta = pts - *pts_p;
// ignore negative jumps
if (delta > -600 * 90 && delta <= -40 * 90) {
if (-delta > VideoDeltaPTS) {
VideoDeltaPTS = -delta;
Debug(4, "video: %#012" PRIx64 "->%#012" PRIx64 " delta%+4" PRId64 " pts\n", *pts_p, pts,
pts - *pts_p);
}
return;
}
} else { // first new clock value
Debug(3, "++++++++++++++++++++++++++++++++++++starte audio\n");
AudioVideoReady(pts);
}
if (*pts_p != pts && lastpts != pts) {
Debug(4, "video: %#012" PRIx64 "->%#012" PRIx64 " delta=%4" PRId64 " pts\n", *pts_p, pts, pts - *pts_p);
*pts_p = pts;
}
}
lastpts = pts;
}
int CuvidMessage(int level, const char *format, ...);
///
/// Update output for new size or aspect ratio.
///
/// @param input_aspect_ratio video stream aspect
///
static void VideoUpdateOutput(AVRational input_aspect_ratio, int input_width, int input_height,
VideoResolutions resolution, int video_x, int video_y, int video_width, int video_height,
int *output_x, int *output_y, int *output_width, int *output_height, int *crop_x,
int *crop_y, int *crop_width, int *crop_height) {
AVRational display_aspect_ratio;
AVRational tmp_ratio;
// input not initialized yet, return immediately
if (!input_aspect_ratio.num || !input_aspect_ratio.den) {
*output_width = video_width;
*output_height = video_height;
return;
}
#ifdef USE_DRM
get_drm_aspect(&display_aspect_ratio.num, &display_aspect_ratio.den);
#else
display_aspect_ratio.num = VideoScreen->width_in_pixels;
display_aspect_ratio.den = VideoScreen->height_in_pixels;
#endif
av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den, display_aspect_ratio.num, display_aspect_ratio.den,
1024 * 1024);
Debug(3, "video: input %dx%d (%d:%d)\n", input_width, input_height, input_aspect_ratio.num,
input_aspect_ratio.den);
Debug(3, "video: display aspect %d:%d Resolution %d\n", display_aspect_ratio.num, display_aspect_ratio.den,
resolution);
Debug(3, "video: video %+d%+d %dx%d\n", video_x, video_y, video_width, video_height);
*crop_x = VideoCutLeftRight[resolution];
*crop_y = VideoCutTopBottom[resolution];
*crop_width = input_width - VideoCutLeftRight[resolution] * 2;
*crop_height = input_height - VideoCutTopBottom[resolution] * 2;
CuvidMessage(2, "video: crop to %+d%+d %dx%d\n", *crop_x, *crop_y, *crop_width, *crop_height);
tmp_ratio.num = 4;
tmp_ratio.den = 3;
if (!av_cmp_q(input_aspect_ratio, tmp_ratio)) {
switch (Video4to3ZoomMode) {
case VideoNormal:
goto normal;
case VideoStretch:
goto stretch;
case VideoCenterCutOut:
goto center_cut_out;
case VideoNone:
goto video_none;
}
}
switch (VideoOtherZoomMode) {
case VideoNormal:
goto normal;
case VideoStretch:
goto stretch;
case VideoCenterCutOut:
goto center_cut_out;
case VideoNone:
goto video_none;
}
normal:
*output_x = video_x;
*output_y = video_y;
*output_height = video_height;
*output_width = (*crop_width * *output_height * input_aspect_ratio.num) / (input_aspect_ratio.den * *crop_height);
if (*output_width > video_width) {
*output_width = video_width;
*output_height =
(*crop_height * *output_width * input_aspect_ratio.den) / (input_aspect_ratio.num * *crop_width);
*output_y += (video_height - *output_height) / 2;
} else if (*output_width < video_width) {
*output_x += (video_width - *output_width) / 2;
}
CuvidMessage(2, "video: normal aspect output %dx%d%+d%+d\n", *output_width, *output_height, *output_x, *output_y);
return;
stretch:
*output_x = video_x;
*output_y = video_y;
*output_width = video_width;
*output_height = video_height;
CuvidMessage(2, "video: stretch output %dx%d%+d%+d\n", *output_width, *output_height, *output_x, *output_y);
return;
center_cut_out:
*output_x = video_x;
*output_y = video_y;
*output_height = video_height;
*output_width = (*crop_width * *output_height * input_aspect_ratio.num) / (input_aspect_ratio.den * *crop_height);
if (*output_width > video_width) {
// fix height cropping
*crop_width = (int)((*crop_width * video_width) / (*output_width * 2.0) + 0.5) * 2;
*crop_x = (input_width - *crop_width) / 2;
*output_width = video_width;
} else if (*output_width < video_width) {
// fix width cropping
*crop_height = (int)((*crop_height * *output_width) / (video_width * 2.0) + 0.5) * 2;
*crop_y = (input_height - *crop_height) / 2;
*output_width = video_width;
}
CuvidMessage(2, "video: aspect crop %dx%d%+d%+d\n", *crop_width, *crop_height, *crop_x, *crop_y);
return;
video_none:
*output_height = *crop_height;
*output_width = (*crop_width * input_aspect_ratio.num) / input_aspect_ratio.den; // normalize pixel aspect ratio
*output_x = video_x + (video_width - *output_width) / 2;
*output_y = video_y + (video_height - *output_height) / 2;
CuvidMessage(2, "video: original aspect output %dx%d%+d%+d\n", *output_width, *output_height, *output_x,
*output_y);
return;
}
static uint64_t test_time = 0;
///
/// Lock video thread.
///
#define VideoThreadLock(void) \
{ \
if (VideoThread) { \
if (pthread_mutex_lock(&VideoLockMutex)) { \
Error(_("video: can't lock thread\n")); \
} \
} \
}
// test_time = GetusTicks();
// printf("Lock start....");
///
/// Unlock video thread.
///
#define VideoThreadUnlock(void) \
{ \
if (VideoThread) { \
if (pthread_mutex_unlock(&VideoLockMutex)) { \
Error(_("video: can't unlock thread\n")); \
} \
} \
}
// printf("Video Locked for %d\n",(GetusTicks()-test_time)/1000);
#ifdef PLACEBO_GL
#define Lock_and_SharedContext \
{ \
VideoThreadLock(); \
Debug(4,"Lock OSDMutex %s %d\n",__FILE__, __LINE__); \
pthread_mutex_lock(&OSDMutex); \
eglMakeCurrent(eglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, eglSharedContext); \
EglCheck(); \
}
#define Unlock_and_NoContext \
{ \
eglMakeCurrent(eglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); \
EglCheck(); \
Debug(4,"UnLock OSDMutex %s %d\n",__FILE__, __LINE__); \
pthread_mutex_unlock(&OSDMutex); \
VideoThreadUnlock(); \
}
#define SharedContext \
{ \
Debug(4,"Lock OSDMutex %s %d\n",__FILE__, __LINE__); \
pthread_mutex_lock(&OSDMutex); \
eglMakeCurrent(eglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, eglSharedContext); \
EglCheck(); \
}
#define NoContext \
{ \
eglMakeCurrent(eglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); \
EglCheck(); \
Debug(4,"UnLock OSDMutex %s %d\n",__FILE__, __LINE__); \
pthread_mutex_unlock(&OSDMutex); \
}
#else
#ifdef PLACEBO
#define Lock_and_SharedContext \
{ VideoThreadLock(); }
#define Unlock_and_NoContext \
{ VideoThreadUnlock(); }
#define SharedContext \
{}
#define NoContext \
{}
#endif
#endif
//----------------------------------------------------------------------------
// GLX
//----------------------------------------------------------------------------
#ifdef USE_GLX
///
/// GLX extension functions
///@{
#ifdef GLX_MESA_swap_control
static PFNGLXSWAPINTERVALMESAPROC GlxSwapIntervalMESA;
#endif
#ifdef GLX_SGI_video_sync
static PFNGLXGETVIDEOSYNCSGIPROC GlxGetVideoSyncSGI;
#endif
#ifdef GLX_SGI_swap_control
static PFNGLXSWAPINTERVALSGIPROC GlxSwapIntervalSGI;
#endif
///
/// GLX check error.
///
#define GlxCheck(void) \
{ \
GLenum err; \
\
if ((err = glGetError()) != GL_NO_ERROR) { \
Debug(3, "video/glx: error %s:%d %d '%s'\n", __FILE__, __LINE__, err, gluErrorString(err)); \
} \
}
///
/// GLX check if a GLX extension is supported.
///
/// @param ext extension to query
/// @returns true if supported, false otherwise
///
static int GlxIsExtensionSupported(const char *ext) {
const char *extensions;
if ((extensions = glXQueryExtensionsString(XlibDisplay, DefaultScreen(XlibDisplay)))) {
const char *s;
int l;
s = strstr(extensions, ext);
l = strlen(ext);
return s && (s[l] == ' ' || s[l] == '\0');
}
return 0;
}
///
/// Setup GLX window.
///
/// @param window xcb window id
/// @param width window width
/// @param height window height
/// @param context GLX context
///
#ifdef CUVID
static void GlxSetupWindow(xcb_window_t window, int width, int height, GLXContext context)
#else
static void GlxSetupWindow(xcb_window_t window, int width, int height, EGLContext context)
#endif
{
uint32_t start;
uint32_t end;
int i;
unsigned count;
#ifdef PLACEBO_
return;
#endif
Debug(3, "video/egl: %s %x %dx%d context: %p", __FUNCTION__, window, width, height, context);
// set gl context
#ifdef CUVID
if (!glXMakeCurrent(XlibDisplay, window, context)) {
Fatal(_("video/egl: GlxSetupWindow can't make egl/glx context current\n"));
EglEnabled = 0;
return;
}
#endif
Debug(3, "video/egl: ok\n");
#ifdef CUVID
// check if v-sync is working correct
end = GetMsTicks();
for (i = 0; i < 10; ++i) {
start = end;
glClear(GL_COLOR_BUFFER_BIT);
glXSwapBuffers(XlibDisplay, window);
end = GetMsTicks();
GlxGetVideoSyncSGI(&count);
Debug(4, "video/glx: %5d frame rate %dms\n", count, end - start);
// nvidia can queue 5 swaps
if (i > 5 && (end - start) < 15) {
Warning(_("video/glx: no v-sync\n"));
}
}
GLenum err = glewInit();
if (err != GLEW_OK) {
Debug(3, "Error: %s\n", glewGetErrorString(err));
}
GlxCheck();
#endif
// viewpoint
glViewport(0, 0, width, height);
GlxCheck();
#ifdef VAAPI
eglMakeCurrent(eglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
#endif
}
///
/// Initialize GLX.
///
#ifdef CUVID
static void EglInit(void) {
XVisualInfo *vi = NULL;
#if defined PLACEBO && !defined PLACEBO_GL
return;
#endif
// The desired 30-bit color visual
int attributeList10[] = {GLX_DRAWABLE_TYPE,