summaryrefslogtreecommitdiff
blob: efea3a1d74f785b6768093dcc44cd6e62eac4838 (plain)
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
diff -a -U 2 -r a/config.c b/config.c
--- a/config.c
+++ b/config.c
@@ -469,4 +469,5 @@
   SplitEditedFiles = 0;
   DelTimeshiftRec = 0;
+  DumpNaluFill = 0;
   MinEventTimeout = 30;
   MinUserInactivity = 300;
@@ -697,4 +698,5 @@
   else if (!strcasecmp(Name, "SplitEditedFiles"))    SplitEditedFiles   = atoi(Value);
   else if (!strcasecmp(Name, "DelTimeshiftRec"))     DelTimeshiftRec    = atoi(Value);
+  else if (!strcasecmp(Name, "DumpNaluFill"))        DumpNaluFill       = atoi(Value);
   else if (!strcasecmp(Name, "MinEventTimeout"))     MinEventTimeout    = atoi(Value);
   else if (!strcasecmp(Name, "MinUserInactivity"))   MinUserInactivity  = atoi(Value);
@@ -829,4 +831,5 @@
   Store("SplitEditedFiles",   SplitEditedFiles);
   Store("DelTimeshiftRec",    DelTimeshiftRec);
+  Store("DumpNaluFill",       DumpNaluFill);
   Store("MinEventTimeout",    MinEventTimeout);
   Store("MinUserInactivity",  MinUserInactivity);
diff -a -U 2 -r a/config.h b/config.h
--- a/config.h
+++ b/config.h
@@ -341,4 +341,5 @@
   int SplitEditedFiles;
   int DelTimeshiftRec;
+  int DumpNaluFill;
   int MinEventTimeout, MinUserInactivity;
   time_t NextWakeupTime;
diff -a -U 2 -r a/menu.c b/menu.c
--- a/menu.c
+++ b/menu.c
@@ -4185,4 +4185,5 @@
   Add(new cMenuEditBoolItem(tr("Setup.Recording$Split edited files"),        &data.SplitEditedFiles));
   Add(new cMenuEditStraItem(tr("Setup.Recording$Delete timeshift recording"),&data.DelTimeshiftRec, 3, delTimeshiftRecTexts));
+  Add(new cMenuEditBoolItem(tr("Setup.Recording$Dump NALU Fill data"),       &data.DumpNaluFill));
 }
 
diff -a -U 2 -r a/recorder.c b/recorder.c
--- a/recorder.c
+++ b/recorder.c
@@ -195,4 +195,12 @@
      }
   frameDetector = new cFrameDetector(Pid, Type);
+  if (   Type == 0x1B // MPEG4 video
+      && (Setup.DumpNaluFill ? (strstr(FileName, "NALUKEEP") == NULL) : (strstr(FileName, "NALUDUMP") != NULL))) { // MPEG4
+     isyslog("Starting NALU fill dumper");
+     naluStreamProcessor = new cNaluStreamProcessor();
+     naluStreamProcessor->SetPid(Pid);
+     }
+  else
+     naluStreamProcessor = NULL;
   index = NULL;
   fileSize = 0;
@@ -217,4 +225,10 @@
 {
   Detach();
+  if (naluStreamProcessor) {
+     long long int TotalPackets = naluStreamProcessor->GetTotalPackets();
+     long long int DroppedPackets = naluStreamProcessor->GetDroppedPackets();
+     isyslog("NALU fill dumper: %lld of %lld packets dropped, %lli%%", DroppedPackets, TotalPackets, TotalPackets ? DroppedPackets*100/TotalPackets : 0);
+     delete naluStreamProcessor;
+     }
   delete index;
   delete fileName;
@@ -357,10 +371,32 @@
                        t.Set(MAXBROKENTIMEOUT);
                        }
-                    if (recordFile->Write(b, Count) < 0) {
-                       LOG_ERROR_STR(fileName->Name());
-                       break;
+		    if (naluStreamProcessor) {
+                       naluStreamProcessor->PutBuffer(b, Count);
+                       bool Fail = false;
+                       while (true) {
+                             int OutLength = 0;
+                             uchar *OutData = naluStreamProcessor->GetBuffer(OutLength);
+                             if (!OutData || OutLength <= 0)
+                                break;
+                             if (recordFile->Write(OutData, OutLength) < 0) {
+                                LOG_ERROR_STR(fileName->Name());
+                                Fail = true;
+                                break;
+                                }
+                             HandleErrors();
+                             fileSize += OutLength;
+                             }
+                       if (Fail)
+                          break;
+                       }
+                    else {
+                       if (recordFile->Write(b, Count) < 0) {
+                          LOG_ERROR_STR(fileName->Name());
+                          break;
+                          }
+                       HandleErrors();
+                       fileSize += Count;
                        }
-                    HandleErrors();
-                    fileSize += Count;
+
                     }
                  }
