MythTV master
pespacket.cpp
Go to the documentation of this file.
1// -*- Mode: c++ -*-
2// Copyright (c) 2003-2004, Daniel Thor Kristjansson
4#ifndef __cpp_size_t_suffix
6#endif
7#include "pespacket.h"
8#include "mpegtables.h"
9
10extern "C" {
11#include "libmythbase/mythconfig.h"
12#include "libavcodec/avcodec.h"
13#include "libavformat/avformat.h"
14#include "libavutil/crc.h"
15#include "libavutil/bswap.h"
16}
17
18#include <vector>
19#include <map>
20
21// return true if complete or broken
22bool PESPacket::AddTSPacket(const TSPacket* packet, int cardid, bool &broken)
23{
24 broken = true;
25 if (!tsheader()->PayloadStart())
26 {
27 LOG(VB_RECORD, LOG_ERR,
28 "Error: We started a PES packet, without a payloadStart!");
29 return true;
30 }
31 if (!IsClone())
32 {
33 LOG(VB_RECORD, LOG_ERR,
34 "Error: Must clone initially to use addPackets()");
35 return false;
36 }
37
38 const int cc = packet->ContinuityCounter();
39 const int ccExp = (m_ccLast + 1) & 0xf;
40 uint payloadSize = TSPacket::kPayloadSize;
41 uint payloadStart = TSPacket::kHeaderSize;
42
43 // If the next TS has an offset, we need to strip it out.
44 // The offset will be used when a new PESPacket is created.
45 if (packet->PayloadStart())
46 {
47 payloadSize--;
48 payloadStart++;
49 }
50 else
51 {
52 // Skip past the adaptation field if present
53 if (packet->HasAdaptationField())
54 {
55 uint delta = packet->AdaptationFieldSize() + 1;
56
57 // Adaptation field size is max 182 (control is '11') or 183 (control is '10').
58 // Do not skip beyond end of packet when the adaptation field size is wrong.
59 if (delta > TSPacket::kPayloadSize)
60 {
62 LOG(VB_GENERAL, LOG_ERR, QString("PESPacket[%1] Invalid adaptation field size:%2 control:%3")
63 .arg(cardid).arg(packet->AdaptationFieldSize()).arg(packet->AdaptationFieldControl()));
64 }
65 payloadSize -= delta;
66 payloadStart += delta;
67 }
68 }
69
70 if (ccExp == cc)
71 {
72 if (m_pesDataSize + payloadSize >= m_allocSize)
73 {
74 uint sz = (((m_allocSize * 2) + 4095) / 4096) * 4096;
75 unsigned char *nbuf = pes_alloc(sz);
76 memcpy(nbuf, m_fullBuffer, m_pesDataSize);
78 m_fullBuffer = nbuf;
80 m_allocSize = sz;
81 }
82
84 packet->data() + payloadStart,
85 payloadSize);
86
87 m_ccLast = cc;
88 m_pesDataSize += payloadSize;
89 }
90 else if (int(m_ccLast) == cc)
91 {
92 // Do nothing with repeats
93 if (VERBOSE_LEVEL_CHECK(VB_RECORD, LOG_DEBUG))
94 {
95 LOG(VB_RECORD, LOG_ERR,
96 QString("AddTSPacket[%1]: Repeat packet!! ").arg(cardid) +
97 QString("PID: 0x%1, continuity counter: %2 ").arg(packet->PID(),0,16).arg(cc) +
98 QString("(expected %1)").arg(ccExp));
99 }
100 }
101 else
102 {
103 // Even if the packet is out of sync it is still the last packet received
104 m_ccLast = cc;
105
106 LOG(VB_RECORD, LOG_ERR,
107 QString("AddTSPacket[%1]: Out of sync!!! Need to wait for next payloadStart ").arg(cardid) +
108 QString("PID: 0x%1, continuity counter: %2 ").arg(packet->PID(),0,16).arg(cc) +
109 QString("(expected %1)").arg(ccExp));
110 return true;
111 }
112
113 // packet is correct or incomplete
114 broken = false;
115 // check if it's safe to call Length
116 if ((m_psiOffset + 1 + 3) <= m_pesDataSize)
117 {
118 // +3 = first 3 bytes of pespacket header, not included in Length()
119 uint tlen = Length() + (m_pesData - m_fullBuffer) +3;
120
121 if (m_pesDataSize >= tlen)
122 {
123 m_badPacket = !VerifyCRC(cardid, packet->PID());
124 return true;
125 }
126 }
127
128 return false;
129}
130
134void PESPacket::GetAsTSPackets(std::vector<TSPacket> &output, uint cc) const
135{
136 uint last_byte_of_pesdata = Length() + 4 - 1;
137 uint size = last_byte_of_pesdata + m_pesData - m_fullBuffer;
138
139 if (m_pesData == m_fullBuffer)
140 {
141 LOG(VB_GENERAL, LOG_ERR, "WriteAsTSPackets m_pesData == m_fullBuffer");
142 output.resize(0);
143 return;
144 }
145
146 output.resize(1);
148 output[0].data()[3] = (output[0].data()[3] & 0xf0) | cc;
149 if (size <= TSPacket::kSize)
150 return;
151
152 TSHeader header;
153 header.data()[1] = 0x00;
154 header.data()[2] = 0x00;
155 header.data()[3] = 0x10; // adaptation field control == payload only
156 header.SetPID(tsheader()->PID());
157
158 const unsigned char *data = m_fullBuffer + TSPacket::kSize;
159 size -= TSPacket::kSize;
160 while (size > 0)
161 {
162 cc = (cc + 1) & 0xF;
163 header.SetContinuityCounter(cc);
164 output.resize(output.size()+1);
165 output[output.size()-1].InitHeader(header.data());
166 uint write_size = std::min(size, TSPacket::kPayloadSize);
167 output[output.size()-1].InitPayload(data, write_size);
168 data += write_size;
169 size -= write_size;
170 }
171}
172
174{
175 if (Length() < 1)
176 return kTheMagicNoCRCCRC;
177 return av_bswap32(av_crc(av_crc_get_table(AV_CRC_32_IEEE), UINT32_MAX,
178 m_pesData, Length() - 1));
179}
180
181bool PESPacket::VerifyCRC(void) const
182{
183 bool ret = !HasCRC() || (CalcCRC() == CRC());
184 if (!ret)
185 {
186 LOG(VB_SIPARSER, LOG_INFO,
187 QString("PESPacket: Failed CRC check 0x%1 != 0x%2 "
188 "for StreamID = 0x%3")
189 .arg(CRC(),8,16,QLatin1Char('0')).arg(CalcCRC(),8,16,QLatin1Char('0')).arg(StreamID(),0,16));
190 }
191 return ret;
192}
193
194bool PESPacket::VerifyCRC(int cardid, int pid) const
195{
196 bool ret = !HasCRC() || (CalcCRC() == CRC());
197 if (!ret)
198 {
199 LOG(VB_RECORD, LOG_INFO,
200 QString("PESPacket[%1] pid(0x%2): ").arg(cardid).arg(pid,0,16) +
201 QString("Failed CRC check 0x%1 != 0x%2 for ID = 0x%3")
202 .arg(CRC(),8,16,QLatin1Char('0')).arg(CalcCRC(),8,16,QLatin1Char('0')).arg(StreamID(),0,16));
203 }
204 return ret;
205}
206
207// These are pixel aspect ratios
209{
210 0.0000F, 1.0000F, 0.6735F, 0.7031F,
211 0.7615F, 0.8055F, 0.8437F, 0.8935F,
212 0.9157F, 0.9815F, 1.0255F, 1.0695F,
213 1.0950F, 1.1575F, 1.2015F, 0.0000F,
214};
215
219{
220 0.0000F, 1.0000F, -3.0F/4.0F, -9.0F/16.0F,
221 -1.0F/2.21F, 0.0000F, 0.0000F, 0.0000F,
222 0.0000F, 0.0000F, 0.0000F, 0.0000F,
223 0.0000F, 0.0000F, 0.0000F, 0.0000F,
224};
225
227{
228 0.0F, 24000/1001.0F, 24.0F, 25.0F,
229 30000/1001.0F, 30.0F, 50.0F, 60000/1001.0F,
230 60.0F, 1.0F, 1.0F, 1.0F,
231 1.0F, 1.0F, 1.0F, 1.0F,
232};
233
235float SequenceHeader::aspect(bool mpeg1) const
236{
237 if (!height())
238 return 1.0F; // avoid segfaults on broken seq data
239
240 uint index = aspectNum();
241 float aspect = mpeg1 ? kMpeg1Aspect[index] : kMpeg2Aspect[index];
242
243 float retval = 0.0F;
244 retval = (aspect > 0.0F) ? width() / (aspect * height()) : retval;
245 retval = (aspect < 0.0F) ? -1.0F / aspect : retval;
246 retval = (retval <= 0.0F) ? width() * 1.0F / height() : retval;
247 return retval;
248}
249
250
251
253// Memory allocator to avoid malloc global lock and waste less memory. //
255
256#if !CONFIG_VALGRIND
257static constexpr size_t BLOCKS188 { 512 };
258#ifdef __cpp_size_t_suffix
259using block188 = std::array<uint8_t, 188UZ>;
260#else
261using block188 = std::array<uint8_t, 188_UZ>;
262#endif
264 public:
265 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init,modernize-use-equals-default)
266 groupof188s() {}; // // constructor doesn't initialize anything
267
268 std::array<block188, BLOCKS188> blocks;
269};
270
271static constexpr size_t BLOCKS4096 { 128 };
272#ifdef __cpp_size_t_suffix
273using block4096 = std::array<uint8_t, 4096UZ>;
274#else
275using block4096 = std::array<uint8_t, 4096_UZ>;
276#endif
278 public:
279 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init,modernize-use-equals-default)
280 groupof4096s() {}; // constructor doesn't initialize anything
281
282 std::array<block4096, BLOCKS4096> blocks;
283};
284
285
286static std::vector<groupof188s*> mem188;
287static std::vector<unsigned char*> free188;
288static std::map<unsigned char*, bool> alloc188;
289
290static std::vector<groupof4096s*> mem4096;
291static std::vector<unsigned char*> free4096;
292static std::map<unsigned char*, bool> alloc4096;
293
294
295static unsigned char* get_188_block()
296{
297 if (free188.empty())
298 {
299 mem188.push_back(new groupof188s);
300 free188.reserve(BLOCKS188);
301 for (block188 &b : mem188.back()->blocks)
302 free188.push_back(b.data());
303 }
304
305 unsigned char *ptr = free188.back();
306 free188.pop_back();
307 alloc188[ptr] = true;
308 return ptr;
309}
310
311static bool is_188_block(unsigned char* ptr)
312{
313 return alloc188.contains(ptr);
314}
315
316static void return_188_block(unsigned char* ptr)
317{
318 alloc188.erase(ptr);
319 free188.push_back(ptr);
320 // free the allocator only if more than 1 block was used
321 if (alloc188.empty() && mem188.size() > 1)
322 {
323 for (auto *b : mem188)
324 delete b;
325 mem188.clear();
326 free188.clear();
327#if 0
328 LOG(VB_GENERAL, LOG_DEBUG, "freeing all 188 blocks");
329#endif
330 }
331}
332
333static unsigned char* get_4096_block()
334{
335 if (free4096.empty())
336 {
337 mem4096.push_back(new groupof4096s);
338 free4096.reserve(BLOCKS4096);
339 for (block4096 &b : mem4096.back()->blocks)
340 free4096.push_back(b.data());
341 }
342
343 unsigned char *ptr = free4096.back();
344 free4096.pop_back();
345 alloc4096[ptr] = true;
346 return ptr;
347}
348
349static bool is_4096_block(unsigned char* ptr)
350{
351 return alloc4096.contains(ptr);
352}
353
354static void return_4096_block(unsigned char* ptr)
355{
356 alloc4096.erase(ptr);
357 free4096.push_back(ptr);
358
359#if 0 // enable this to debug memory leaks
360 LOG(VB_GENERAL, LOG_DEBUG, QString("%1 4096 blocks remain")
361 .arg(alloc4096.size()));
362 map<unsigned char*, bool>::iterator it;
363 for (it = alloc4096.begin(); it != alloc4096.end(); ++it)
364 {
365 TSPacket *ts = (TSPacket*) it->first;
366 LGO(VB_GENERAL, LOG_DEBUG, QString("PES Packet: pid(0x%1)")
367 .arg(ts->PID(),0,16));
368 if (ts->PID() == 0x1ffb)
369 {
370 LOG(VB_GENERAL, LOG_DEBUG, QString(" tid(0x%1) ext(0x%2)")
371 .arg(PSIPTable(*ts).TableID(),0,16)
372 .arg(PSIPTable(*ts).TableIDExtension(),0,16));
373 }
374 }
375#endif
376
377 // free the allocator only if more than 1 block was used
378 if (alloc4096.empty() && mem4096.size() > 1)
379 {
380 for (auto *b : mem4096)
381 delete b;
382 mem4096.clear();
383 free4096.clear();
384#if 0
385 LOG(VB_GENERAL, LOG_DEBUG, "freeing all 4096 blocks");
386#endif
387 }
388}
389#endif
390
391static QMutex pes_alloc_mutex;
392
393unsigned char *pes_alloc(uint size)
394{
395 QMutexLocker locker(&pes_alloc_mutex);
396#if !CONFIG_VALGRIND
397 if (size <= 188)
398 return get_188_block();
399 if (size <= 4096)
400 return get_4096_block();
401#endif // CONFIG_VALGRIND
402 // NOLINTNEXTLINE(cppcoreguidelines-no-malloc)
403 return (unsigned char*) malloc(size);
404}
405
406void pes_free(unsigned char *ptr)
407{
408 QMutexLocker locker(&pes_alloc_mutex);
409#if !CONFIG_VALGRIND
410 if (is_188_block(ptr))
411 return_188_block(ptr);
412 else if (is_4096_block(ptr))
414 else
415#endif // CONFIG_VALGRIND
416 // NOLINTNEXTLINE(cppcoreguidelines-no-malloc)
417 free(ptr);
418}
bool VerifyCRC(void) const
Definition: pespacket.cpp:181
bool AddTSPacket(const TSPacket *tspacket, int cardid, bool &broken)
Definition: pespacket.cpp:22
const unsigned char * data() const
Definition: pespacket.h:167
static const uint kTheMagicNoCRCCRC
Definition: pespacket.h:230
unsigned char * m_pesData
Pointer to PES data in full buffer.
Definition: pespacket.h:219
uint CalcCRC(void) const
Definition: pespacket.cpp:173
uint m_psiOffset
AFCOffset + StartOfFieldPointer.
Definition: pespacket.h:222
uint m_pesDataSize
Number of data bytes (TS header + PES data)
Definition: pespacket.h:224
void GetAsTSPackets(std::vector< TSPacket > &output, uint cc) const
Returns payload only PESPacket as series of TSPackets.
Definition: pespacket.cpp:134
const TSHeader * tsheader() const
Definition: pespacket.h:90
uint m_allocSize
Total number of bytes we allocated.
Definition: pespacket.h:225
bool m_badPacket
true if a CRC is not good yet
Definition: pespacket.h:226
virtual bool HasCRC() const
1 bit Cyclic Redundancy Check present
Definition: pespacket.h:130
uint StreamID() const
Definition: pespacket.h:98
unsigned char * m_fullBuffer
Pointer to allocated data.
Definition: pespacket.h:220
uint m_ccLast
Continuity counter of last inserted TS Packet.
Definition: pespacket.h:223
bool IsClone() const
Definition: pespacket.h:83
uint CRC(void) const
Definition: pespacket.h:189
uint Length() const
Definition: pespacket.h:99
A PSIP table is a variant of a PES packet containing an MPEG, ATSC or DVB table.
Definition: mpegtables.h:410
uint TableID(void) const
Definition: mpegtables.h:496
uint TableIDExtension(void) const
Definition: mpegtables.h:515
uint width(void) const
Definition: pespacket.h:239
static const AspectArray kMpeg2Aspect
The negative values are screen aspect ratios, while the positive ones are pixel aspect ratios.
Definition: pespacket.h:252
static const AspectArray kMpeg1Aspect
Definition: pespacket.h:251
float aspect(bool mpeg1) const
Returns the screen aspect ratio.
Definition: pespacket.cpp:235
uint height(void) const
Definition: pespacket.h:240
uint aspectNum(void) const
Definition: pespacket.h:241
static const AspectArray kMpeg2Fps
Definition: pespacket.h:253
Used to access header of a TSPacket.
Definition: tspacket.h:47
bool HasAdaptationField(void) const
Definition: tspacket.h:113
unsigned int ContinuityCounter(void) const
Definition: tspacket.h:109
unsigned int PID(void) const
Definition: tspacket.h:93
static constexpr unsigned int kHeaderSize
Definition: tspacket.h:177
bool PayloadStart(void) const
Definition: tspacket.h:89
unsigned int AdaptationFieldControl(void) const
Definition: tspacket.h:103
void SetContinuityCounter(unsigned int cc)
Definition: tspacket.h:170
void SetPID(unsigned int pid)
Definition: tspacket.h:160
const unsigned char * data(void) const
Definition: tspacket.h:174
size_t AdaptationFieldSize(void) const
Definition: tspacket.h:114
Used to access the data of a Transport Stream packet.
Definition: tspacket.h:208
static constexpr unsigned int kPayloadSize
Definition: tspacket.h:262
static constexpr unsigned int kSize
Definition: tspacket.h:261
std::array< block188, BLOCKS188 > blocks
Definition: pespacket.cpp:268
std::array< block4096, BLOCKS4096 > blocks
Definition: pespacket.cpp:282
unsigned int uint
Definition: compat.h:60
static bool VERBOSE_LEVEL_CHECK(uint64_t mask, LogLevel_t level)
Definition: mythlogging.h:29
#define LOG(_MASK_, _LEVEL_, _QSTRING_)
Definition: mythlogging.h:39
std::array< uint8_t, 4096_UZ > block4096
Definition: pespacket.cpp:275
static bool is_188_block(unsigned char *ptr)
Definition: pespacket.cpp:311
void pes_free(unsigned char *ptr)
Definition: pespacket.cpp:406
static std::vector< unsigned char * > free188
Definition: pespacket.cpp:287
static std::vector< groupof4096s * > mem4096
Definition: pespacket.cpp:290
static unsigned char * get_188_block()
Definition: pespacket.cpp:295
static void return_4096_block(unsigned char *ptr)
Definition: pespacket.cpp:354
static bool is_4096_block(unsigned char *ptr)
Definition: pespacket.cpp:349
static std::vector< groupof188s * > mem188
Definition: pespacket.cpp:286
static constexpr size_t BLOCKS188
Definition: pespacket.cpp:257
static std::map< unsigned char *, bool > alloc188
Definition: pespacket.cpp:288
static std::map< unsigned char *, bool > alloc4096
Definition: pespacket.cpp:292
static std::vector< unsigned char * > free4096
Definition: pespacket.cpp:291
static constexpr size_t BLOCKS4096
Definition: pespacket.cpp:271
static unsigned char * get_4096_block()
Definition: pespacket.cpp:333
unsigned char * pes_alloc(uint size)
Definition: pespacket.cpp:393
static QMutex pes_alloc_mutex
Definition: pespacket.cpp:391
std::array< uint8_t, 188_UZ > block188
Definition: pespacket.cpp:261
static void return_188_block(unsigned char *ptr)
Definition: pespacket.cpp:316
std::array< float, 16 > AspectArray
Definition: pespacket.h:13
#define output