-
Notifications
You must be signed in to change notification settings - Fork 11
/
vaapidev.c
3079 lines (2785 loc) · 78.7 KB
/
vaapidev.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
/// Copyright (C) 2011 - 2015 by Johns. All Rights Reserved.
/// Copyright (C) 2018 by pesintta, rofafor.
///
/// SPDX-License-Identifier: AGPL-3.0-only
#define noDUMP_TRICKSPEED ///< dump raw trickspeed packets
#include <sys/types.h>
#include <sys/stat.h>
#ifdef __FreeBSD__
#include <signal.h>
#endif
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <inttypes.h>
#include <unistd.h>
#include <string.h>
#include <libavcodec/avcodec.h>
#if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(57,64,100)
#error "libavcodec is too old - please, upgrade!"
#endif
#include <libavutil/mem.h>
#ifndef __USE_GNU
#define __USE_GNU
#endif
#include <pthread.h>
#include "iatomic.h" // portable atomic_t
#include "misc.h"
#include "vaapidevice.h"
#include "audio.h"
#include "video.h"
#include "codec.h"
#ifdef DEBUG
static int DumpH264(const uint8_t * data, int size);
static void DumpMpeg(const uint8_t * data, int size);
static int ValidateMpeg(const uint8_t * data, int size);
#endif
//////////////////////////////////////////////////////////////////////////////
// Variables
//////////////////////////////////////////////////////////////////////////////
extern int ConfigAudioBufferTime; ///< config size ms of audio buffer
char ConfigStartX11Server; ///< flag start the x11 server
static signed char ConfigStartSuspended; ///< flag to start in suspend mode
static char ConfigFullscreen; ///< fullscreen modus
static const char *X11ServerArguments; ///< default command arguments
static pthread_mutex_t SuspendLockMutex; ///< suspend lock mutex
static volatile char StreamFreezed; ///< stream freezed
int TraceMode = 0; ///< Tracing mode for debugging
//////////////////////////////////////////////////////////////////////////////
// Audio
//////////////////////////////////////////////////////////////////////////////
static volatile char NewAudioStream; ///< new audio stream
static volatile char SkipAudio; ///< skip audio stream
static AudioDecoder *MyAudioDecoder; ///< audio decoder
static enum AVCodecID AudioCodecID; ///< current codec id
static int AudioChannelID; ///< current audio channel id
static VideoStream *AudioSyncStream; ///< video stream for audio/video sync
/// Minimum free space in audio buffer 8 packets for 8 channels
#define AUDIO_MIN_BUFFER_FREE (3072 * 8 * 8)
#define AUDIO_BUFFER_SIZE (512 * 1024) ///< audio PES buffer default size
static AVPacket AudioAvPkt[1]; ///< audio a/v packet
//////////////////////////////////////////////////////////////////////////////
// Audio codec parser
//////////////////////////////////////////////////////////////////////////////
///
/// Mpeg bitrate table.
///
/// BitRateTable[Version][Layer][Index]
///
static const uint16_t BitRateTable[2][4][16] = {
// MPEG Version 1
{{},
{0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448,
0},
{0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 0},
{0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 0}},
// MPEG Version 2 & 2.5
{{},
{0, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256, 0},
{0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, 0},
{0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, 0}
}
};
///
/// Mpeg samperate table.
///
static const uint16_t SampleRateTable[4] = {
44100, 48000, 32000, 0
};
///
/// Fast check for Mpeg audio.
///
/// 4 bytes 0xFFExxxxx Mpeg audio
///
static inline int FastMpegCheck(const uint8_t * p)
{
if (p[0] != 0xFF) { // 11bit frame sync
return 0;
}
if ((p[1] & 0xE0) != 0xE0) {
return 0;
}
if ((p[1] & 0x18) == 0x08) { // version ID - 01 reserved
return 0;
}
if (!(p[1] & 0x06)) { // layer description - 00 reserved
return 0;
}
if ((p[2] & 0xF0) == 0xF0) { // bitrate index - 1111 reserved
return 0;
}
if ((p[2] & 0x0C) == 0x0C) { // sampling rate index - 11 reserved
return 0;
}
return 1;
}
///
/// Check for Mpeg audio.
///
/// 0xFFEx already checked.
///
/// @param data incomplete PES packet
/// @param size number of bytes
///
/// @retval <0 possible mpeg audio, but need more data
/// @retval 0 no valid mpeg audio
/// @retval >0 valid mpeg audio
///
/// From: http://www.mpgedit.org/mpgedit/mpeg_format/mpeghdr.htm
///
/// AAAAAAAA AAABBCCD EEEEFFGH IIJJKLMM
///
/// o a 11x Frame sync
/// o b 2x Mpeg audio version (2.5, reserved, 2, 1)
/// o c 2x Layer (reserved, III, II, I)
/// o e 2x BitRate index
/// o f 2x SampleRate index (4100, 48000, 32000, 0)
/// o g 1x Paddding bit
/// o .. Doesn't care
///
/// frame length:
/// Layer I:
/// FrameLengthInBytes = (12 * BitRate / SampleRate + Padding) * 4
/// Layer II & III:
/// FrameLengthInBytes = 144 * BitRate / SampleRate + Padding
///
static int MpegCheck(const uint8_t * data, int size)
{
int mpeg2;
int mpeg25;
int layer;
int bit_rate_index;
int sample_rate_index;
int padding;
int bit_rate;
int sample_rate;
int frame_size;
mpeg2 = !(data[1] & 0x08) && (data[1] & 0x10);
mpeg25 = !(data[1] & 0x08) && !(data[1] & 0x10);
layer = 4 - ((data[1] >> 1) & 0x03);
bit_rate_index = (data[2] >> 4) & 0x0F;
sample_rate_index = (data[2] >> 2) & 0x03;
padding = (data[2] >> 1) & 0x01;
sample_rate = SampleRateTable[sample_rate_index];
if (!sample_rate) { // no valid sample rate try next
// moved into fast check
abort();
return 0;
}
sample_rate >>= mpeg2; // mpeg 2 half rate
sample_rate >>= mpeg25; // mpeg 2.5 quarter rate
bit_rate = BitRateTable[mpeg2 | mpeg25][layer][bit_rate_index];
if (!bit_rate) { // no valid bit-rate try next
// FIXME: move into fast check?
return 0;
}
bit_rate *= 1000;
switch (layer) {
case 1:
frame_size = (12 * bit_rate) / sample_rate;
frame_size = (frame_size + padding) * 4;
break;
case 2:
case 3:
default:
frame_size = (144 * bit_rate) / sample_rate;
frame_size = frame_size + padding;
break;
}
if (frame_size + 4 > size) {
return -frame_size - 4;
}
// check if after this frame a new mpeg frame starts
if (FastMpegCheck(data + frame_size)) {
return frame_size;
}
return 0;
}
///
/// Fast check for AAC LATM audio.
///
/// 3 bytes 0x56Exxx AAC LATM audio
///
static inline int FastLatmCheck(const uint8_t * p)
{
if (p[0] != 0x56) { // 11bit sync
return 0;
}
if ((p[1] & 0xE0) != 0xE0) {
return 0;
}
return 1;
}
///
/// Check for AAC LATM audio.
///
/// 0x56Exxx already checked.
///
/// @param data incomplete PES packet
/// @param size number of bytes
///
/// @retval <0 possible AAC LATM audio, but need more data
/// @retval 0 no valid AAC LATM audio
/// @retval >0 valid AAC LATM audio
///
static int LatmCheck(const uint8_t * data, int size)
{
int frame_size;
// 13 bit frame size without header
frame_size = ((data[1] & 0x1F) << 8) + data[2];
frame_size += 3;
if (frame_size + 2 > size) {
return -frame_size - 2;
}
// check if after this frame a new AAC LATM frame starts
if (FastLatmCheck(data + frame_size)) {
return frame_size;
}
return 0;
}
///
/// Possible AC-3 frame sizes.
///
/// from ATSC A/52 table 5.18 frame size code table.
///
const uint16_t Ac3FrameSizeTable[38][3] = {
{64, 69, 96}, {64, 70, 96}, {80, 87, 120}, {80, 88, 120},
{96, 104, 144}, {96, 105, 144}, {112, 121, 168}, {112, 122, 168},
{128, 139, 192}, {128, 140, 192}, {160, 174, 240}, {160, 175, 240},
{192, 208, 288}, {192, 209, 288}, {224, 243, 336}, {224, 244, 336},
{256, 278, 384}, {256, 279, 384}, {320, 348, 480}, {320, 349, 480},
{384, 417, 576}, {384, 418, 576}, {448, 487, 672}, {448, 488, 672},
{512, 557, 768}, {512, 558, 768}, {640, 696, 960}, {640, 697, 960},
{768, 835, 1152}, {768, 836, 1152}, {896, 975, 1344}, {896, 976, 1344},
{1024, 1114, 1536}, {1024, 1115, 1536}, {1152, 1253, 1728},
{1152, 1254, 1728}, {1280, 1393, 1920}, {1280, 1394, 1920},
};
///
/// Fast check for (E-)AC-3 audio.
///
/// 5 bytes 0x0B77xxxxxx AC-3 audio
///
static inline int FastAc3Check(const uint8_t * p)
{
if (p[0] != 0x0B) { // 16bit sync
return 0;
}
if (p[1] != 0x77) {
return 0;
}
return 1;
}
///
/// Check for (E-)AC-3 audio.
///
/// 0x0B77xxxxxx already checked.
///
/// @param data incomplete PES packet
/// @param size number of bytes
///
/// @retval <0 possible AC-3 audio, but need more data
/// @retval 0 no valid AC-3 audio
/// @retval >0 valid AC-3 audio
///
/// o AC-3 Header
/// AAAAAAAA AAAAAAAA BBBBBBBB BBBBBBBB CCDDDDDD EEEEEFFF
///
/// o a 16x Frame sync, always 0x0B77
/// o b 16x CRC 16
/// o c 2x Samplerate
/// o d 6x Framesize code
/// o e 5x Bitstream ID
/// o f 3x Bitstream mode
///
/// o E-AC-3 Header
/// AAAAAAAA AAAAAAAA BBCCCDDD DDDDDDDD EEFFGGGH IIIII...
///
/// o a 16x Frame sync, always 0x0B77
/// o b 2x Frame type
/// o c 3x Sub stream ID
/// o d 10x Framesize - 1 in words
/// o e 2x Framesize code
/// o f 2x Framesize code 2
///
static int Ac3Check(const uint8_t * data, int size)
{
int frame_size;
if (size < 5) { // need 5 bytes to see if AC-3/E-AC-3
return -5;
}
if (data[5] > (10 << 3)) { // E-AC-3
if ((data[4] & 0xF0) == 0xF0) { // invalid fscod fscod2
return 0;
}
frame_size = ((data[2] & 0x03) << 8) + data[3] + 1;
frame_size *= 2;
} else { // AC-3
int fscod;
int frmsizcod;
// crc1 crc1 fscod|frmsizcod
fscod = data[4] >> 6;
if (fscod == 0x03) { // invalid sample rate
return 0;
}
frmsizcod = data[4] & 0x3F;
if (frmsizcod > 37) { // invalid frame size
return 0;
}
// invalid is checked above
frame_size = Ac3FrameSizeTable[frmsizcod][fscod] * 2;
}
if (frame_size + 5 > size) {
return -frame_size - 5;
}
// FIXME: relaxed checks if codec is already detected
// check if after this frame a new AC-3 frame starts
if (FastAc3Check(data + frame_size)) {
return frame_size;
}
return 0;
}
///
/// Fast check for ADTS Audio Data Transport Stream.
///
/// 7/9 bytes 0xFFFxxxxxxxxxxx(xxxx) ADTS audio
///
static inline int FastAdtsCheck(const uint8_t * p)
{
if (p[0] != 0xFF) { // 12bit sync
return 0;
}
if ((p[1] & 0xF6) != 0xF0) { // sync + layer must be 0
return 0;
}
if ((p[2] & 0x3C) == 0x3C) { // sampling frequency index != 15
return 0;
}
return 1;
}
///
/// Check for ADTS Audio Data Transport Stream.
///
/// 0xFFF already checked.
///
/// @param data incomplete PES packet
/// @param size number of bytes
///
/// @retval <0 possible ADTS audio, but need more data
/// @retval 0 no valid ADTS audio
/// @retval >0 valid AC-3 audio
///
/// AAAAAAAA AAAABCCD EEFFFFGH HHIJKLMM MMMMMMMM MMMOOOOO OOOOOOPP
/// (QQQQQQQQ QQQQQQQ)
///
/// o A*12 syncword 0xFFF
/// o B*1 MPEG Version: 0 for MPEG-4, 1 for MPEG-2
/// o C*2 layer: always 0
/// o ..
/// o F*4 sampling frequency index (15 is invalid)
/// o ..
/// o M*13 frame length
///
static int AdtsCheck(const uint8_t * data, int size)
{
int frame_size;
if (size < 6) {
return -6;
}
frame_size = (data[3] & 0x03) << 11;
frame_size |= (data[4] & 0xFF) << 3;
frame_size |= (data[5] & 0xE0) >> 5;
if (frame_size + 3 > size) {
return -frame_size - 3;
}
// check if after this frame a new ADTS frame starts
if (FastAdtsCheck(data + frame_size)) {
return frame_size;
}
return 0;
}
/**
** Set volume of audio device.
**
** @param volume VDR volume (0 .. 255)
*/
void SetVolumeDevice(int volume)
{
AudioSetVolume((volume * 1000) / 255);
}
/**
*** Resets channel ID (restarts audio).
**/
void ResetChannelId(void)
{
AudioChannelID = -1;
Debug3("audio/demux: reset channel id");
}
//////////////////////////////////////////////////////////////////////////////
// Video
//////////////////////////////////////////////////////////////////////////////
#define VIDEO_BUFFER_SIZE (512 * 1024) ///< video PES buffer default size
#define VIDEO_PACKET_MAX 192 ///< max number of video packets
/**
** Video output stream device structure. Parser, decoder, display.
*/
struct __video_stream__
{
VideoHwDecoder *HwDecoder; ///< video hardware decoder
VideoDecoder *Decoder; ///< video decoder
pthread_mutex_t DecoderLockMutex; ///< video decoder lock mutex
enum AVCodecID CodecID; ///< current codec id
enum AVCodecID LastCodecID; ///< last codec id
volatile char NewStream; ///< flag new video stream
volatile char ClosingStream; ///< flag closing video stream
volatile char SkipStream; ///< skip video stream
volatile char Freezed; ///< stream freezed
volatile char TrickSpeed; ///< current trick speed
volatile char Close; ///< command close video stream
volatile char ClearBuffers; ///< command clear video buffers
volatile char ClearClose; ///< clear video buffers for close
int InvalidPesCounter; ///< counter of invalid PES packets
enum AVCodecID CodecIDRb[VIDEO_PACKET_MAX]; ///< codec ids in ring buffer
AVPacket PacketRb[VIDEO_PACKET_MAX]; ///< PES packet ring buffer
int StartCodeState; ///< last three bytes start code state
int PacketWrite; ///< ring buffer write pointer
int PacketRead; ///< ring buffer read pointer
atomic_t PacketsFilled; ///< how many of the ring buffer is used
};
static VideoStream MyVideoStream[1]; ///< normal video stream
#ifdef DEBUG
uint32_t VideoSwitch; ///< debug video switch ticks
static int VideoMaxPacketSize; ///< biggest used packet buffer
#endif
const char *X11DisplayName; ///< x11 display name
static volatile char Usr1Signal; ///< true got usr1 signal
//////////////////////////////////////////////////////////////////////////////
/**
** Initialize video packet ringbuffer.
**
** @param stream video stream
*/
static void VideoPacketInit(VideoStream * stream)
{
int i;
for (i = 0; i < VIDEO_PACKET_MAX; ++i) {
AVPacket *avpkt;
avpkt = &stream->PacketRb[i];
// build a clean ffmpeg av packet
if (av_new_packet(avpkt, VIDEO_BUFFER_SIZE)) {
Fatal("[vaapidevice] out of memory");
}
}
atomic_set(&stream->PacketsFilled, 0);
stream->PacketRead = stream->PacketWrite = 0;
}
/**
** Cleanup video packet ringbuffer.
**
** @param stream video stream
*/
static void VideoPacketExit(VideoStream * stream)
{
int i;
atomic_set(&stream->PacketsFilled, 0);
for (i = 0; i < VIDEO_PACKET_MAX; ++i) {
av_packet_unref(&stream->PacketRb[i]);
}
}
/**
** Place video data in packet ringbuffer.
**
** @param stream video stream
** @param pts presentation timestamp of pes packet
** @param dts decode timestamp of pes packet
** @param data data of pes packet
** @param size size of pes packet
*/
static void VideoEnqueue(VideoStream * stream, int64_t pts, int64_t dts, const void *data, int size)
{
AVPacket *avpkt;
avpkt = &stream->PacketRb[stream->PacketWrite];
if (!avpkt->stream_index) { // add pts only for first added
avpkt->pts = pts;
avpkt->dts = dts;
}
if (avpkt->stream_index + size >= avpkt->size) {
Error("video: packet buffer too small for %d", avpkt->stream_index + size);
// new + grow reserves AV_INPUT_BUFFER_PADDING_SIZE
av_grow_packet(avpkt, ((size + VIDEO_BUFFER_SIZE / 2)
/ (VIDEO_BUFFER_SIZE / 2)) * (VIDEO_BUFFER_SIZE / 2));
// FIXME: out of memory!
#ifdef DEBUG
if (avpkt->size <= avpkt->stream_index + size) {
Fatal("%d %d %d\n", avpkt->size, avpkt->stream_index, size);
}
#endif
}
memcpy(avpkt->data + avpkt->stream_index, data, size);
avpkt->stream_index += size;
#ifdef DEBUG
if (avpkt->stream_index > VideoMaxPacketSize) {
VideoMaxPacketSize = avpkt->stream_index;
Debug3("video: max used PES packet size: %d", VideoMaxPacketSize);
}
#endif
}
/**
** Reset current packet.
**
** @param stream video stream
*/
static void VideoResetPacket(VideoStream * stream)
{
AVPacket *avpkt;
stream->StartCodeState = 0; // reset start code state
stream->CodecIDRb[stream->PacketWrite] = AV_CODEC_ID_NONE;
avpkt = &stream->PacketRb[stream->PacketWrite];
avpkt->stream_index = 0;
avpkt->pts = AV_NOPTS_VALUE;
avpkt->dts = AV_NOPTS_VALUE;
}
/**
** Finish current packet advance to next.
**
** @param stream video stream
** @param codec_id codec id of packet (MPEG/H264)
*/
static void VideoNextPacket(VideoStream * stream, int codec_id)
{
AVPacket *avpkt;
avpkt = &stream->PacketRb[stream->PacketWrite];
if (!avpkt->stream_index) { // ignore empty packets
if (codec_id != AV_CODEC_ID_NONE) {
return;
}
Debug3("video: possible stream change loss");
}
if (atomic_read(&stream->PacketsFilled) >= VIDEO_PACKET_MAX - 1) {
// no free slot available drop last packet
Error("video: no empty slot in packet ringbuffer");
avpkt->stream_index = 0;
if (codec_id == AV_CODEC_ID_NONE) {
Debug3("video: possible stream change loss");
}
return;
}
// clear area for decoder, always enough space allocated
memset(avpkt->data + avpkt->stream_index, 0, AV_INPUT_BUFFER_PADDING_SIZE);
stream->CodecIDRb[stream->PacketWrite] = codec_id;
//DumpH264(avpkt->data, avpkt->stream_index);
// advance packet write
stream->PacketWrite = (stream->PacketWrite + 1) % VIDEO_PACKET_MAX;
atomic_inc(&stream->PacketsFilled);
VideoDisplayWakeup();
// intialize next package to use
VideoResetPacket(stream);
}
/**
** Place mpeg video data in packet ringbuffer.
**
** Some tv-stations sends mulitple pictures in a single PES packet.
** Split the packet into single picture packets.
** Nick/CC, Viva, MediaShop, Deutsches Music Fernsehen
**
** FIXME: this code can be written much faster
**
** @param stream video stream
** @param pts presentation timestamp of pes packet
** @param dts presentation timestamp of pes packet
** @param data data of pes packet
** @param size size of pes packet
*/
static void VideoMpegEnqueue(VideoStream * stream, int64_t pts, int64_t dts, const void *data, int size)
{
static const char startcode[3] = { 0x00, 0x00, 0x01 };
const uint8_t *p;
int n;
int first;
// first scan
first = !stream->PacketRb[stream->PacketWrite].stream_index;
p = data;
n = size;
switch (stream->StartCodeState) { // prefix starting in last packet
case 3: // 0x00 0x00 0x01 seen
if (!p[0] || p[0] == 0xb3) {
stream->PacketRb[stream->PacketWrite].stream_index -= 3;
VideoNextPacket(stream, AV_CODEC_ID_MPEG2VIDEO);
VideoEnqueue(stream, pts, dts, startcode, 3);
first = p[0] == 0xb3;
p++;
n--;
pts = AV_NOPTS_VALUE;
dts = AV_NOPTS_VALUE;
}
break;
case 2: // 0x00 0x00 seen
if (p[0] == 0x01 && (!p[1] || p[1] == 0xb3)) {
stream->PacketRb[stream->PacketWrite].stream_index -= 2;
VideoNextPacket(stream, AV_CODEC_ID_MPEG2VIDEO);
VideoEnqueue(stream, pts, dts, startcode, 2);
first = p[1] == 0xb3;
p += 2;
n -= 2;
pts = AV_NOPTS_VALUE;
dts = AV_NOPTS_VALUE;
}
break;
case 1: // 0x00 seen
if (!p[0] && p[1] == 0x01 && (!p[2] || p[2] == 0xb3)) {
stream->PacketRb[stream->PacketWrite].stream_index -= 1;
VideoNextPacket(stream, AV_CODEC_ID_MPEG2VIDEO);
VideoEnqueue(stream, pts, dts, startcode, 1);
first = p[2] == 0xb3;
p += 3;
n -= 3;
pts = AV_NOPTS_VALUE;
dts = AV_NOPTS_VALUE;
}
case 0:
break;
}
// b3 b4 b8 00 b5 ... 00 b5 ...
while (n > 3) {
// scan for picture header 0x00000100
// FIXME: not perfect, must split at 0xb3 also
if (!p[0] && !p[1] && p[2] == 0x01 && !p[3]) {
const uint8_t *p2 = data;
if (first) {
first = 0;
n -= 4;
p += 4;
continue;
}
// packet has already an picture header
// first packet goes only upto picture header
VideoEnqueue(stream, pts, dts, data, p - p2);
VideoNextPacket(stream, AV_CODEC_ID_MPEG2VIDEO);
data = p;
size = n;
// time-stamp only valid for first packet
pts = AV_NOPTS_VALUE;
dts = AV_NOPTS_VALUE;
n -= 4;
p += 4;
continue;
}
--n;
++p;
}
stream->StartCodeState = 0;
switch (n) { // handle packet border start code
case 3:
if (!p[0] && !p[1] && p[2] == 0x01) {
stream->StartCodeState = 3;
}
break;
case 2:
if (!p[0] && !p[1]) {
stream->StartCodeState = 2;
}
break;
case 1:
if (!p[0]) {
stream->StartCodeState = 1;
}
break;
case 0:
break;
}
VideoEnqueue(stream, pts, dts, data, size);
}
/**
** Open video stream.
**
** @param stream video stream
*/
static void VideoStreamOpen(VideoStream * stream)
{
stream->SkipStream = 1;
stream->CodecID = AV_CODEC_ID_NONE;
stream->LastCodecID = AV_CODEC_ID_NONE;
if ((stream->HwDecoder = VideoNewHwDecoder(stream))) {
stream->Decoder = CodecVideoNewDecoder(stream->HwDecoder);
VideoPacketInit(stream);
stream->SkipStream = 0;
}
}
/**
** Close video stream.
**
** @param stream video stream
** @param delhw flag delete hardware decoder
**
** @note must be called from the video thread, otherwise xcb has a
** deadlock.
*/
static void VideoStreamClose(VideoStream * stream, int delhw)
{
stream->SkipStream = 1;
if (stream->Decoder) {
VideoDecoder *decoder;
decoder = stream->Decoder;
// FIXME: remove this lock for main stream close
pthread_mutex_lock(&stream->DecoderLockMutex);
stream->Decoder = NULL; // lock read thread
pthread_mutex_unlock(&stream->DecoderLockMutex);
CodecVideoClose(decoder);
CodecVideoDelDecoder(decoder);
}
if (stream->HwDecoder) {
if (delhw) {
VideoDelHwDecoder(stream->HwDecoder);
}
stream->HwDecoder = NULL;
// FIXME: CodecVideoClose calls/uses hw decoder
}
VideoPacketExit(stream);
stream->NewStream = 1;
stream->InvalidPesCounter = 0;
}
/**
** Poll PES packet ringbuffer.
**
** Called if video frame buffers are full.
**
** @param stream video stream
**
** @retval 1 something todo
** @retval -1 empty stream
*/
int VideoPollInput(VideoStream * stream)
{
if (!stream->Decoder) { // closing
return -1;
}
if (stream->Close) { // close stream request
VideoStreamClose(stream, 1);
stream->Close = 0;
return 1;
}
if (stream->ClearBuffers) { // clear buffer request
atomic_set(&stream->PacketsFilled, 0);
stream->PacketRead = stream->PacketWrite;
// FIXME: ->Decoder already checked
if (stream->Decoder) {
CodecVideoFlushBuffers(stream->Decoder);
VideoResetStart(stream->HwDecoder);
}
stream->ClearBuffers = 0;
return 1;
}
if (!atomic_read(&stream->PacketsFilled)) {
return -1;
}
return 1;
}
/**
** Decode from PES packet ringbuffer.
**
** @param stream video stream
**
** @retval 0 packet decoded
** @retval 1 stream paused
** @retval -1 empty stream
*/
int VideoDecodeInput(VideoStream * stream)
{
int filled;
AVPacket *avpkt;
int saved_size;
if (!stream->Decoder) { // closing
return -1;
}
if (stream->Close) { // close stream request
VideoStreamClose(stream, 1);
stream->Close = 0;
return 1;
}
if (stream->ClearBuffers) { // clear buffer request
atomic_set(&stream->PacketsFilled, 0);
stream->PacketRead = stream->PacketWrite;
// FIXME: ->Decoder already checked
if (stream->Decoder) {
CodecVideoFlushBuffers(stream->Decoder);
VideoResetStart(stream->HwDecoder);
}
stream->ClearBuffers = 0;
return 1;
}
if (stream->Freezed) { // stream freezed
// clear is called during freezed
return 1;
}
filled = atomic_read(&stream->PacketsFilled);
if (!filled) {
return -1;
}
//
// handle queued commands
//
avpkt = &stream->PacketRb[stream->PacketRead];
switch (stream->CodecIDRb[stream->PacketRead]) {
case AV_CODEC_ID_NONE:
stream->ClosingStream = 0;
if (stream->LastCodecID != AV_CODEC_ID_NONE) {
stream->LastCodecID = AV_CODEC_ID_NONE;
CodecVideoClose(stream->Decoder);
goto skip;
}
// FIXME: look if more close are in the queue
// size can be zero
goto skip;
case AV_CODEC_ID_MPEG2VIDEO:
if (stream->LastCodecID != AV_CODEC_ID_MPEG2VIDEO) {
stream->LastCodecID = AV_CODEC_ID_MPEG2VIDEO;
CodecVideoOpen(stream->Decoder, AV_CODEC_ID_MPEG2VIDEO);
}
break;
case AV_CODEC_ID_H264:
if (stream->LastCodecID != AV_CODEC_ID_H264) {
stream->LastCodecID = AV_CODEC_ID_H264;
CodecVideoOpen(stream->Decoder, AV_CODEC_ID_H264);
}
break;
case AV_CODEC_ID_HEVC:
if (stream->LastCodecID != AV_CODEC_ID_HEVC) {
stream->LastCodecID = AV_CODEC_ID_HEVC;
CodecVideoOpen(stream->Decoder, AV_CODEC_ID_HEVC);
}
break;
default:
break;
}
// avcodec_decode_video2 needs size
saved_size = avpkt->size;
avpkt->size = avpkt->stream_index;
avpkt->stream_index = 0;
// old version
if (stream->Decoder) {
CodecVideoDecode(stream->Decoder, avpkt);
}
avpkt->size = saved_size;
skip:
// advance packet read
stream->PacketRead = (stream->PacketRead + 1) % VIDEO_PACKET_MAX;
atomic_dec(&stream->PacketsFilled);
return 0;
}
/**
** Get number of video buffers.
**
** @param stream video stream
*/
int VideoGetBuffers(const VideoStream * stream)
{
return atomic_read(&stream->PacketsFilled);
}
/**
** Try video start.
**
** NOT TRUE: Could be called, when already started.
*/
static void StartVideo(void)
{
VideoInit(X11DisplayName);
if (ConfigFullscreen) {
// FIXME: not good looking, mapped and then resized.
VideoSetFullscreen(1);
}
if (!MyVideoStream->Decoder) {
VideoStreamOpen(MyVideoStream);