diff -a -U 2 -r a/recorder.h b/recorder.h
--- a/recorder.h
+++ b/recorder.h	C2022-01-08 17:51:00.397595525 +0100
@@ -27,4 +27,5 @@
   cFrameDetector *frameDetector;
   cPatPmtGenerator patPmtGenerator;
+  cNaluStreamProcessor *naluStreamProcessor;
   cFileName *fileName;
   cRecordingInfo *recordingInfo;
diff -a -U 2 -r a/remux.c b/remux.c
--- a/remux.c
+++ b/remux.c
@@ -357,4 +357,40 @@
 }
 
+void TsExtendAdaptionField(unsigned char *Packet, int ToLength)
+{
+    // Hint: ExtenAdaptionField(p, TsPayloadOffset(p) - 4) is a null operation
+
+    int Offset = TsPayloadOffset(Packet); // First byte after existing adaption field
+
+    if (ToLength <= 0)
+    {
+        // Remove adaption field
+        Packet[3] = Packet[3] & ~TS_ADAPT_FIELD_EXISTS;
+        return;
+    }
+
+    // Set adaption field present
+    Packet[3] = Packet[3] | TS_ADAPT_FIELD_EXISTS;
+
+    // Set new length of adaption field:
+    Packet[4] = ToLength <= TS_SIZE-4 ? ToLength-1 : TS_SIZE-4-1;
+
+    if (Packet[4] == TS_SIZE-4-1)
+    {
+        // No more payload, remove payload flag
+        Packet[3] = Packet[3] & ~TS_PAYLOAD_EXISTS;
+    }
+
+    int NewPayload = TsPayloadOffset(Packet); // First byte after new adaption field
+
+    // Fill new adaption field
+    if (Offset == 4 && Offset < NewPayload)
+        Offset++; // skip adaptation_field_length
+    if (Offset == 5 && Offset < NewPayload)
+        Packet[Offset++] = 0; // various flags set to 0
+    while (Offset < NewPayload)
+        Packet[Offset++] = 0xff; // stuffing byte
+}
+
 // --- cPatPmtGenerator ------------------------------------------------------
 
@@ -1765,2 +1801,343 @@
   return Processed;
 }
