This repository has been archived by the owner on Jan 26, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
tsprocessor.cpp
4683 lines (4299 loc) · 132 KB
/
tsprocessor.cpp
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
/*
* If not stated otherwise in this file or this component's license file the
* following copyright and licenses apply:
*
* Copyright 2018 RDK Management
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file tsprocessor.cpp
* @brief Source file for player context
*/
#include <stdlib.h>
#include <memory.h>
#include <math.h>
#include <assert.h>
#include <unistd.h>
#include <errno.h>
#include <stdint.h>
#include <sys/time.h>
#include "priv_aamp.h"
#include "StreamAbstractionAAMP.h"
#include "tsprocessor.h"
#include "AampUtils.h"
/**
* @brief NOP function used to controll logging
* @param[in] format printf style format string
*/
void print_nop(const char *format, ...){}
#ifdef LOG_ENABLE_TRACE
#define TRACE1 AAMPLOG_TRACE("PC: TRACE1 %s:%d:"); AAMPLOG_TRACE
#define TRACE2 AAMPLOG_TRACE("PC: TRACE2 "); AAMPLOG_TRACE
#define TRACE3 AAMPLOG_TRACE("PC: TRACE3 "); AAMPLOG_TRACE
#define TRACE4 AAMPLOG_TRACE("PC: TRACE4 "); AAMPLOG_TRACE
#else
#define TRACE1 print_nop
#define TRACE2 print_nop
#define TRACE3 print_nop
#define TRACE4 print_nop
#endif
#ifndef LOG_ENABLE
#define DEBUG print_nop
#define INFO print_nop
#else
#define INFO AAMPLOG_INFO("PC: INFO " ); AAMPLOG_INFO
#define DEBUG AAMPLOG_TRACE("PC: DEBUG " ); AAMPLOG_TRACE
#endif
#define LOG_WARNINGS_AND_ERRORS
#undef ERROR
#ifndef LOG_WARNINGS_AND_ERRORS
#define NOTICE print_nop
#define WARNING print_nop
#define ERROR print_nop
#define FATAL print_nop
#else
#define NOTICE(FORMAT, ...) AAMPLOG(mLogObj, eLOGLEVEL_INFO, "INFO", FORMAT, ##__VA_ARGS__)
#define WARNING(FORMAT, ...) AAMPLOG(mLogObj, eLOGLEVEL_WARN, "WARN", FORMAT, ##__VA_ARGS__)
#define ERROR(FORMAT, ...) AAMPLOG(mLogObj, eLOGLEVEL_ERROR, "ERROR", FORMAT, ##__VA_ARGS__)
#endif
#define DUMP_PACKET 0
#define PACKET_SIZE (188)
#define MAX_PACKET_SIZE (208)
#define FIXED_FRAME_RATE (10)
#define FRAME_WIDTH_MAX (1920)
#define FRAME_HEIGHT_MAX (1080)
#define WAIT_FOR_DATA_MILLISEC 100
#define WAIT_FOR_DATA_MAX_RETRIES 1
#define MAX_PMT_SECTION_SIZE (1021)
#define PATPMT_MAX_SIZE (2*1024)
#define PAT_SPTS_SIZE (13)
#define PAT_TABLE_ENTRY_SIZE (4)
/** Maximum PTS value */
#define MAX_PTS (uint33_t::max_value().value)
/** Maximum descriptor present for a elementary stream */
#define MAX_DESCRIPTOR (4)
#define I_FRAME (0x1)
#define P_FRAME (0x2)
#define B_FRAME (0x4)
#define ALL_FRAMES (0x7)
#define SEQ_START (0x10)
#define IDX_BUFF_SIZE (128*1024)
/*Throttle Default Parameters - From DVRManager*/
#define DEFAULT_THROTTLE_MAX_DELAY_MS 500
#define DEFAULT_THROTTLE_MAX_DIFF_SEGMENTS_MS 400
#define DEFAULT_THROTTLE_DELAY_IGNORED_MS 200
#define DEFAULT_THROTTLE_DELAY_FOR_DISCONTINUITY_MS 2000
#define PES_STATE_WAITING_FOR_HEADER 0
#define PES_STATE_GETTING_HEADER 1
#define PES_STATE_GETTING_HEADER_EXTENSION 2
#define PES_STATE_GETTING_ES 3
#define PAYLOAD_UNIT_START(packetStart) ( packetStart[1] & 0x40)
#define CONTAINS_PAYLOAD(packetStart) ( packetStart[3] & 0x10)
#define IS_PES_PACKET_START(a) ( (a[0] == 0 )&& (a[1] == 0 ) &&(a[2] == 1 ))
#define PES_OPTIONAL_HEADER_PRESENT(pesStart) ( ( pesStart[6] & 0xC0) == 0x80 )
#define PES_HEADER_LENGTH 6
#define PES_OPTIONAL_HEADER_LENGTH(pesStart) (pesStart[PES_HEADER_LENGTH+2])
#define PES_MIN_DATA (PES_HEADER_LENGTH+3)
#define ADAPTATION_FIELD_PRESENT(mpegbuf) ((mpegbuf[3] & 0x20) == 0x20)
#define PES_PAYLOAD_LENGTH(pesStart) (pesStart[4]<<8|pesStart[5])
#define MAX_FIRST_PTS_OFFSET (uint33_t{45000}) /*500 ms*/
#define DESCRIPTOR_TAG_SUBTITLE 0x59
#define DESCRIPTOR_TAG_AC3 0x6A
#define DESCRIPTOR_TAG_EAC3 0x7A
//#define DEBUG_DEMUX_TRACK 1
#ifdef DEBUG_DEMUX_TRACK
#define DEBUG_DEMUX(a...) { \
if (type == DEBUG_DEMUX_TRACK || DEBUG_DEMUX_TRACK == 0xff) \
{ \
AAMPLOG_WARN("PC: DEBUG_DEMUX Track %d : ", DEBUG_DEMUX_TRACK );\
logprintf(a); \
}\
else \
{ \
DEBUG(a); \
}\
}
#else
#define DEBUG_DEMUX DEBUG
#endif
/**
* @enum StreamType
* @brief Types of streams
*/
enum StreamType
{
eSTREAM_TYPE_MPEG2_VIDEO = 0x02, /**< MPEG2 Video */
eSTREAM_TYPE_MPEG1_AUDIO = 0x03, /**< MPEG1 Audio */
eSTREAM_TYPE_MPEG2_AUDIO = 0x04, /**< MPEG2 Audio */
eSTREAM_TYPE_PES_PRIVATE = 0x06, /**< PES packets containing private data */
eSTREAM_TYPE_AAC_ADTS = 0x0F, /**< MPEG2 AAC Audio */
eSTREAM_TYPE_AAC_LATM = 0x11, /**< MPEG4 LATM AAC Audio */
eSTREAM_TYPE_DSM_CC = 0x15, /**< ISO/IEC13818-6 DSM CC deferred association tag with ID3 metadata */
eSTREAM_TYPE_H264 = 0x1B, /**< H.264 Video */
eSTREAM_TYPE_HEVC_VIDEO = 0x24, /**< HEVC video */
eSTREAM_TYPE_ATSC_VIDEO = 0x80, /**< ATSC Video */
eSTREAM_TYPE_ATSC_AC3 = 0x81, /**< ATSC AC3 Audio */
eSTREAM_TYPE_HDMV_DTS = 0x82, /**< HDMV DTS Audio */
eSTREAM_TYPE_LPCM_AUDIO = 0x83, /**< LPCM Audio */
eSTREAM_TYPE_ATSC_AC3PLUS = 0x84, /**< SDDS Audio */
eSTREAM_TYPE_DTSHD_AUDIO = 0x86, /**< DTS-HD Audio */
eSTREAM_TYPE_ATSC_EAC3 = 0x87, /**< ATSC E-AC3 Audio */
eSTREAM_TYPE_DTS_AUDIO = 0x8A, /**< DTS Audio */
eSTREAM_TYPE_AC3_AUDIO = 0x91, /**< A52b/AC3 Audio */
eSTREAM_TYPE_SDDS_AUDIO1 = 0x94 /**< SDDS Audio */
};
static unsigned long long mTimeAdjust;
static bool mbInduceRollover;
void tsdemuxer_InduceRollover( bool enable )
{ // for use by aampcli.exe - allows induced PTS rollover to be triggered or (re)disabled
mTimeAdjust = 0;
mbInduceRollover = enable;
}
/**
* @brief extract 33 bit timestamp from ts packet header
* @param ptr pointer to first of five bytes encoding a 33 bit PTS timestamp
* @return 33 bit unsigned integer (which fits in long long)
*/
static uint33_t Extract33BitTimestamp( const unsigned char *ptr )
{
unsigned long long v; // this is to hold a 64bit integer, lowest 36 bits contain a timestamp with markers
v = (unsigned long long) (ptr[0] & 0x0F) << 32
| (unsigned long long) ptr[1] << 24 | (unsigned long long) ptr[2] << 16
| (unsigned long long) ptr[3] << 8 | (unsigned long long) ptr[4];
unsigned long long timeStamp = 0;
timeStamp |= (v >> 3) & (0x0007ULL << 30); // top 3 bits, shifted left by 3, other bits zeroed out
timeStamp |= (v >> 2) & (0x7fff << 15); // middle 15 bits
timeStamp |= (v >> 1) & (0x7fff << 0); // bottom 15 bits
if( mbInduceRollover )
{
mTimeAdjust = (MAX_PTS-90000*10) - timeStamp;
mbInduceRollover = false;
}
timeStamp += mTimeAdjust;
return {timeStamp};
}
/**
* @brief std::exchange for pre-c++14 compiler
* @param obj - object whose value to replace
* @param new_value - the value to assign to obj
* @return The old value of obj
*/
template<class T, class U = T>
T exchange(T& obj, U&& new_value)
{
T old_value = std::move(obj);
obj = std::forward<U>(new_value);
return old_value;
}
/**
* @class Demuxer
* @brief Software demuxer of MPEGTS
*/
class Demuxer
{
private:
AampLogManager *mLogObj;
class PrivateInstanceAAMP *aamp;
int pes_state;
int pes_header_ext_len;
int pes_header_ext_read;
GrowableBuffer pes_header;
GrowableBuffer es;
double position;
double duration;
uint33_t base_pts;
uint33_t current_pts;
uint33_t current_dts;
uint33_t first_pts;
bool update_first_pts;
MediaType type;
bool trickmode;
bool finalized_base_pts;
int sentESCount;
bool allowPtsRewind;
bool reached_steady_state;
/**
* @brief Sends elementary stream with proper PTS
*/
void send()
{
if( !reached_steady_state )
{
if ((base_pts > current_pts)
|| (current_dts && base_pts > current_dts))
{
WARNING("Discard ES Type %d position %f base_pts %llu current_pts %llu diff %f seconds length %d",
type, position, base_pts.value, current_pts.value, (double)(base_pts - current_pts) / 90000, (int)es.len );
es.len = 0;
return;
}
if (base_pts + uint33_t::half_max() > current_pts + uint33_t::half_max())
{
WARNING("Discard ES Type %d position %f base_pts %llu current_pts %llu base_pts+half_max %llu current_pts+half_max %llu",
type, position, base_pts.value, current_pts.value, (base_pts+uint33_t::half_max()).value, (current_pts+uint33_t::half_max()).value);
es.len = 0;
return;
}
reached_steady_state = true;
}
double pts = position;
double dts;
if (!trickmode)
{
pts += (double)(current_pts - base_pts) / 90000;
}
if (!trickmode && current_dts)
{
dts = position + (double)(current_dts - base_pts) / 90000;
}
else
{
dts = pts;
}
DEBUG_DEMUX("Send : pts %f dts %f", pts, dts);
DEBUG_DEMUX("position %f base_pts %llu current_pts %llu diff %f seconds length %d", position, base_pts, current_pts, (double)(current_pts - base_pts) / 90000, (int)es.len );
aamp->SendStreamCopy(type, es.ptr, es.len, pts, dts, duration);
if (gpGlobalConfig->logging.info)
{
sentESCount++;
if(0 == (sentESCount % 150 ))
{
AAMPLOG_WARN("Demuxer:: type %d sent %d packets", (int)type, sentESCount);
}
}
es.len = 0;
}
public:
/**
* @brief Demuxer Constructor
* @param[in] aamp pointer to PrivateInstanceAAMP object associated with demux
* @param[in] type Media type to be demuxed
*/
Demuxer(AampLogManager *logObj, class PrivateInstanceAAMP *aamp,MediaType type) : mLogObj(logObj), aamp(aamp), pes_state(0),
pes_header_ext_len(0), pes_header_ext_read(0), pes_header(),
es(), position(0), duration(0), base_pts{0}, current_pts{0},
current_dts{0}, type(type), trickmode(false), finalized_base_pts(false),
sentESCount(0), allowPtsRewind(false), first_pts{0}, update_first_pts(false), reached_steady_state(false)
{
init(0, 0, false, true);
}
/**
* @brief Copy Constructor
*/
Demuxer(const Demuxer&) = delete;
/**
* @brief Assignment operator overloading
*/
Demuxer& operator=(const Demuxer&) = delete;
/**
* @brief Demuxer Destructor
*/
~Demuxer()
{
aamp_Free(&es);
aamp_Free(&pes_header);
}
/**
* @brief Initialize demux
* @param[in] position start position
* @param[in] duration duration
* @param[in] trickmode true if trickmode
* @param[in] resetBasePTS true to reset base pts used for restamping
*/
void init(double position, double duration, bool trickmode, bool resetBasePTS)
{
this->position = position;
this->duration = duration;
this->trickmode = trickmode;
if (resetBasePTS)
{
base_pts = -1;
}
current_dts = 0;
current_pts = 0;
first_pts = 0;
update_first_pts = false;
finalized_base_pts = false;
memset(&pes_header, 0x00, sizeof(GrowableBuffer));
memset(&es, 0x00, sizeof(GrowableBuffer));
sentESCount = 0;
pes_state = PES_STATE_WAITING_FOR_HEADER;
DEBUG_DEMUX("init : position %f, duration %f resetBasePTS %d", position, duration, resetBasePTS);
}
/**
* @brief flush es buffer and reset demux state
*/
void flush()
{
if (es.len > 0)
{
INFO("demux : sending remaining bytes. es.len %d", (int)es.len);
send();
}
AAMPLOG_INFO("Demuxer::count %d in duration %f",sentESCount, duration);
reset();
}
/**
* @brief reset demux state
*/
void reset()
{
aamp_Free(&es);
aamp_Free(&pes_header);
memset(&pes_header, 0x00, sizeof(GrowableBuffer));
memset(&es, 0x00, sizeof(GrowableBuffer));
sentESCount = 0;
}
/**
* @brief Set base PTS used for re-stamping
* @param[in] basePTS new base PTS
* @param[in] final true if base PTS is finalized
*/
void setBasePTS(unsigned long long basePTS, bool isFinal)
{
if (!trickmode)
{
NOTICE("Type[%d], basePTS %llu final %d\n", (int)type, basePTS, (int)isFinal);
}
base_pts = basePTS;
finalized_base_pts = isFinal;
}
/**
* @brief Get base PTS used for re-stamping
* @retval base PTS used for re-stamping
*/
unsigned long long getBasePTS()
{
return base_pts.value;
}
/**
* @brief Process a TS packet
* @param[in] packetStart start of buffer containing packet
* @param[out] basePtsUpdated true if base PTS is updated
* @param[in] ptsError true if encountered PTS error.
*/
void processPacket(unsigned char * packetStart, bool &basePtsUpdated, bool &ptsError, bool &isPacketIgnored)
{
int adaptation_fieldlen = 0;
basePtsUpdated = false;
if (CONTAINS_PAYLOAD(packetStart))
{
if (ADAPTATION_FIELD_PRESENT(packetStart))
{
adaptation_fieldlen = packetStart[4];
}
int pesOffset = 4 + adaptation_fieldlen;
if (ADAPTATION_FIELD_PRESENT(packetStart))
{
pesOffset++;
}
/*Store the pts/dts*/
if (PAYLOAD_UNIT_START(packetStart))
{
if (es.len > 0)
{
send();
}
unsigned char* pesStart = packetStart + pesOffset;
if (IS_PES_PACKET_START(pesStart))
{
if (PES_OPTIONAL_HEADER_PRESENT(pesStart))
{
if ((pesStart[7] & 0x80) && ((pesStart[9] & 0x20) == 0x20))
{
const uint33_t timeStamp = Extract33BitTimestamp(&pesStart[9]);
auto prev_pts = exchange(current_pts, timeStamp);
if(prev_pts > current_pts && prev_pts - current_pts > uint33_t::half_max())
{//pts may come out of order so prev>current is not sufficient to detect the rollover
WARNING("PTS Rollover type:%d %llu -> %llu ", type, prev_pts.value, current_pts.value);
}
current_pts = timeStamp;
DEBUG("PTS updated %llu", current_pts.value);
if(!finalized_base_pts)
{
finalized_base_pts = true;
if(!trickmode)
{
if (-1 == base_pts)
{
base_pts = current_pts - MAX_FIRST_PTS_OFFSET;
WARNING("Type[%d] base_pts not initialized, updated to %llu", type, base_pts);
}
else
{
if(current_pts < base_pts)
{
auto orig_base_pts = base_pts;
if (current_pts > MAX_FIRST_PTS_OFFSET)
{
base_pts = current_pts - MAX_FIRST_PTS_OFFSET;
}
else
{
base_pts = current_pts;
}
WARNING("Type[%d] current_pts[%llu] < base_pts[%llu], base_pts[%llu]->[%llu]",
type, current_pts.value, base_pts.value, orig_base_pts.value, base_pts.value);
}
else /*current_pts >= base_pts*/
{
auto delta = current_pts - base_pts;
if (MAX_FIRST_PTS_OFFSET < delta)
{
auto orig_base_pts = base_pts;
base_pts = current_pts - MAX_FIRST_PTS_OFFSET;
NOTICE("Type[%d] delta[%lld] > MAX_FIRST_PTS_OFFSET, current_pts[%llu] base_pts[%llu]->[%llu]",
type, delta.value, current_pts.value, orig_base_pts.value, base_pts.value);
}
else
{
NOTICE("Type[%d] PTS in range.delta[%lld] <= MAX_FIRST_PTS_OFFSET base_pts[%llu]",
type, delta.value, base_pts.value);
}
}
}
}
if (-1 == base_pts)
{
base_pts = timeStamp;
WARNING("base_pts not available, updated to pts %llu", timeStamp);
}
else if (base_pts > timeStamp)
{
WARNING("base_pts update from %llu to %llu", base_pts, timeStamp);
base_pts = timeStamp;
}
basePtsUpdated = true;
}
}
else
{
WARNING("PTS NOT present pesStart[7] & 0x80 = 0x%x pesStart[9]&0xF0 = 0x%x",
pesStart[7] & 0x80, (pesStart[9] & 0x20));
}
if (((pesStart[7] & 0xC0) == 0xC0) && ((pesStart[14] & 0x1) == 0x01))
{
current_dts = Extract33BitTimestamp(&pesStart[14]);
}
else
{
DEBUG("DTS NOT present pesStart[7] & 0x80 = 0x%x pesStart[9]&0xF0 = 0x%x",
pesStart[7] & 0x80, (pesStart[9] & 0x20));
}
}
else
{
WARNING("Optional pes header NOT present pesStart[6] & 0xC0 = 0x%x", pesStart[6] & 0xC0);
}
}
else
{
WARNING("Packet start prefix check failed 0x%x 0x%x 0x%x adaptation_fieldlen %d", pesStart[0],
pesStart[1], pesStart[2], adaptation_fieldlen);
/* DELIA 47453 video stops playing when ad fragments are injected
* without expected discontinuity tag in the hls manifest files.
* This results in PTS error and video looping.
* In particular hls file, video payload alone is available and
* unexpectedly we received audio payload without proper PES data.
* But this audio TS packet got processed, and PES packet start code
* is not available in that packet.
* This is the first audio TS packet got in the middle of playback and
* current_pts is not updated, and the pts was deafult initalized value.
* So we returned the PTS error from this api, as current_pts is less than
* base_pts value.
* Now we have avoided the pts check if the current_pts is not updated for
* first audio, video or dsmcc packet due to TS packet doesnt have proper PES data.
*/
if( current_pts == 0 )
{
WARNING("Avoiding PTS check when new audio or video TS packet is received without proper PES data");
isPacketIgnored = true;
return;
}
}
DEBUG(" PES_PAYLOAD_LENGTH %d", PES_PAYLOAD_LENGTH(pesStart));
}
if ((first_pts == 0) && !update_first_pts)
{
first_pts = current_pts;
update_first_pts = true;
//Notify first video PTS to AAMP for VTT initialization
if (!trickmode && type == eMEDIATYPE_VIDEO)
{
aamp->NotifyFirstVideoPTS(first_pts.value);
//Notifying BasePTS value for media progress event
aamp->NotifyVideoBasePTS(getBasePTS());
}
}
/*PARSE PES*/
{
unsigned char * data = packetStart + pesOffset;
int size = PACKET_SIZE - pesOffset;
int bytes_to_read;
if (PAYLOAD_UNIT_START(packetStart))
{
pes_state = PES_STATE_GETTING_HEADER;
pes_header.len = 0;
DEBUG_DEMUX("Payload Unit Start");
}
while (size > 0)
{
switch (pes_state)
{
case PES_STATE_WAITING_FOR_HEADER:
WARNING("PES_STATE_WAITING_FOR_HEADER , discard data. type =%d size = %d", (int)type, size);
size = 0;
break;
case PES_STATE_GETTING_HEADER:
bytes_to_read = PES_MIN_DATA - pes_header.len;
if (size < bytes_to_read)
{
bytes_to_read = size;
}
DEBUG("PES_STATE_GETTING_HEADER. size = %d, bytes_to_read =%d", size, bytes_to_read);
aamp_AppendBytes(&pes_header, data, bytes_to_read);
data += bytes_to_read;
size -= bytes_to_read;
if (pes_header.len == PES_MIN_DATA)
{
if (!IS_PES_PACKET_START(pes_header.ptr))
{
WARNING("Packet start prefix check failed 0x%x 0x%x 0x%x", pes_header.ptr[0],
pes_header.ptr[1], pes_header.ptr[2]);
pes_state = PES_STATE_WAITING_FOR_HEADER;
break;
}
if (PES_OPTIONAL_HEADER_PRESENT(pes_header.ptr))
{
pes_state = PES_STATE_GETTING_HEADER_EXTENSION;
pes_header_ext_len = PES_OPTIONAL_HEADER_LENGTH(pes_header.ptr);
pes_header_ext_read = 0;
DEBUG(
"Optional header preset len = %d. Switching to PES_STATE_GETTING_HEADER_EXTENSION",
pes_header_ext_len);
}
else
{
WARNING(
"Optional header not preset pesStart[6] 0x%x bytes_to_read %d- switching to PES_STATE_WAITING_FOR_HEADER",
pes_header.ptr[6], bytes_to_read);
pes_state = PES_STATE_WAITING_FOR_HEADER;
}
}
break;
case PES_STATE_GETTING_HEADER_EXTENSION:
bytes_to_read = pes_header_ext_len - pes_header_ext_read;
if (bytes_to_read > size)
{
bytes_to_read = size;
}
data += bytes_to_read;
size -= bytes_to_read;
pes_header_ext_read += bytes_to_read;
if (pes_header_ext_read == pes_header_ext_len)
{
pes_state = PES_STATE_GETTING_ES;
DEBUG("Optional header read. switch to PES_STATE_GETTING_ES");
}
break;
case PES_STATE_GETTING_ES:
/*Handle padding?*/
TRACE1("PES_STATE_GETTING_ES bytes_to_read = %d", size);
aamp_AppendBytes(&es, data, size);
size = 0;
break;
default:
pes_state = PES_STATE_WAITING_FOR_HEADER;
ERROR("Invalid pes_state. type =%d size = %d", (int)type, size);
break;
}
}
}
}
else
{
INFO("No payload in packet packetStart[3] 0x%x", packetStart[3]);
}
ptsError = false;
}
};
#define rmf_osal_memcpy(d, s, n, dc, sc) memcpy(d, s, n)
static unsigned long crc32_table[256];
static int crc32_initialized = 0;
/**
* @brief Init CRC32 table
*/
static void init_crc32()
{
if (crc32_initialized) return;
unsigned int k, i, j;
for (i = 0; i < 256; i++)
{
k = 0;
for (j = (i << 24) | 0x800000; j != 0x80000000; j <<= 1)
{
k = (k << 1) ^ (((k ^ j) & 0x80000000) ? 0x04c11db7 : 0);
}
crc32_table[i] = k;
}
crc32_initialized = 1;
}
/**
* @brief Get 32 bit CRC value
* @param[in] data buffer containing data
* @param[in] size length of data
* @param[in] initial initial CRC
* @retval 32 bit CRC value
*/
static uint32_t get_crc32(unsigned char *data, int size, uint32_t initial = 0xffffffff)
{
int i;
uint32_t result = initial;
init_crc32();
for (i = 0; i < size; i++)
{
result = (result << 8) ^ crc32_table[(result >> 24) ^ data[i]];
}
return result;
}
/**
* @brief Dump TS packet
* @param[in] packet buffer containing packet
* @param[in] packetSize length of packet
*/
static void dumpPacket(unsigned char *packet, int packetSize)
{
if (DUMP_PACKET)
{
int i;
char buff[1024];
int col = 0;
int buffPos = 0;
buff[buffPos] = 0x00;
for (i = 0; i < packetSize; ++i)
{
buffPos += snprintf(&buff[buffPos], (sizeof(buff) - buffPos), "%02X\n", packet[i]);
++col;
if (col == 8)
{
strcat(buff, " ");
buffPos += 1;
}
if (col == 16)
{
buffPos += snprintf(&buff[buffPos], (sizeof(buff) - buffPos), "\n");
col = 0;
}
}
printf("%s\n", buff);
}
}
/**
* @brief dump TS packets
* @param[in] packets buffer containing packets
* @param[in] len length of packets
* @param[in] packetSize size of TS packet
*/
static void dumpPackets(unsigned char *packets, int len, int packetSize)
{
while (len)
{
dumpPacket(packets, packetSize);
len -= packetSize;
packets += packetSize;
}
}
/**
* @brief Get the format for a stream type
* @param[in] streamType stream type
* @return StreamOutputFormat format for input stream type
*/
static StreamOutputFormat getStreamFormatForCodecType(int streamType)
{
StreamOutputFormat format = FORMAT_UNKNOWN; // Maybe GStreamer will be able to detect the format
switch (streamType)
{
case eSTREAM_TYPE_MPEG2_VIDEO:
format = FORMAT_VIDEO_ES_MPEG2;
break;
case eSTREAM_TYPE_MPEG1_AUDIO:
case eSTREAM_TYPE_MPEG2_AUDIO:
case eSTREAM_TYPE_AAC_ADTS:
case eSTREAM_TYPE_AAC_LATM:
format = FORMAT_AUDIO_ES_AAC;
break;
case eSTREAM_TYPE_H264:
format = FORMAT_VIDEO_ES_H264;
break;
case eSTREAM_TYPE_HEVC_VIDEO:
format = FORMAT_VIDEO_ES_HEVC;
break;
case eSTREAM_TYPE_ATSC_AC3:
format = FORMAT_AUDIO_ES_AC3;
break;
case eSTREAM_TYPE_ATSC_AC3PLUS:
case eSTREAM_TYPE_ATSC_EAC3:
format = FORMAT_AUDIO_ES_EC3;
break;
case eSTREAM_TYPE_PES_PRIVATE:
//could be any ac4, ac3, subtitles etc.
break;
// not sure on the format, so keep as unknown
case eSTREAM_TYPE_DSM_CC:
case eSTREAM_TYPE_ATSC_VIDEO:
case eSTREAM_TYPE_HDMV_DTS:
case eSTREAM_TYPE_LPCM_AUDIO:
case eSTREAM_TYPE_DTSHD_AUDIO:
case eSTREAM_TYPE_DTS_AUDIO:
case eSTREAM_TYPE_AC3_AUDIO:
case eSTREAM_TYPE_SDDS_AUDIO1:
default:
break;
}
return format;
}
/**
* @brief TSProcessor Constructor
*/
TSProcessor::TSProcessor(AampLogManager *logObj, class PrivateInstanceAAMP *aamp,StreamOperation streamOperation, int track, TSProcessor* peerTSProcessor, TSProcessor* auxTSProcessor)
: m_needDiscontinuity(true),
m_PatPmtLen(0), m_PatPmt(0), m_PatPmtTrickLen(0), m_PatPmtTrick(0), m_PatPmtPcrLen(0), m_PatPmtPcr(0),
m_nullPFrame(0), m_nullPFrameLength(0), m_nullPFrameNextCount(0), m_nullPFrameOffset(0),
m_emulationPreventionCapacity(0), m_emulationPreventionOffset(0), m_emulationPrevention(0), aamp(aamp),
m_currStreamOffset(0), m_currPTS(-1), m_currTimeStamp(-1LL), m_currFrameNumber(-1),
m_currFrameLength(0), m_currFrameOffset(-1LL), m_trickExcludeAudio(true), m_patCounter(0),
m_pmtCounter(0), m_playMode(PlayMode_normal), m_playModeNext(PlayMode_normal), m_playRate(1.0f), m_absPlayRate(1.0f),
m_playRateNext(1.0f), m_apparentFrameRate(FIXED_FRAME_RATE), m_packetSize(PACKET_SIZE), m_ttsSize(0),
m_pcrPid(-1), m_videoPid(-1), m_haveBaseTime(false), m_haveEmittedIFrame(false), m_haveUpdatedFirstPTS(true),
m_pcrPerPTSCount(0), m_baseTime(0), m_segmentBaseTime(0), m_basePCR(-1LL), m_prevRateAdjustedPCR(-1LL),
m_currRateAdjustedPCR(0), m_currRateAdjustedPTS(-1LL), m_nullPFrameWidth(-1), m_nullPFrameHeight(-1),
m_frameWidth(FRAME_WIDTH_MAX), m_frameHeight(FRAME_HEIGHT_MAX), m_scanForFrameSize(false), m_scanRemainderSize(0),
m_scanRemainderLimit(SCAN_REMAINDER_SIZE_MPEG2), m_isH264(false), m_isMCChannel(false), m_isInterlaced(false), m_isInterlacedKnown(false),
m_throttle(true), m_haveThrottleBase(false), m_lastThrottleContentTime(-1LL), m_lastThrottleRealTime(-1LL),
m_baseThrottleContentTime(-1LL), m_baseThrottleRealTime(-1LL), m_throttlePTS{uint33_t::max_value()}, m_insertPCR(false),
m_scanSkipPacketsEnabled(false), m_currSPSId(0), m_picOrderCount(0), m_updatePicOrderCount(false),
m_havePAT(false), m_versionPAT(0), m_program(0), m_pmtPid(0), m_havePMT(false), m_versionPMT(-1), m_indexAudio(false),
m_haveAspect(false), m_haveFirstPTS(false), m_currentPTS(uint33_t::max_value()), m_pmtCollectorNextContinuity(0),
m_pmtCollectorSectionLength(0), m_pmtCollectorOffset(0), m_pmtCollector(NULL),
m_scrambledWarningIssued(false), m_checkContinuity(false), videoComponentCount(0), audioComponentCount(0),
m_actualStartPTS{uint33_t::max_value()}, m_throttleMaxDelayMs(DEFAULT_THROTTLE_MAX_DELAY_MS),
m_throttleMaxDiffSegments(DEFAULT_THROTTLE_MAX_DIFF_SEGMENTS_MS),
m_throttleDelayIgnoredMs(DEFAULT_THROTTLE_DELAY_IGNORED_MS), m_throttleDelayForDiscontinuityMs(DEFAULT_THROTTLE_DELAY_FOR_DISCONTINUITY_MS),
m_throttleCond(), m_basePTSCond(), m_mutex(), m_enabled(true), m_processing(false), m_framesProcessedInSegment(0),
m_lastPTSOfSegment(-1), m_streamOperation(streamOperation), m_vidDemuxer(NULL), m_audDemuxer(NULL), m_dsmccDemuxer(NULL),
m_demux(false), m_peerTSProcessor(peerTSProcessor), m_packetStartAfterFirstPTS(-1), m_queuedSegment(NULL),
m_queuedSegmentPos(0), m_queuedSegmentDuration(0), m_queuedSegmentLen(0), m_queuedSegmentDiscontinuous(false), m_startPosition(-1.0),
m_track(track), m_last_frame_time(0), m_demuxInitialized(false), m_basePTSFromPeer(-1), m_dsmccComponentFound(false), m_dsmccComponent()
, m_AudioTrackIndexToPlay(0)
, m_auxTSProcessor(auxTSProcessor)
, m_auxiliaryAudio(false)
, mLogObj(logObj)
,m_audioGroupId()
{
INFO("constructor - %p", this);
memset(m_SPS, 0, 32 * sizeof(H264SPS));
memset(m_PPS, 0, 256 * sizeof(H264PPS));
pthread_cond_init(&m_throttleCond, NULL);
pthread_cond_init(&m_basePTSCond, NULL);
pthread_mutex_init(&m_mutex, NULL);
m_versionPMT = 0;
if ((m_streamOperation == eStreamOp_DEMUX_ALL) || (m_streamOperation == eStreamOp_DEMUX_VIDEO) || (m_streamOperation == eStreamOp_DEMUX_VIDEO_AND_AUX))
{
m_vidDemuxer = new Demuxer(mLogObj, aamp, eMEDIATYPE_VIDEO);
//demux DSM CC stream only together with video stream
m_dsmccDemuxer = new Demuxer(mLogObj, aamp, eMEDIATYPE_DSM_CC);
m_demux = true;
}
if ((m_streamOperation == eStreamOp_DEMUX_ALL) || (m_streamOperation == eStreamOp_DEMUX_AUDIO))
{
m_audDemuxer = new Demuxer(mLogObj, aamp, eMEDIATYPE_AUDIO);
m_demux = true;
}
else if ((m_streamOperation == eStreamOp_DEMUX_AUX) || m_streamOperation == eStreamOp_DEMUX_VIDEO_AND_AUX)
{
m_auxiliaryAudio = true;
m_audDemuxer = new Demuxer(mLogObj, aamp, eMEDIATYPE_AUX_AUDIO);
// Map auxiliary specific streamOperation back to generic streamOperation used by TSProcessor
if (m_streamOperation == eStreamOp_DEMUX_AUX)
{
m_streamOperation = eStreamOp_DEMUX_AUDIO; // this is an audio only streamOperation
}
else
{
m_streamOperation = eStreamOp_DEMUX_ALL; // this is a muxed streamOperation
}
m_demux = true;
}
int compBufLen = MAX_PIDS*sizeof(RecordingComponent);
memset(videoComponents, 0, compBufLen);
memset(audioComponents, 0, compBufLen);
}
/**
* @brief TSProcessor Destructor
*/
TSProcessor::~TSProcessor()
{
INFO("destructor - %p", this);
if (m_PatPmt)
{
free(m_PatPmt);
m_PatPmt = 0;
}
if (m_PatPmtTrick)
{
free(m_PatPmtTrick);
m_PatPmtTrick = 0;
}
if (m_PatPmtPcr)
{
free(m_PatPmtPcr);
m_PatPmtPcr = 0;
}
if (m_nullPFrame)
{
free(m_nullPFrame);
m_nullPFrame = 0;
}
if (m_pmtCollector)
{
free(m_pmtCollector);
m_pmtCollector = 0;
}
if (m_emulationPrevention)
{
free(m_emulationPrevention);
m_emulationPrevention = 0;
}
for (int i = 0; i < audioComponentCount; ++i)
{
if (audioComponents[i].associatedLanguage)
{
free(audioComponents[i].associatedLanguage);
}
}
SAFE_DELETE(m_vidDemuxer);
SAFE_DELETE(m_audDemuxer);
SAFE_DELETE(m_dsmccDemuxer);
if (m_queuedSegment)
{
free(m_queuedSegment);
m_queuedSegment = NULL;
}
pthread_mutex_destroy(&m_mutex);
pthread_cond_destroy(&m_throttleCond);
pthread_cond_destroy(&m_basePTSCond);
}
#define BUFFER_POOL_SIZE (10)
#define PLAY_BUFFER_AUDIO_MAX_PACKETS (100)
#define PLAY_BUFFER_MAX_PACKETS (512)
#define PLAY_BUFFER_SIZE (PLAY_BUFFER_MAX_PACKETS*MAX_PACKET_SIZE)
#define POOL_BUFFER_ALIGNMENT (16)
#define PLAY_BUFFER_CTX_OFFSET (0)
#define PLAY_BUFFER_SIGNATURE (('P')|(('L')<<8)|(('A')<<16)|(('Y')<<24))
/**
* @brief Insert PAT and PMT sections
* @retval length of output buffer
*/
int TSProcessor::insertPatPmt(unsigned char *buffer, bool trick, int bufferSize)
{
int len;
if (trick && m_trickExcludeAudio)
{
len = m_PatPmtTrickLen;
rmf_osal_memcpy(buffer, m_PatPmtTrick, len, bufferSize, m_PatPmtTrickLen);
}
else if (trick && m_isMCChannel)
{
len = m_PatPmtPcrLen;
rmf_osal_memcpy(buffer, m_PatPmtPcr, len, bufferSize, m_PatPmtPcrLen);
}
else