-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsrs_kernel_ts.cpp
More file actions
3494 lines (2902 loc) · 111 KB
/
srs_kernel_ts.cpp
File metadata and controls
3494 lines (2902 loc) · 111 KB
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) 2013-2025 The SRS Authors
//
// SPDX-License-Identifier: MIT
//
#include <srs_kernel_ts.hpp>
// for srs-librtmp, @see https://github.com/ossrs/srs/issues/213
#include <unistd.h>
#include <fcntl.h>
#include <sstream>
using namespace std;
#include <cstring>
#include <openssl/aes.h>
#include <srs_core_autofree.hpp>
#include <srs_kernel_buffer.hpp>
#include <srs_kernel_codec.hpp>
#include <srs_kernel_error.hpp>
#include <srs_kernel_log.hpp>
#include <srs_kernel_stream.hpp>
#include <srs_kernel_utility.hpp>
#define HLS_AES_ENCRYPT_BLOCK_LENGTH SRS_TS_PACKET_SIZE * 4
// the mpegts header specifed the video/audio pid.
#define TS_PMT_NUMBER 1
#define TS_PMT_PID 0x1001
#define TS_VIDEO_AVC_PID 0x100
#define TS_AUDIO_AAC_PID 0x101
#define TS_AUDIO_MP3_PID 0x102
// @see pycrc reflect at https://github.com/winlinvip/pycrc/blob/master/pycrc/algorithms.py#L107
uint64_t __crc32_reflect(uint64_t data, int width)
{
uint64_t res = data & 0x01;
for (int i = 0; i < (int)width - 1; i++) {
data >>= 1;
res = (res << 1) | (data & 0x01);
}
return res;
}
// @see pycrc gen_table at https://github.com/winlinvip/pycrc/blob/master/pycrc/algorithms.py#L178
void __crc32_make_table(uint32_t t[256], uint32_t poly, bool reflect_in)
{
int width = 32; // 32bits checksum.
uint64_t msb_mask = (uint32_t)(0x01 << (width - 1));
uint64_t mask = (uint32_t)(((msb_mask - 1) << 1) | 1);
int tbl_idx_width = 8; // table index size.
int tbl_width = 0x01 << tbl_idx_width; // table size: 256
for (int i = 0; i < (int)tbl_width; i++) {
uint64_t reg = uint64_t(i);
if (reflect_in) {
reg = __crc32_reflect(reg, tbl_idx_width);
}
reg = reg << (width - tbl_idx_width);
for (int j = 0; j < tbl_idx_width; j++) {
if ((reg & msb_mask) != 0) {
reg = (reg << 1) ^ poly;
} else {
reg = reg << 1;
}
}
if (reflect_in) {
reg = __crc32_reflect(reg, width);
}
t[i] = (uint32_t)(reg & mask);
}
}
// @see pycrc table_driven at https://github.com/winlinvip/pycrc/blob/master/pycrc/algorithms.py#L207
uint32_t __crc32_table_driven(uint32_t *t, const void *buf, int size, uint32_t previous, bool reflect_in, uint32_t xor_in, bool reflect_out, uint32_t xor_out)
{
int width = 32; // 32bits checksum.
uint64_t msb_mask = (uint32_t)(0x01 << (width - 1));
uint64_t mask = (uint32_t)(((msb_mask - 1) << 1) | 1);
int tbl_idx_width = 8; // table index size.
uint8_t *p = (uint8_t *)buf;
uint64_t reg = 0;
if (!reflect_in) {
reg = xor_in;
for (int i = 0; i < (int)size; i++) {
uint8_t tblidx = (uint8_t)((reg >> (width - tbl_idx_width)) ^ p[i]);
reg = t[tblidx] ^ (reg << tbl_idx_width);
}
} else {
reg = previous ^ __crc32_reflect(xor_in, width);
for (int i = 0; i < (int)size; i++) {
uint8_t tblidx = (uint8_t)(reg ^ p[i]);
reg = t[tblidx] ^ (reg >> tbl_idx_width);
}
reg = __crc32_reflect(reg, width);
}
if (reflect_out) {
reg = __crc32_reflect(reg, width);
}
reg ^= xor_out;
return (uint32_t)(reg & mask);
}
// @see pycrc https://github.com/winlinvip/pycrc/blob/master/pycrc/algorithms.py#L238
// IEEETable is the table for the MPEG polynomial.
static uint32_t __crc32_MPEG_table[256];
static bool __crc32_MPEG_table_initialized = false;
// @see pycrc https://github.com/winlinvip/pycrc/blob/master/pycrc/models.py#L238
// crc32('123456789') = 0x0376e6e7
// where it's defined as model:
// 'name': 'crc-32',
// 'width': 32,
// 'poly': 0x4c11db7,
// 'reflect_in': False,
// 'xor_in': 0xffffffff,
// 'reflect_out': False,
// 'xor_out': 0x0,
// 'check': 0x0376e6e7,
uint32_t srs_crc32_mpegts(const void *buf, int size)
{
// @see golang IEEE of hash/crc32/crc32.go
// IEEE is by far and away the most common CRC-32 polynomial.
// Used by ethernet (IEEE 802.3), v.42, fddi, gzip, zip, png, ...
// @remark The poly of CRC32 IEEE is 0x04C11DB7, its reverse is 0xEDB88320,
// please read https://en.wikipedia.org/wiki/Cyclic_redundancy_check
uint32_t poly = 0x04C11DB7;
bool reflect_in = false;
uint32_t xor_in = 0xffffffff;
bool reflect_out = false;
uint32_t xor_out = 0x0;
if (!__crc32_MPEG_table_initialized) {
__crc32_make_table(__crc32_MPEG_table, poly, reflect_in);
__crc32_MPEG_table_initialized = true;
}
return __crc32_table_driven(__crc32_MPEG_table, buf, size, 0x00, reflect_in, xor_in, reflect_out, xor_out);
}
string srs_ts_stream2string(SrsTsStream stream)
{
switch (stream) {
case SrsTsStreamReserved:
return "Reserved";
case SrsTsStreamAudioMp3:
return "MP3";
case SrsTsStreamAudioAAC:
return "AAC";
case SrsTsStreamAudioAC3:
return "AC3";
case SrsTsStreamAudioDTS:
return "AudioDTS";
case SrsTsStreamVideoH264:
return "H.264";
case SrsTsStreamVideoHEVC:
return "H.265";
case SrsTsStreamVideoMpeg4:
return "MP4";
case SrsTsStreamAudioMpeg4:
return "MP4A";
default:
return "Other";
}
}
SrsTsChannel::SrsTsChannel()
{
pid_ = 0;
apply_ = SrsTsPidApplyReserved;
stream_ = SrsTsStreamReserved;
msg_ = NULL;
continuity_counter_ = 0;
context_ = NULL;
}
SrsTsChannel::~SrsTsChannel()
{
srs_freep(msg_);
}
SrsTsMessage::SrsTsMessage(SrsTsChannel *c, SrsTsPacket *p)
{
channel_ = c;
packet_ = p;
ps_helper_ = NULL;
dts_ = pts_ = 0;
sid_ = (SrsTsPESStreamId)0x00;
continuity_counter_ = 0;
PES_packet_length_ = 0;
payload_ = new SrsSimpleStream();
is_discontinuity_ = false;
start_pts_ = 0;
write_pcr_ = false;
}
SrsTsMessage::~SrsTsMessage()
{
srs_freep(payload_);
}
srs_error_t SrsTsMessage::dump(SrsBuffer *stream, int *pnb_bytes)
{
srs_error_t err = srs_success;
if (stream->empty()) {
return err;
}
// xB
int nb_bytes = stream->size() - stream->pos();
if (PES_packet_length_ > 0) {
nb_bytes = srs_min(nb_bytes, PES_packet_length_ - payload_->length());
}
if (nb_bytes > 0) {
if (!stream->require(nb_bytes)) {
return srs_error_new(ERROR_STREAM_CASTER_TS_PSE, "ts: dump PSE bytes failed, requires=%dB", nb_bytes);
}
payload_->append(stream->data() + stream->pos(), nb_bytes);
stream->skip(nb_bytes);
}
if (pnb_bytes)
*pnb_bytes = nb_bytes;
return err;
}
bool SrsTsMessage::completed(int8_t payload_unit_start_indicator)
{
if (PES_packet_length_ == 0) {
return payload_unit_start_indicator;
}
return payload_->length() >= PES_packet_length_;
}
bool SrsTsMessage::fresh()
{
// Note that both must be 0. For PS stream, the payload might be empty but PES_packet_length is not, see
// PsPacketDecodePrivateStream of KernelPSTest. For TS stream, both should be 0 in the same time.
return PES_packet_length_ == 0 && payload_->length() == 0;
}
bool SrsTsMessage::is_audio()
{
return ((sid_ >> 5) & 0x07) == SrsTsPESStreamIdAudioChecker;
}
bool SrsTsMessage::is_video()
{
return ((sid_ >> 4) & 0x0f) == SrsTsPESStreamIdVideoChecker;
}
int SrsTsMessage::stream_number()
{
if (is_audio()) {
return sid_ & 0x1f;
} else if (is_video()) {
return sid_ & 0x0f;
}
return -1;
}
SrsTsMessage *SrsTsMessage::detach()
{
// @remark the packet cannot be used, but channel is ok.
SrsTsMessage *cp = new SrsTsMessage(channel_, NULL);
cp->ps_helper_ = ps_helper_;
cp->start_pts_ = start_pts_;
cp->write_pcr_ = write_pcr_;
cp->is_discontinuity_ = is_discontinuity_;
cp->dts_ = dts_;
cp->pts_ = pts_;
cp->sid_ = sid_;
cp->PES_packet_length_ = PES_packet_length_;
cp->continuity_counter_ = continuity_counter_;
srs_freep(cp->payload_);
cp->payload_ = payload_;
payload_ = NULL;
return cp;
}
ISrsTsHandler::ISrsTsHandler()
{
}
ISrsTsHandler::~ISrsTsHandler()
{
}
ISrsTsContext::ISrsTsContext()
{
}
ISrsTsContext::~ISrsTsContext()
{
}
SrsTsContext::SrsTsContext()
{
ready_ = false;
pure_audio_ = false;
sync_byte_ = 0x47; // ts default sync byte.
vcodec_ = SrsVideoCodecIdReserved;
acodec_ = SrsAudioCodecIdReserved1;
}
SrsTsContext::~SrsTsContext()
{
std::map<int, SrsTsChannel *>::iterator it;
for (it = pids_.begin(); it != pids_.end(); ++it) {
SrsTsChannel *channel = it->second;
srs_freep(channel);
}
pids_.clear();
}
bool SrsTsContext::is_pure_audio()
{
return pure_audio_;
}
void SrsTsContext::on_pmt_parsed()
{
pure_audio_ = true;
std::map<int, SrsTsChannel *>::iterator it;
for (it = pids_.begin(); it != pids_.end(); ++it) {
SrsTsChannel *channel = it->second;
if (channel->apply_ == SrsTsPidApplyVideo) {
pure_audio_ = false;
}
}
}
void SrsTsContext::reset()
{
ready_ = false;
vcodec_ = SrsVideoCodecIdReserved;
acodec_ = SrsAudioCodecIdReserved1;
}
SrsTsChannel *SrsTsContext::get(int pid)
{
if (pids_.find(pid) == pids_.end()) {
return NULL;
}
return pids_[pid];
}
void SrsTsContext::set(int pid, SrsTsPidApply apply_pid, SrsTsStream stream)
{
SrsTsChannel *channel = NULL;
if (pids_.find(pid) == pids_.end()) {
channel = new SrsTsChannel();
channel->context_ = this;
pids_[pid] = channel;
} else {
channel = pids_[pid];
}
channel->pid_ = pid;
channel->apply_ = apply_pid;
channel->stream_ = stream;
}
srs_error_t SrsTsContext::decode(SrsBuffer *stream, ISrsTsHandler *handler)
{
srs_error_t err = srs_success;
// parse util EOF of stream.
// for example, parse multiple times for the PES_packet_length(0) packet.
while (!stream->empty()) {
SrsUniquePtr<SrsTsPacket> packet(new SrsTsPacket(this));
SrsTsMessage *msg_raw = NULL;
if ((err = packet->decode(stream, &msg_raw)) != srs_success) {
return srs_error_wrap(err, "ts: ts packet decode");
}
if (!msg_raw) {
continue;
}
SrsUniquePtr<SrsTsMessage> msg(msg_raw);
if ((err = handler->on_ts_message(msg.get())) != srs_success) {
return srs_error_wrap(err, "ts: handle ts message");
}
}
return err;
}
srs_error_t SrsTsContext::encode(ISrsStreamWriter *writer, SrsTsMessage *msg, SrsVideoCodecId vc, SrsAudioCodecId ac)
{
srs_error_t err = srs_success;
SrsTsStream vs, as;
int16_t video_pid = 0, audio_pid = 0;
switch (vc) {
case SrsVideoCodecIdAVC:
vs = SrsTsStreamVideoH264;
video_pid = TS_VIDEO_AVC_PID;
break;
case SrsVideoCodecIdHEVC:
vs = SrsTsStreamVideoHEVC;
video_pid = TS_VIDEO_AVC_PID;
break;
case SrsVideoCodecIdDisabled:
vs = SrsTsStreamReserved;
break;
case SrsVideoCodecIdReserved:
case SrsVideoCodecIdReserved1:
case SrsVideoCodecIdReserved2:
case SrsVideoCodecIdSorensonH263:
case SrsVideoCodecIdScreenVideo:
case SrsVideoCodecIdOn2VP6:
case SrsVideoCodecIdOn2VP6WithAlphaChannel:
case SrsVideoCodecIdScreenVideoVersion2:
case SrsVideoCodecIdAV1:
case SrsVideoCodecIdVP9:
vs = SrsTsStreamReserved;
break;
}
switch (ac) {
case SrsAudioCodecIdAAC:
as = SrsTsStreamAudioAAC;
audio_pid = TS_AUDIO_AAC_PID;
break;
case SrsAudioCodecIdMP3:
as = SrsTsStreamAudioMp3;
audio_pid = TS_AUDIO_MP3_PID;
break;
case SrsAudioCodecIdDisabled:
as = SrsTsStreamReserved;
break;
case SrsAudioCodecIdReserved1:
case SrsAudioCodecIdLinearPCMPlatformEndian:
case SrsAudioCodecIdADPCM:
case SrsAudioCodecIdLinearPCMLittleEndian:
case SrsAudioCodecIdNellymoser16kHzMono:
case SrsAudioCodecIdNellymoser8kHzMono:
case SrsAudioCodecIdNellymoser:
case SrsAudioCodecIdReservedG711AlawLogarithmicPCM:
case SrsAudioCodecIdReservedG711MuLawLogarithmicPCM:
case SrsAudioCodecIdReserved:
case SrsAudioCodecIdSpeex:
case SrsAudioCodecIdReservedMP3_8kHz:
case SrsAudioCodecIdReservedDeviceSpecificSound:
case SrsAudioCodecIdOpus:
as = SrsTsStreamReserved;
break;
}
if (as == SrsTsStreamReserved && vs == SrsTsStreamReserved) {
return srs_error_new(ERROR_HLS_NO_STREAM, "ts: no a/v stream, vcodec=%d, acodec=%d", vc, ac);
}
// When any codec changed, write PAT/PMT table.
if (vcodec_ != vc || acodec_ != ac) {
if (vcodec_ != SrsVideoCodecIdReserved || acodec_ != SrsAudioCodecIdReserved1) {
srs_trace("TS: Refresh PMT when vcodec=%d=>%d, acodec=%d=>%d", vcodec_, vc, acodec_, ac);
}
vcodec_ = vc;
acodec_ = ac;
if ((err = encode_pat_pmt(writer, video_pid, vs, audio_pid, as)) != srs_success) {
return srs_error_wrap(err, "ts: encode PAT/PMT");
}
}
// encode the media frame to PES packets over TS.
if (msg->is_audio()) {
return encode_pes(writer, msg, audio_pid, as, vs == SrsTsStreamReserved);
} else {
return encode_pes(writer, msg, video_pid, vs, vs == SrsTsStreamReserved);
}
}
srs_error_t SrsTsContext::encode_pat_pmt(ISrsStreamWriter *writer, int16_t vpid, SrsTsStream vs, int16_t apid, SrsTsStream as)
{
srs_error_t err = srs_success;
bool codec_ok = (vs == SrsTsStreamVideoH264 || as == SrsTsStreamAudioAAC || as == SrsTsStreamAudioMp3);
codec_ok = codec_ok ? true : (vs == SrsTsStreamVideoHEVC);
if (!codec_ok) {
return srs_error_new(ERROR_HLS_NO_STREAM, "ts: no PID, vs=%d, as=%d", vs, as);
}
int16_t pmt_number = TS_PMT_NUMBER;
int16_t pmt_pid = TS_PMT_PID;
if (true) {
SrsUniquePtr<SrsTsPacket> pkt(SrsTsPacket::create_pat(this, pmt_number, pmt_pid));
pkt->sync_byte_ = sync_byte_;
SrsUniquePtr<char[]> buf(new char[SRS_TS_PACKET_SIZE]);
// set the left bytes with 0xFF.
int nb_buf = pkt->size();
srs_assert(nb_buf < SRS_TS_PACKET_SIZE);
memset(buf.get() + nb_buf, 0xFF, SRS_TS_PACKET_SIZE - nb_buf);
SrsBuffer stream(buf.get(), nb_buf);
if ((err = pkt->encode(&stream)) != srs_success) {
return srs_error_wrap(err, "ts: encode packet");
}
if ((err = writer->write(buf.get(), SRS_TS_PACKET_SIZE, NULL)) != srs_success) {
return srs_error_wrap(err, "ts: write packet");
}
}
if (true) {
SrsUniquePtr<SrsTsPacket> pkt(SrsTsPacket::create_pmt(this, pmt_number, pmt_pid, vpid, vs, apid, as));
pkt->sync_byte_ = sync_byte_;
SrsUniquePtr<char[]> buf(new char[SRS_TS_PACKET_SIZE]);
// set the left bytes with 0xFF.
int nb_buf = pkt->size();
srs_assert(nb_buf < SRS_TS_PACKET_SIZE);
memset(buf.get() + nb_buf, 0xFF, SRS_TS_PACKET_SIZE - nb_buf);
SrsBuffer stream(buf.get(), nb_buf);
if ((err = pkt->encode(&stream)) != srs_success) {
return srs_error_wrap(err, "ts: encode packet");
}
if ((err = writer->write(buf.get(), SRS_TS_PACKET_SIZE, NULL)) != srs_success) {
return srs_error_wrap(err, "ts: write packet");
}
}
// When PAT and PMT are writen, the context is ready now.
ready_ = true;
return err;
}
srs_error_t SrsTsContext::encode_pes(ISrsStreamWriter *writer, SrsTsMessage *msg, int16_t pid, SrsTsStream sid, bool pure_audio)
{
srs_error_t err = srs_success;
// Sometimes, the context is not ready(PAT/PMT write failed), error in this situation.
if (!ready_) {
return srs_error_new(ERROR_TS_CONTEXT_NOT_READY, "ts: not ready");
}
if (msg->payload_->length() == 0) {
return err;
}
bool codec_ok = (sid == SrsTsStreamVideoH264 || sid == SrsTsStreamAudioAAC || sid == SrsTsStreamAudioMp3);
codec_ok = codec_ok ? true : (sid == SrsTsStreamVideoHEVC);
if (!codec_ok) {
srs_info("ts: ignore the unknown stream, sid=%d", sid);
return err;
}
SrsTsChannel *channel = get(pid);
srs_assert(channel);
char *start = msg->payload_->bytes();
char *end = start + msg->payload_->length();
char *p = start;
while (p < end) {
SrsTsPacket *pkt_raw = NULL;
if (p == start) {
// write pcr according to message.
bool write_pcr = msg->write_pcr_;
// for pure audio, always write pcr.
// TODO: FIXME: maybe only need to write at begin and end of ts.
if (pure_audio && msg->is_audio()) {
write_pcr = true;
}
// it's ok to set pcr equals to dts,
// @see https://github.com/ossrs/srs/issues/311
// Fig. 3.18. Program Clock Reference of Digital-Video-and-Audio-Broadcasting-Technology, page 65
// In MPEG-2, these are the "Program Clock Refer- ence" (PCR) values which are
// nothing else than an up-to-date copy of the STC counter fed into the transport
// stream at a certain time. The data stream thus carries an accurate internal
// "clock time". All coding and de- coding processes are controlled by this clock
// time. To do this, the receiver, i.e. the MPEG decoder, must read out the
// "clock time", namely the PCR values, and compare them with its own internal
// system clock, that is to say its own 42 bit counter.
int64_t pcr = write_pcr ? msg->dts_ : -1;
// TODO: FIXME: finger it why use discontinuity of msg.
pkt_raw = SrsTsPacket::create_pes_first(this,
pid, msg->sid_, channel->continuity_counter_++, msg->is_discontinuity_,
pcr, msg->dts_, msg->pts_, msg->payload_->length());
} else {
pkt_raw = SrsTsPacket::create_pes_continue(this, pid, msg->sid_, channel->continuity_counter_++);
}
SrsUniquePtr<SrsTsPacket> pkt(pkt_raw);
pkt->sync_byte_ = sync_byte_;
SrsUniquePtr<char[]> buf(new char[SRS_TS_PACKET_SIZE]);
// set the left bytes with 0xFF.
int nb_buf = pkt->size();
srs_assert(nb_buf < SRS_TS_PACKET_SIZE);
int left = (int)srs_min(end - p, SRS_TS_PACKET_SIZE - nb_buf);
int nb_stuffings = SRS_TS_PACKET_SIZE - nb_buf - left;
if (nb_stuffings > 0) {
// set all bytes to stuffings.
memset(buf.get(), 0xFF, SRS_TS_PACKET_SIZE);
// padding with stuffings.
pkt->padding(nb_stuffings);
// size changed, recalc it.
nb_buf = pkt->size();
srs_assert(nb_buf < SRS_TS_PACKET_SIZE);
left = (int)srs_min(end - p, SRS_TS_PACKET_SIZE - nb_buf);
nb_stuffings = SRS_TS_PACKET_SIZE - nb_buf - left;
srs_assert(nb_stuffings == 0);
}
memcpy(buf.get() + nb_buf, p, left);
p += left;
SrsBuffer stream(buf.get(), nb_buf);
if ((err = pkt->encode(&stream)) != srs_success) {
return srs_error_wrap(err, "ts: encode packet");
}
if ((err = writer->write(buf.get(), SRS_TS_PACKET_SIZE, NULL)) != srs_success) {
return srs_error_wrap(err, "ts: write packet");
}
}
return err;
}
SrsTsPacket::SrsTsPacket(ISrsTsContext *c)
{
context_ = c;
sync_byte_ = 0;
transport_error_indicator_ = 0;
payload_unit_start_indicator_ = 0;
transport_priority_ = 0;
pid_ = SrsTsPidPAT;
transport_scrambling_control_ = SrsTsScrambledDisabled;
adaption_field_control_ = SrsTsAdaptationFieldTypeReserved;
continuity_counter_ = 0;
adaptation_field_ = NULL;
payload_ = NULL;
}
SrsTsPacket::~SrsTsPacket()
{
srs_freep(adaptation_field_);
srs_freep(payload_);
}
srs_error_t SrsTsPacket::decode(SrsBuffer *stream, SrsTsMessage **ppmsg)
{
srs_error_t err = srs_success;
int pos = stream->pos();
// 4B ts packet header.
if (!stream->require(4)) {
return srs_error_new(ERROR_STREAM_CASTER_TS_HEADER, "ts: decode packet");
}
sync_byte_ = stream->read_1bytes();
if (sync_byte_ != 0x47) {
return srs_error_new(ERROR_STREAM_CASTER_TS_SYNC_BYTE, "ts: sync_bytes must be 0x47, actual=%#x", sync_byte_);
}
int16_t pidv = stream->read_2bytes();
transport_error_indicator_ = (pidv >> 15) & 0x01;
payload_unit_start_indicator_ = (pidv >> 14) & 0x01;
transport_priority_ = (pidv >> 13) & 0x01;
pid_ = (SrsTsPid)(pidv & 0x1FFF);
int8_t ccv = stream->read_1bytes();
transport_scrambling_control_ = (SrsTsScrambled)((ccv >> 6) & 0x03);
adaption_field_control_ = (SrsTsAdaptationFieldType)((ccv >> 4) & 0x03);
continuity_counter_ = ccv & 0x0F;
// TODO: FIXME: create pids map when got new pid.
srs_info("ts: header sync=%#x error=%d unit_start=%d priotiry=%d pid=%d scrambling=%d adaption=%d counter=%d",
sync_byte, transport_error_indicator, payload_unit_start_indicator, transport_priority, pid,
transport_scrambling_control, adaption_field_control, continuity_counter);
// optional: adaptation field
if (adaption_field_control_ == SrsTsAdaptationFieldTypeAdaptionOnly || adaption_field_control_ == SrsTsAdaptationFieldTypeBoth) {
srs_freep(adaptation_field_);
adaptation_field_ = new SrsTsAdaptationField(this);
if ((err = adaptation_field_->decode(stream)) != srs_success) {
return srs_error_wrap(err, "ts: demux af field");
}
srs_verbose("ts: demux af ok.");
}
// calc the user defined data size for payload.
int nb_payload = SRS_TS_PACKET_SIZE - (stream->pos() - pos);
// optional: payload.
if (adaption_field_control_ == SrsTsAdaptationFieldTypePayloadOnly || adaption_field_control_ == SrsTsAdaptationFieldTypeBoth) {
if (pid_ == SrsTsPidPAT) {
// 2.4.4.3 Program association Table
srs_freep(payload_);
payload_ = new SrsTsPayloadPAT(this);
} else {
SrsTsChannel *channel = context_->get(pid_);
if (channel && channel->apply_ == SrsTsPidApplyPMT) {
// 2.4.4.8 Program Map Table
srs_freep(payload_);
payload_ = new SrsTsPayloadPMT(this);
} else if (channel && (channel->apply_ == SrsTsPidApplyVideo || channel->apply_ == SrsTsPidApplyAudio)) {
// 2.4.3.6 PES packet
srs_freep(payload_);
payload_ = new SrsTsPayloadPES(this);
} else {
// left bytes as reserved.
stream->skip(srs_min(stream->left(), nb_payload));
}
}
if (payload_ && (err = payload_->decode(stream, ppmsg)) != srs_success) {
return srs_error_wrap(err, "ts: demux payload");
}
}
return err;
}
int SrsTsPacket::size()
{
int sz = 4;
sz += adaptation_field_ ? adaptation_field_->size() : 0;
sz += payload_ ? payload_->size() : 0;
return sz;
}
srs_error_t SrsTsPacket::encode(SrsBuffer *stream)
{
srs_error_t err = srs_success;
// 4B ts packet header.
if (!stream->require(4)) {
return srs_error_new(ERROR_STREAM_CASTER_TS_HEADER, "ts: requires 4+ bytes");
}
stream->write_1bytes(sync_byte_);
int16_t pidv = pid_ & 0x1FFF;
pidv |= (transport_priority_ << 13) & 0x2000;
pidv |= (transport_error_indicator_ << 15) & 0x8000;
pidv |= (payload_unit_start_indicator_ << 14) & 0x4000;
stream->write_2bytes(pidv);
int8_t ccv = continuity_counter_ & 0x0F;
ccv |= (transport_scrambling_control_ << 6) & 0xC0;
ccv |= (adaption_field_control_ << 4) & 0x30;
stream->write_1bytes(ccv);
srs_info("ts: header sync=%#x error=%d unit_start=%d priotiry=%d pid=%d scrambling=%d adaption=%d counter=%d",
sync_byte, transport_error_indicator, payload_unit_start_indicator, transport_priority, pid,
transport_scrambling_control, adaption_field_control, continuity_counter);
// optional: adaptation field
if (adaptation_field_) {
if ((err = adaptation_field_->encode(stream)) != srs_success) {
return srs_error_wrap(err, "ts: mux af field");
}
srs_verbose("ts: mux af ok.");
}
// optional: payload.
if (payload_) {
if ((err = payload_->encode(stream)) != srs_success) {
return srs_error_wrap(err, "ts: mux payload");
}
srs_verbose("ts: mux payload ok.");
}
return err;
}
void SrsTsPacket::padding(int nb_stuffings)
{
if (!adaptation_field_) {
SrsTsAdaptationField *af = new SrsTsAdaptationField(this);
adaptation_field_ = af;
af->adaption_field_length_ = 0; // calc in size.
af->discontinuity_indicator_ = 0;
af->random_access_indicator_ = 0;
af->elementary_stream_priority_indicator_ = 0;
af->PCR_flag_ = 0;
af->OPCR_flag_ = 0;
af->splicing_point_flag_ = 0;
af->transport_private_data_flag_ = 0;
af->adaptation_field_extension_flag_ = 0;
// consume the af size if possible.
nb_stuffings = srs_max(0, nb_stuffings - af->size());
}
adaptation_field_->nb_af_reserved_ = nb_stuffings;
// set payload with af.
if (adaption_field_control_ == SrsTsAdaptationFieldTypePayloadOnly) {
adaption_field_control_ = SrsTsAdaptationFieldTypeBoth;
}
}
SrsTsPacket *SrsTsPacket::create_pat(ISrsTsContext *context, int16_t pmt_number, int16_t pmt_pid)
{
SrsTsPacket *pkt = new SrsTsPacket(context);
pkt->sync_byte_ = 0x47;
pkt->transport_error_indicator_ = 0;
pkt->payload_unit_start_indicator_ = 1;
pkt->transport_priority_ = 0;
pkt->pid_ = SrsTsPidPAT;
pkt->transport_scrambling_control_ = SrsTsScrambledDisabled;
pkt->adaption_field_control_ = SrsTsAdaptationFieldTypePayloadOnly;
pkt->continuity_counter_ = 0;
pkt->adaptation_field_ = NULL;
SrsTsPayloadPAT *pat = new SrsTsPayloadPAT(pkt);
pkt->payload_ = pat;
pat->pointer_field = 0;
pat->table_id = SrsTsPsiIdPas;
pat->section_syntax_indicator = 1;
pat->section_length = 0; // calc in size.
pat->transport_stream_id = 1;
pat->version_number = 0;
pat->current_next_indicator = 1;
pat->section_number = 0;
pat->last_section_number = 0;
pat->programs.push_back(new SrsTsPayloadPATProgram(pmt_number, pmt_pid));
pat->CRC_32 = 0; // calc in encode.
return pkt;
}
SrsTsPacket *SrsTsPacket::create_pmt(ISrsTsContext *context,
int16_t pmt_number, int16_t pmt_pid, int16_t vpid, SrsTsStream vs, int16_t apid, SrsTsStream as)
{
SrsTsPacket *pkt = new SrsTsPacket(context);
pkt->sync_byte_ = 0x47;
pkt->transport_error_indicator_ = 0;
pkt->payload_unit_start_indicator_ = 1;
pkt->transport_priority_ = 0;
pkt->pid_ = (SrsTsPid)pmt_pid;
pkt->transport_scrambling_control_ = SrsTsScrambledDisabled;
pkt->adaption_field_control_ = SrsTsAdaptationFieldTypePayloadOnly;
// TODO: FIXME: maybe should continuous in channel.
pkt->continuity_counter_ = 0;
pkt->adaptation_field_ = NULL;
SrsTsPayloadPMT *pmt = new SrsTsPayloadPMT(pkt);
pkt->payload_ = pmt;
pmt->pointer_field = 0;
pmt->table_id = SrsTsPsiIdPms;
pmt->section_syntax_indicator = 1;
pmt->section_length = 0; // calc in size.
pmt->program_number = pmt_number;
pmt->version_number = 0;
pmt->current_next_indicator = 1;
pmt->section_number = 0;
pmt->last_section_number = 0;
// Here we must get the correct codec.
bool codec_ok = (vs == SrsTsStreamVideoH264 || as == SrsTsStreamAudioAAC || as == SrsTsStreamAudioMp3);
codec_ok = codec_ok ? true : (vs == SrsTsStreamVideoHEVC);
srs_assert(codec_ok);
// if mp3 or aac specified, use audio to carry pcr.
if (as == SrsTsStreamAudioAAC || as == SrsTsStreamAudioMp3) {
// use audio to carray pcr by default.
// for hls, there must be atleast one audio channel.
pmt->PCR_PID = apid;
pmt->infos.push_back(new SrsTsPayloadPMTESInfo(as, apid));
}
// If h.264/h.265 specified, use video to carry pcr.
codec_ok = (vs == SrsTsStreamVideoH264);
codec_ok = codec_ok ? true : (vs == SrsTsStreamVideoHEVC);
if (codec_ok) {
pmt->PCR_PID = vpid;
pmt->infos.push_back(new SrsTsPayloadPMTESInfo(vs, vpid));
}
pmt->CRC_32 = 0; // calc in encode.
return pkt;
}
SrsTsPacket *SrsTsPacket::create_pes_first(ISrsTsContext *context,
int16_t pid, SrsTsPESStreamId sid, uint8_t continuity_counter, bool discontinuity,
int64_t pcr, int64_t dts, int64_t pts, int size)
{
SrsTsPacket *pkt = new SrsTsPacket(context);
pkt->sync_byte_ = 0x47;
pkt->transport_error_indicator_ = 0;
pkt->payload_unit_start_indicator_ = 1;
pkt->transport_priority_ = 0;
pkt->pid_ = (SrsTsPid)pid;
pkt->transport_scrambling_control_ = SrsTsScrambledDisabled;
pkt->adaption_field_control_ = SrsTsAdaptationFieldTypePayloadOnly;
pkt->continuity_counter_ = continuity_counter;
pkt->adaptation_field_ = NULL;
SrsTsPayloadPES *pes = new SrsTsPayloadPES(pkt);
pkt->payload_ = pes;
if (pcr >= 0) {
// Ignore coverage for PCR, we don't use it in HLS.
// LCOV_EXCL_START
SrsTsAdaptationField *af = new SrsTsAdaptationField(pkt);
pkt->adaptation_field_ = af;
pkt->adaption_field_control_ = SrsTsAdaptationFieldTypeBoth;
af->adaption_field_length_ = 0; // calc in size.
af->discontinuity_indicator_ = discontinuity;
af->random_access_indicator_ = 0;
af->elementary_stream_priority_indicator_ = 0;
af->PCR_flag_ = 1;
af->OPCR_flag_ = 0;
af->splicing_point_flag_ = 0;
af->transport_private_data_flag_ = 0;
af->adaptation_field_extension_flag_ = 0;
af->program_clock_reference_base_ = pcr;
af->program_clock_reference_extension_ = 0;
// LCOV_EXCL_STOP
}
pes->pes_.packet_start_code_prefix_ = 0x01;
pes->pes_.stream_id_ = (uint8_t)sid;
pes->pes_.PES_packet_length_ = (size > 0xFFFF) ? 0 : size;
pes->pes_.PES_scrambling_control_ = 0;
pes->pes_.PES_priority_ = 0;
pes->pes_.data_alignment_indicator_ = 0;
pes->pes_.copyright_ = 0;
pes->pes_.original_or_copy_ = 0;
pes->pes_.PTS_DTS_flags_ = (dts == pts) ? 0x02 : 0x03;
pes->pes_.ESCR_flag_ = 0;
pes->pes_.ES_rate_flag_ = 0;
pes->pes_.DSM_trick_mode_flag_ = 0;
pes->pes_.additional_copy_info_flag_ = 0;
pes->pes_.PES_CRC_flag_ = 0;
pes->pes_.PES_extension_flag_ = 0;
pes->pes_.PES_header_data_length_ = 0; // calc in size.
pes->pes_.pts_ = pts;
pes->pes_.dts_ = dts;
return pkt;
}
SrsTsPacket *SrsTsPacket::create_pes_continue(ISrsTsContext *context, int16_t pid, SrsTsPESStreamId sid, uint8_t continuity_counter)
{
SrsTsPacket *pkt = new SrsTsPacket(context);
pkt->sync_byte_ = 0x47;
pkt->transport_error_indicator_ = 0;
pkt->payload_unit_start_indicator_ = 0;
pkt->transport_priority_ = 0;
pkt->pid_ = (SrsTsPid)pid;
pkt->transport_scrambling_control_ = SrsTsScrambledDisabled;
pkt->adaption_field_control_ = SrsTsAdaptationFieldTypePayloadOnly;
pkt->continuity_counter_ = continuity_counter;
pkt->adaptation_field_ = NULL;
pkt->payload_ = NULL;
return pkt;