+
+// --- cNaluDumper ---------------------------------------------------------
+
+cNaluDumper::cNaluDumper()
+{
+    LastContinuityOutput = -1;
+    reset();
+}
+
+void cNaluDumper::reset()
+{
+    LastContinuityInput = -1;
+    ContinuityOffset = 0;
+    PesId = -1;
+    PesOffset = 0;
+    NaluFillState = NALU_NONE;
+    NaluOffset = 0;
+    History = 0xffffffff;
+    DropAllPayload = false;
+}
+
+void cNaluDumper::ProcessPayload(unsigned char *Payload, int size, bool PayloadStart, sPayloadInfo &Info)
+{
+    Info.DropPayloadStartBytes = 0;
+    Info.DropPayloadEndBytes = 0;
+    int LastKeepByte = -1;
+
+    if (PayloadStart)
+    {
+        History = 0xffffffff;
+        PesId = -1;
+        NaluFillState = NALU_NONE;
+    }
+
+    for (int i=0; i<size; i++) {
+        History = (History << 8) | Payload[i];
+
+        PesOffset++;
+        NaluOffset++;
+
+        bool DropByte = false;
+
+        if (History >= 0x00000180 && History <= 0x000001FF)
+        {
+            // Start of PES packet
+            PesId = History & 0xff;
+            PesOffset = 0;
+            NaluFillState = NALU_NONE;
+        }
+        else if (PesId >= 0xe0 && PesId <= 0xef // video stream
+                 && History >= 0x00000100 && History <= 0x0000017F) // NALU start code
+        {
+            int NaluId = History & 0xff;
+            NaluOffset = 0;
+            NaluFillState = ((NaluId & 0x1f) == 0x0c) ? NALU_FILL : NALU_NONE;
+        }
+
+        if (PesId >= 0xe0 && PesId <= 0xef // video stream
+            && PesOffset >= 1 && PesOffset <= 2)
+        {
+            Payload[i] = 0; // Zero out PES length field
+        }
+
+        if (NaluFillState == NALU_FILL && NaluOffset > 0) // Within NALU fill data
+        {
+            // We expect a series of 0xff bytes terminated by a single 0x80 byte.
+
+            if (Payload[i] == 0xFF)
+            {
+                DropByte = true;
+            }
+            else if (Payload[i] == 0x80)
+            {
+                NaluFillState = NALU_TERM; // Last byte of NALU fill, next byte sets NaluFillEnd=true
+                DropByte = true;
+            }
+            else // Invalid NALU fill
+            {
+                dsyslog("cNaluDumper: Unexpected NALU fill data: %02x", Payload[i]);
+                NaluFillState = NALU_END;
+                if (LastKeepByte == -1)
+                {
+                    // Nalu fill from beginning of packet until last byte
+                    // packet start needs to be dropped
+                    Info.DropPayloadStartBytes = i;
+                }
+            }
+        }
+        else if (NaluFillState == NALU_TERM) // Within NALU fill data
+        {
+            // We are after the terminating 0x80 byte
+            NaluFillState = NALU_END;
+            if (LastKeepByte == -1)
+            {
+                // Nalu fill from beginning of packet until last byte
+                // packet start needs to be dropped
+                Info.DropPayloadStartBytes = i;
+            }
+        }
+
+        if (!DropByte)
+            LastKeepByte = i; // Last useful byte
+    }
+
+    Info.DropAllPayloadBytes = (LastKeepByte == -1);
+    Info.DropPayloadEndBytes = size-1-LastKeepByte;
+}
+
+bool cNaluDumper::ProcessTSPacket(unsigned char *Packet)
+{
+    bool HasAdaption = TsHasAdaptationField(Packet);
+    bool HasPayload = TsHasPayload(Packet);
+
+    // Check continuity:
+    int ContinuityInput = TsContinuityCounter(Packet);
+    if (LastContinuityInput >= 0)
+    {
+        int NewContinuityInput = HasPayload ? (LastContinuityInput + 1) & TS_CONT_CNT_MASK : LastContinuityInput;
+        int Offset = (NewContinuityInput - ContinuityInput) & TS_CONT_CNT_MASK;
+        if (Offset > 0)
+            dsyslog("cNaluDumper: TS continuity offset %i", Offset);
+        if (Offset > ContinuityOffset)
+            ContinuityOffset = Offset; // max if packets get dropped, otherwise always the current one.
+    }
+    LastContinuityInput = ContinuityInput;
+
+    if (HasPayload) {
+        sPayloadInfo Info;
+        int Offset = TsPayloadOffset(Packet);
+        ProcessPayload(Packet + Offset, TS_SIZE - Offset, TsPayloadStart(Packet), Info);
+
+        if (DropAllPayload && !Info.DropAllPayloadBytes)
+        {
+            // Return from drop packet mode to normal mode
+            DropAllPayload = false;
+
+            // Does the packet start with some remaining NALU fill data?
+            if (Info.DropPayloadStartBytes > 0)
+            {
+                // Add these bytes as stuffing to the adaption field.
+
+                // Sample payload layout:
+                // FF FF FF FF FF 80 00 00 01 xx xx xx xx
+                //                   ^DropPayloadStartBytes
+
+                TsExtendAdaptionField(Packet, Offset - 4 + Info.DropPayloadStartBytes);
+            }
+        }
+
+        bool DropThisPayload = DropAllPayload;
+
+        if (!DropAllPayload && Info.DropPayloadEndBytes > 0) // Payload ends with 0xff NALU Fill
+        {
+            // Last packet of useful data
+            // Do early termination of NALU fill data
+            Packet[TS_SIZE-1] = 0x80;
+            DropAllPayload = true;
+            // Drop all packets AFTER this one
+
+            // Since we already wrote the 0x80, we have to make sure that
+            // as soon as we stop dropping packets, any beginning NALU fill of next
+            // packet gets dumped. (see DropPayloadStartBytes above)
+        }
+
+        if (DropThisPayload && HasAdaption)
+        {
+            // Drop payload data, but keep adaption field data
+            TsExtendAdaptionField(Packet, TS_SIZE-4);
+            DropThisPayload = false;
+        }
+
+        if (DropThisPayload)
+        {
+            return true; // Drop packet
+        }
+    }
+
+    // Fix Continuity Counter and reproduce incoming offsets:
+    int NewContinuityOutput = TsHasPayload(Packet) ? (LastContinuityOutput + 1) & TS_CONT_CNT_MASK : LastContinuityOutput;
+    NewContinuityOutput = (NewContinuityOutput + ContinuityOffset) & TS_CONT_CNT_MASK;
+    TsSetContinuityCounter(Packet, NewContinuityOutput);
+    LastContinuityOutput = NewContinuityOutput;
+    ContinuityOffset = 0;
+
+    return false; // Keep packet
+}
+
+// --- cNaluStreamProcessor ---------------------------------------------------------
+
+cNaluStreamProcessor::cNaluStreamProcessor()
+{
+    pPatPmtParser = NULL;
+    vpid = -1;
+    data = NULL;
+    length = 0;
+    tempLength = 0;
+    tempLengthAtEnd = false;
+    TotalPackets = 0;
+    DroppedPackets = 0;
+}
+
+void cNaluStreamProcessor::PutBuffer(uchar *Data, int Length)
+{
+    if (length > 0)
+        esyslog("cNaluStreamProcessor::PutBuffer: New data before old data was processed!");
+
+    data = Data;
+    length = Length;
+}
+
+uchar* cNaluStreamProcessor::GetBuffer(int &OutLength)
+{
+    if (length <= 0)
+    {
+        // Need more data - quick exit
+        OutLength = 0;
+        return NULL;
+    }
+    if (tempLength > 0) // Data in temp buffer?
+    {
+        if (tempLengthAtEnd) // Data is at end, copy to beginning
+        {
+            // Overlapping src and dst!
+            for (int i=0; i<tempLength; i++)
+                tempBuffer[i] = tempBuffer[TS_SIZE-tempLength+i];
+        }
+        // Normalize TempBuffer fill
+        if (tempLength < TS_SIZE && length > 0)
+        {
+            int Size = min(TS_SIZE-tempLength, length);
+            memcpy(tempBuffer+tempLength, data, Size);
+            data += Size;
+            length -= Size;
+            tempLength += Size;
+        }
+        if (tempLength < TS_SIZE)
+        {
+            // All incoming data buffered, but need more data
+            tempLengthAtEnd = false;
+            OutLength = 0;
+            return NULL;
+        }
+        // Now: TempLength==TS_SIZE
+        if (tempBuffer[0] != TS_SYNC_BYTE)
+        {
+            // Need to sync on TS within temp buffer
+            int Skipped = 1;
+            while (Skipped < TS_SIZE && (tempBuffer[Skipped] != TS_SYNC_BYTE || (Skipped < length && data[Skipped] != TS_SYNC_BYTE)))
+                Skipped++;
+            esyslog("ERROR: skipped %d bytes to sync on start of TS packet", Skipped);
+            // Pass through skipped bytes
+            tempLengthAtEnd = true;
+            tempLength = TS_SIZE - Skipped; // may be 0, thats ok
+            OutLength = Skipped;
+            return tempBuffer;
+        }
+        // Now: TempBuffer is a TS packet
+        int Pid = TsPid(tempBuffer);
+        if (pPatPmtParser)
+        {
+            if (Pid == 0)
+                pPatPmtParser->ParsePat(tempBuffer, TS_SIZE);
+            else if (pPatPmtParser->IsPmtPid(Pid))
+                pPatPmtParser->ParsePmt(tempBuffer, TS_SIZE);
+        }
+
+        TotalPackets++;
+        bool Drop = false;
+        if (Pid == vpid || (pPatPmtParser && Pid == pPatPmtParser->Vpid() && pPatPmtParser->Vtype() == 0x1B))
+            Drop = NaluDumper.ProcessTSPacket(tempBuffer);
+        if (!Drop)
+        {
+            // Keep this packet, then continue with new data
+            tempLength = 0;
+            OutLength = TS_SIZE;
+            return tempBuffer;
+        }
+        // Drop TempBuffer
+        DroppedPackets++;
+        tempLength = 0;
+    }
+    // Now: TempLength==0, just process data/length
+
+    // Pointer to processed data / length:
+    uchar *Out = data;
+    uchar *OutEnd = Out;
+
+    while (length >= TS_SIZE)
+    {
+        if (data[0] != TS_SYNC_BYTE) {
+            int Skipped = 1;
+            while (Skipped < length && (data[Skipped] != TS_SYNC_BYTE || (length - Skipped > TS_SIZE && data[Skipped + TS_SIZE] != TS_SYNC_BYTE)))
+                Skipped++;
+            esyslog("ERROR: skipped %d bytes to sync on start of TS packet", Skipped);
+
+            // Pass through skipped bytes
+            if (OutEnd != data)
+                memcpy(OutEnd, data, Skipped);
+            OutEnd += Skipped;
+            continue;
+        }
+        // Now: Data starts with complete TS packet
+
+        int Pid = TsPid(data);
+        if (pPatPmtParser)
+        {
+            if (Pid == 0)
+                pPatPmtParser->ParsePat(data, TS_SIZE);
+            else if (pPatPmtParser->IsPmtPid(Pid))
+                pPatPmtParser->ParsePmt(data, TS_SIZE);
+        }
+
+        TotalPackets++;
+        bool Drop = false;
+        if (Pid == vpid || (pPatPmtParser && Pid == pPatPmtParser->Vpid() && pPatPmtParser->Vtype() == 0x1B))
+            Drop = NaluDumper.ProcessTSPacket(data);
+        if (!Drop)
+        {
+            if (OutEnd != data)
+                memcpy(OutEnd, data, TS_SIZE);
+            OutEnd += TS_SIZE;
+        }
+        else
+        {
+            DroppedPackets++;
+        }
+        data += TS_SIZE;
+        length -= TS_SIZE;
+    }
+    // Now: Less than a packet remains.
+    if (length > 0)
+    {
+        // copy remains into temp buffer
+        memcpy(tempBuffer, data, length);
+        tempLength = length;
+        tempLengthAtEnd = false;
+        length = 0;
+    }
+    OutLength = (OutEnd - Out);
+    return OutLength > 0 ? Out : NULL;
+}
diff -a -U 2 -r a/remux.h b/remux.h
--- a/remux.h
+++ b/remux.h
@@ -65,4 +65,9 @@
 }
 
+inline bool TsSetPayload(const uchar *p)
+{
+  return p[3] & TS_PAYLOAD_EXISTS;
+}
+
 inline bool TsHasAdaptationField(const uchar *p)
 {
@@ -156,4 +161,5 @@
 void TsSetPts(uchar *p, int l, int64_t Pts);
 void TsSetDts(uchar *p, int l, int64_t Dts);
+void TsExtendAdaptionField(unsigned char *Packet, int ToLength);
 
 // Some PES handling tools:
@@ -550,3 +556,77 @@
   };
 
+
+#define PATCH_NALUDUMP 100
+
+class cNaluDumper {
+    unsigned int History;
+
+    int LastContinuityInput;
+    int LastContinuityOutput;
+    int ContinuityOffset;
+
+    bool DropAllPayload;
+
+    int PesId;
+    int PesOffset;
+
+    int NaluOffset;
+
+    enum eNaluFillState {
+        NALU_NONE=0,    // currently not NALU fill stream
+        NALU_FILL,      // Within NALU fill stream, 0xff bytes and NALU start code in byte 0
+        NALU_TERM,      // Within NALU fill stream, read 0x80 terminating byte
+        NALU_END        // Beyond end of NALU fill stream, expecting 0x00 0x00 0x01 now
+        };
+
+    eNaluFillState NaluFillState;
+
+    struct sPayloadInfo {
+        int DropPayloadStartBytes;
+        int DropPayloadEndBytes;
+        bool DropAllPayloadBytes;
+    };
+
+public:
+    cNaluDumper();
+
+    void reset();
+
+    // Single packet interface:
+    bool ProcessTSPacket(unsigned char *Packet);
+
+private:
+    void ProcessPayload(unsigned char *Payload, int size, bool PayloadStart, sPayloadInfo &Info);
+};
+
+class cNaluStreamProcessor {
+    //Buffer stream interface:
+    int vpid;
+    uchar *data;
+    int length;
+    uchar tempBuffer[TS_SIZE];
+    int tempLength;
+    bool tempLengthAtEnd;
+    cPatPmtParser *pPatPmtParser;
+    cNaluDumper NaluDumper;
+
+    long long int TotalPackets;
+    long long int DroppedPackets;
+public:
+    cNaluStreamProcessor();
+
+    void SetPid(int VPid) { vpid = VPid; }
+    void SetPatPmtParser(cPatPmtParser *_pPatPmtParser) { pPatPmtParser = _pPatPmtParser; }
+    // Set either a PID or set a pointer to an PatPmtParser that will detect _one_ PID
+
+    void PutBuffer(uchar *Data, int Length);
+    // Add new data to be processed. Data must be valid until Get() returns NULL.
+    uchar* GetBuffer(int &OutLength);
+    // Returns filtered data, or NULL/0 to indicate that all data from Put() was processed
+    // or buffered.
+
+    long long int GetTotalPackets() { return TotalPackets; }
+    long long int GetDroppedPackets() { return DroppedPackets; }
+};
+
 #endif // __REMUX_H