summaryrefslogtreecommitdiff
path: root/cutter.c
blob: ed924a7106cb8321b6ff8f6c3620fadfd491ff6d (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
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
/*
 * cutter.c: The video cutting facilities
 *
 * See the main source file 'vdr.c' for copyright information and
 * how to reach the author.
 *
 * $Id: cutter.c 4.4 2017/12/14 14:09:46 kls Exp $
 */

#include "cutter.h"
#include "menu.h"
#include "recording.h"
#include "remux.h"
#include "videodir.h"

// --- cPacketBuffer ---------------------------------------------------------

class cPacketBuffer {
private:
  uchar *data;
  int size;
  int length;
public:
  cPacketBuffer(void);
  ~cPacketBuffer();
  void Append(uchar *Data, int Length);
       ///< Appends Length bytes of Data to this packet buffer.
  void Flush(uchar *Data, int &Length, int MaxLength);
       ///< Flushes the content of this packet buffer into the given Data, starting
       ///< at position Length, and clears the buffer afterwards. Length will be
       ///< incremented accordingly. If Length plus the total length of the stored
       ///< packets would exceed MaxLength, nothing is copied.
  };

cPacketBuffer::cPacketBuffer(void)
{
  data = NULL;
  size = length = 0;
}

cPacketBuffer::~cPacketBuffer()
{
  free(data);
}

void cPacketBuffer::Append(uchar *Data, int Length)
{
  if (length + Length >= size) {
     int NewSize = (length + Length) * 3 / 2;
     if (uchar *p = (uchar *)realloc(data, NewSize)) {
        data = p;
        size = NewSize;
        }
     else
        return; // out of memory
     }
  memcpy(data + length, Data, Length);
  length += Length;
}

void cPacketBuffer::Flush(uchar *Data, int &Length, int MaxLength)
{
  if (Data && length > 0 && Length + length <= MaxLength) {
     memcpy(Data + Length, data, length);
     Length += length;
     }
  length = 0;
}

// --- cPacketStorage --------------------------------------------------------

class cPacketStorage {
private:
  cPacketBuffer *buffers[MAXPID];
public:
  cPacketStorage(void);
  ~cPacketStorage();
  void Append(int Pid, uchar *Data, int Length);
  void Flush(int Pid, uchar *Data, int &Length, int MaxLength);
  };

cPacketStorage::cPacketStorage(void)
{
  for (int i = 0; i < MAXPID; i++)
      buffers[i] = NULL;
}

cPacketStorage::~cPacketStorage()
{
  for (int i = 0; i < MAXPID; i++)
      delete buffers[i];
}

void cPacketStorage::Append(int Pid, uchar *Data, int Length)
{
  if (!buffers[Pid])
     buffers[Pid] = new cPacketBuffer;
  buffers[Pid]->Append(Data, Length);
}

void cPacketStorage::Flush(int Pid, uchar *Data, int &Length, int MaxLength)
{
  if (buffers[Pid])
     buffers[Pid]->Flush(Data, Length, MaxLength);
}

// --- cMpeg2Fixer -----------------------------------------------------------

class cMpeg2Fixer : private cTsPayload {
private:
  bool FindHeader(uint32_t Code, const char *Header);
public:
  cMpeg2Fixer(uchar *Data, int Length, int Vpid);
  void SetBrokenLink(void);
  void SetClosedGop(void);
  int GetTref(void);
  void AdjGopTime(int Offset, int FramesPerSecond);
  void AdjTref(int TrefOffset);
  };

cMpeg2Fixer::cMpeg2Fixer(uchar *Data, int Length, int Vpid)
{
  // Go to first video packet:
  for (; Length > 0; Data += TS_SIZE, Length -= TS_SIZE) {
      if (TsPid(Data) == Vpid) {
         Setup(Data, Length, Vpid);
         break;
         }
      }
}

bool cMpeg2Fixer::FindHeader(uint32_t Code, const char *Header)
{
  Reset();
  if (Find(Code))
     return true;
  esyslog("ERROR: %s header not found!", Header);
  return false;
}

void cMpeg2Fixer::SetBrokenLink(void)
{
  if (!FindHeader(0x000001B8, "GOP"))
     return;
  SkipBytes(3);
  uchar b = GetByte();
  if (!(b & 0x40)) { // GOP not closed
     b |= 0x20;
     SetByte(b, GetLastIndex());
     }
}

void cMpeg2Fixer::SetClosedGop(void)
{
  if (!FindHeader(0x000001B8, "GOP"))
     return;
  SkipBytes(3);
  uchar b = GetByte();
  b |= 0x40;
  SetByte(b, GetLastIndex());
}

int cMpeg2Fixer::GetTref(void)
{
  if (!FindHeader(0x00000100, "picture"))
     return 0;
  int Tref = GetByte() << 2;
  Tref |= GetByte() >> 6;
  return Tref;
}

void cMpeg2Fixer::AdjGopTime(int Offset, int FramesPerSecond)
{
  if (!FindHeader(0x000001B8, "GOP"))
     return;
  uchar Byte1 = GetByte();
  int Index1 = GetLastIndex();
  uchar Byte2 =  GetByte();
  int Index2 = GetLastIndex();
  uchar Byte3 = GetByte();
  int Index3 = GetLastIndex();
  uchar Byte4 =  GetByte();
  int Index4 = GetLastIndex();
  uchar Frame = ((Byte3 & 0x1F) << 1) | (Byte4 >> 7);
  uchar Sec   = ((Byte2 & 0x07) << 3) | (Byte3 >> 5);
  uchar Min   = ((Byte1 & 0x03) << 4) | (Byte2 >> 4);
  uchar Hour  = ((Byte1 & 0x7C) >> 2);
  int GopTime = ((Hour * 60 + Min) * 60 + Sec) * FramesPerSecond + Frame;
  if (GopTime) { // do not fix when zero
     GopTime += Offset;
     if (GopTime < 0)
        GopTime += 24 * 60 * 60 * FramesPerSecond;
     Frame = GopTime % FramesPerSecond;
     GopTime = GopTime / FramesPerSecond;
     Sec = GopTime % 60;
     GopTime = GopTime / 60;
     Min = GopTime % 60;
     GopTime = GopTime / 60;
     Hour = GopTime % 24;
     SetByte((Byte1 & 0x80) | (Hour << 2) | (Min >> 4), Index1);
     SetByte(((Min & 0x0F) << 4) | 0x08 | (Sec >> 3), Index2);
     SetByte(((Sec & 0x07) << 3) | (Frame >> 1), Index3);
     SetByte((Byte4 & 0x7F) | ((Frame & 0x01) << 7), Index4);
     }
}

void cMpeg2Fixer::AdjTref(int TrefOffset)
{
  if (!FindHeader(0x00000100, "picture"))
     return;
  int Tref = GetByte() << 2;
  int Index1 = GetLastIndex();
  uchar Byte2 = GetByte();
  int Index2 = GetLastIndex();
  Tref |= Byte2 >> 6;
  Tref -= TrefOffset;
  SetByte(Tref >> 2, Index1);
  SetByte((Tref << 6) | (Byte2 & 0x3F), Index2);
}

// --- cCuttingThread --------------------------------------------------------

class cCuttingThread : public cThread {
private:
  cString editedVersionName; // we add the edited version's name to Recordings only after the cutting process has successfully started, so we need to store that name here
  const char *error;
  bool isPesRecording;
  double framesPerSecond;
  cUnbufferedFile *fromFile, *toFile;
  cFileName *fromFileName, *toFileName;
  cIndexFile *fromIndex, *toIndex;
  cMarks fromMarks, toMarks;
  int numSequences;
  off_t maxVideoFileSize;
  off_t fileSize;
  bool suspensionLogged;
  int sequence;          // cutting sequence
  int delta;             // time between two frames (PTS ticks)
  int64_t lastVidPts;    // the video PTS of the last frame (in display order)
  bool multiFramePkt;    // multiple frames within one PES packet
  int64_t firstPts;      // first valid PTS, for dangling packet stripping
  int64_t offset;        // offset to add to all timestamps
  int tRefOffset;        // number of stripped frames in GOP
  uchar counter[MAXPID]; // the TS continuity counter for each PID
  bool keepPkt[MAXPID];  // flag for each PID to keep packets, for dangling packet stripping
  int numIFrames;        // number of I-frames without pending packets
  cPatPmtParser patPmtParser;
  bool Throttled(void);
  bool SwitchFile(bool Force = false);
  bool LoadFrame(int Index, uchar *Buffer, bool &Independent, int &Length);
  bool FramesAreEqual(int Index1, int Index2);
  void GetPendingPackets(uchar *Buffer, int &Length, int Index);
       // Gather all non-video TS packets from Index upward that either belong to
       // payloads that started before Index, or have a PTS that is before lastVidPts,
       // and add them to the end of the given Data.
  bool FixFrame(uchar *Data, int &Length, bool Independent, int Index, bool CutIn, bool CutOut);
  bool ProcessSequence(int LastEndIndex, int BeginIndex, int EndIndex, int NextBeginIndex);
protected:
  virtual void Action(void);
public:
  cCuttingThread(const char *FromFileName, const char *ToFileName);
  virtual ~cCuttingThread();
  const char *Error(void) { return error; }
  };

cCuttingThread::cCuttingThread(const char *FromFileName, const char *ToFileName)
:cThread("video cutting", true)
{
  error = NULL;
  fromFile = toFile = NULL;
  fromFileName = toFileName = NULL;
  fromIndex = toIndex = NULL;
  cRecording Recording(FromFileName);
  isPesRecording = Recording.IsPesRecording();
  framesPerSecond = Recording.FramesPerSecond();
  suspensionLogged = false;
  fileSize = 0;
  sequence = 0;
  delta = int(round(PTSTICKS / framesPerSecond));
  lastVidPts = -1;
  multiFramePkt = false;
  firstPts = -1;
  offset = 0;
  tRefOffset = 0;
  memset(counter, 0x00, sizeof(counter));
  numIFrames = 0;
  if (fromMarks.Load(FromFileName, framesPerSecond, isPesRecording) && fromMarks.Count()) {
     numSequences = fromMarks.GetNumSequences();
     if (numSequences > 0) {
        editedVersionName = ToFileName;
        fromFileName = new cFileName(FromFileName, false, true, isPesRecording);
        toFileName = new cFileName(ToFileName, true, true, isPesRecording);
        fromIndex = new cIndexFile(FromFileName, false, isPesRecording);
        toIndex = new cIndexFile(ToFileName, true, isPesRecording);
        toMarks.Load(ToFileName, framesPerSecond, isPesRecording); // doesn't actually load marks, just sets the file name
        maxVideoFileSize = MEGABYTE(Setup.MaxVideoFileSize);
        if (isPesRecording && maxVideoFileSize > MEGABYTE(MAXVIDEOFILESIZEPES))
           maxVideoFileSize = MEGABYTE(MAXVIDEOFILESIZEPES);
        Start();
        }
     else
        esyslog("no editing sequences found for %s", FromFileName);
     }
  else
     esyslog("no editing marks found for %s", FromFileName);
}

cCuttingThread::~cCuttingThread()
{
  Cancel(3);
  delete fromFileName;
  delete toFileName;
  delete fromIndex;
  delete toIndex;
}

bool cCuttingThread::Throttled(void)
{
  if (cIoThrottle::Engaged()) {
     if (!suspensionLogged) {
        dsyslog("suspending cutter thread");
        suspensionLogged = true;
        }
     return true;
     }
  else if (suspensionLogged) {
     dsyslog("resuming cutter thread");
     suspensionLogged = false;
     }
  return false;
}

bool cCuttingThread::LoadFrame(int Index, uchar *Buffer, bool &Independent, int &Length)
{
  uint16_t FileNumber;
  off_t FileOffset;
  if (fromIndex->Get(Index, &FileNumber, &FileOffset, &Independent, &Length)) {
     fromFile = fromFileName->SetOffset(FileNumber, FileOffset);
     if (fromFile) {
        fromFile->SetReadAhead(MEGABYTE(20));
        int len = ReadFrame(fromFile, Buffer,  Length, MAXFRAMESIZE);
        if (len < 0)
           error = "ReadFrame";
        else if (len != Length)
           Length = len;
        return error == NULL;
        }
     else
        error = "fromFile";
     }
  return false;
}

bool cCuttingThread::SwitchFile(bool Force)
{
  if (fileSize > maxVideoFileSize || Force) {
     toFile = toFileName->NextFile();
     if (!toFile) {
        error = "toFile";
        return false;
        }
     fileSize = 0;
     }
  return true;
}

class cHeapBuffer {
private:
  uchar *buffer;
public:
  cHeapBuffer(int Size) { buffer = MALLOC(uchar, Size); }
  ~cHeapBuffer() { free(buffer); }
  operator uchar * () { return buffer; }
  };

bool cCuttingThread::FramesAreEqual(int Index1, int Index2)
{
  cHeapBuffer Buffer1(MAXFRAMESIZE);
  cHeapBuffer Buffer2(MAXFRAMESIZE);
  if (!Buffer1 || !Buffer2)
     return false;
  bool Independent;
  int Length1;
  int Length2;
  if (LoadFrame(Index1, Buffer1, Independent, Length1) && LoadFrame(Index2, Buffer2, Independent, Length2)) {
     if (Length1 == Length2) {
        int Diffs = 0;
        for (int i = 0; i < Length1; i++) {
            if (Buffer1[i] != Buffer2[i]) {
               if (Diffs++ > 10) // the continuity counters of the PAT/PMT packets may differ
                  return false;
               }
            }
        return true;
        }
     }
  return false;
}

void cCuttingThread::GetPendingPackets(uchar *Data, int &Length, int Index)
{
  cHeapBuffer Buffer(MAXFRAMESIZE);
  if (!Buffer)
     return;
  bool Processed[MAXPID] = { false };
  cPacketStorage PacketStorage;
  int64_t LastPts = lastVidPts + delta;// adding one frame length to fully cover the very last frame
  Processed[patPmtParser.Vpid()] = true; // we only want non-video packets
  for (int NumIndependentFrames = 0; NumIndependentFrames < 2; Index++) {
      bool Independent;
      int len;
      if (LoadFrame(Index, Buffer, Independent, len)) {
         if (Independent)
            NumIndependentFrames++;
         for (uchar *p = Buffer; len >= TS_SIZE && *p == TS_SYNC_BYTE; len -= TS_SIZE, p += TS_SIZE) {
             int Pid = TsPid(p);
             if (Pid != PATPID && !patPmtParser.IsPmtPid(Pid) && !Processed[Pid]) {
                int64_t Pts = TsGetPts(p, TS_SIZE);
                if (Pts >= 0) {
                   int64_t d = PtsDiff(LastPts, Pts);
                   if (d < 0) // Pts is before LastPts
                      PacketStorage.Flush(Pid, Data, Length, MAXFRAMESIZE);
                   else { // Pts is at or after LastPts
                      NumIndependentFrames = 0; // we search until we find two consecutive I-frames without any more pending packets
                      Processed[Pid] = true;
                      }
                   }
                if (!Processed[Pid])
                   PacketStorage.Append(Pid, p, TS_SIZE);
                }
             }
         }
      else
         break;
      }
}

bool cCuttingThread::FixFrame(uchar *Data, int &Length, bool Independent, int Index, bool CutIn, bool CutOut)
{
  if (!patPmtParser.Vpid()) {
     if (!patPmtParser.ParsePatPmt(Data, Length))
        return false;
     }
  if (CutIn) {
     sequence++;
     memset(keepPkt, false, sizeof(keepPkt));
     numIFrames = 0;
     firstPts = TsGetPts(Data, Length);
     // Determine the PTS offset at the beginning of each sequence (except the first one):
     if (sequence != 1) {
        if (firstPts >= 0)
           offset = (lastVidPts + delta - firstPts) & MAX33BIT;
        }
     }
  if (CutOut)
     GetPendingPackets(Data, Length, Index + 1);
  if (Independent) {
     numIFrames++;
     tRefOffset = 0;
     }
  // Fix MPEG-2:
  if (patPmtParser.Vtype() == 2) {
     cMpeg2Fixer Mpeg2fixer(Data, Length, patPmtParser.Vpid());
     if (CutIn) {
        if (sequence == 1 || multiFramePkt)
           Mpeg2fixer.SetBrokenLink();
        else {
           Mpeg2fixer.SetClosedGop();
           tRefOffset = Mpeg2fixer.GetTref();
           }
        }
     if (tRefOffset)
        Mpeg2fixer.AdjTref(tRefOffset);
     if (sequence > 1 && Independent)
        Mpeg2fixer.AdjGopTime((offset - MAX33BIT) / delta, round(framesPerSecond));
     }
  bool DeletedFrame = false;
  bool GotVidPts = false;
  bool StripVideo = sequence > 1 && tRefOffset;
  uchar *p;
  int len;
  for (p = Data, len = Length; len >= TS_SIZE && *p == TS_SYNC_BYTE; p += TS_SIZE, len -= TS_SIZE) {
      int Pid = TsPid(p);
      // Strip dangling packets:
      if (numIFrames < 2 && Pid != PATPID && !patPmtParser.IsPmtPid(Pid)) {
         if (Pid != patPmtParser.Vpid() || StripVideo) {
            int64_t Pts = TsGetPts(p, TS_SIZE);
            if (Pts >= 0)
               keepPkt[Pid] = PtsDiff(firstPts, Pts) >= 0; // Pts is at or after FirstPts
            if (!keepPkt[Pid]) {
               TsHidePayload(p);
               numIFrames = 0; // we search until we find two consecutive I-frames without any more dangling packets
               if (Pid == patPmtParser.Vpid())
                  DeletedFrame = true;
               }
            }
         }
      // Adjust the TS continuity counter:
      if (sequence > 1) {
         if (TsHasPayload(p))
            counter[Pid] = (counter[Pid] + 1) & TS_CONT_CNT_MASK;
         TsSetContinuityCounter(p, counter[Pid]);
         }
      else
         counter[Pid] = TsContinuityCounter(p); // collect initial counters
      // Adjust PTS:
      int64_t Pts = TsGetPts(p, TS_SIZE);
      if (Pts >= 0) {
         if (sequence > 1) {
            Pts = PtsAdd(Pts, offset);
            TsSetPts(p, TS_SIZE, Pts);
            }
         // Keep track of the highest video PTS - in case of multiple fields per frame, take the first one
         if (!GotVidPts && Pid == patPmtParser.Vpid()) {
            GotVidPts = true;
            if (lastVidPts < 0 || PtsDiff(lastVidPts, Pts) > 0)
               lastVidPts = Pts;
            }
         }
      // Adjust DTS:
      if (sequence > 1) {
         int64_t Dts = TsGetDts(p, TS_SIZE);
         if (Dts >= 0) {
            Dts = PtsAdd(Dts, offset);
            if (CutIn)
               Dts = PtsAdd(Dts, tRefOffset * delta);
            TsSetDts(p, TS_SIZE, Dts);
            }
         int64_t Pcr = TsGetPcr(p);
         if (Pcr >= 0) {
            Pcr = Pcr + offset * PCRFACTOR;
            if (Pcr > MAX27MHZ)
               Pcr -= MAX27MHZ + 1;
            TsSetPcr(p, Pcr);
            }
         }
      }
  if (!DeletedFrame && !GotVidPts) {
     // Adjust PTS for multiple frames within a single PES packet:
     lastVidPts = (lastVidPts + delta) & MAX33BIT;
     multiFramePkt = true;
     }
  return DeletedFrame;
}

bool cCuttingThread::ProcessSequence(int LastEndIndex, int BeginIndex, int EndIndex, int NextBeginIndex)
{
  // Check for seamless connections:
  bool SeamlessBegin = LastEndIndex >= 0 && FramesAreEqual(LastEndIndex, BeginIndex);
  bool SeamlessEnd = NextBeginIndex >= 0 && FramesAreEqual(EndIndex, NextBeginIndex);
  // Process all frames from BeginIndex (included) to EndIndex (excluded):
  cHeapBuffer Buffer(MAXFRAMESIZE);
  if (!Buffer) {
     error = "malloc";
     return false;
     }
  for (int Index = BeginIndex; Running() && Index < EndIndex; Index++) {
      bool Independent;
      int Length;
      if (LoadFrame(Index, Buffer, Independent, Length)) {
         // Make sure there is enough disk space:
         AssertFreeDiskSpace(-1);
         bool CutIn = !SeamlessBegin && Index == BeginIndex;
         bool CutOut = !SeamlessEnd && Index == EndIndex - 1;
         bool DeletedFrame = false;
         if (!isPesRecording) {
            DeletedFrame = FixFrame(Buffer, Length, Independent, Index, CutIn, CutOut);
            }
         else if (CutIn)
            cRemux::SetBrokenLink(Buffer, Length);
         // Every file shall start with an independent frame:
         if (Independent) {
            if (!SwitchFile())
               return false;
            }
         // Write index:
         if (!DeletedFrame && !toIndex->Write(Independent, toFileName->Number(), fileSize)) {
            error = "toIndex";
            return false;
            }
         // Write data:
         if (toFile->Write(Buffer, Length) < 0) {
            error = "safe_write";
            return false;
            }
         fileSize += Length;
         // Generate marks at the editing points in the edited recording:
         if (numSequences > 1 && Index == BeginIndex) {
            if (toMarks.Count() > 0)
               toMarks.Add(toIndex->Last());
            toMarks.Add(toIndex->Last());
            toMarks.Save();
            }
         }
      else
         return false;
      }
  return true;
}

void cCuttingThread::Action(void)
{
  if (cMark *BeginMark = fromMarks.GetNextBegin()) {
     fromFile = fromFileName->Open();
     toFile = toFileName->Open();
     if (!fromFile || !toFile)
        return;
     {
       LOCK_RECORDINGS_WRITE;
       Recordings->AddByName(editedVersionName, false);
     }
     int LastEndIndex = -1;
     while (BeginMark && Running()) {
           // Suspend cutting if we have severe throughput problems:
           if (Throttled()) {
              cCondWait::SleepMs(100);
              continue;
              }
           // Determine the actual begin and end marks, skipping any marks at the same position:
           cMark *EndMark = fromMarks.GetNextEnd(BeginMark);
           // Process the current sequence:
           int EndIndex = EndMark ? EndMark->Position() : fromIndex->Last() + 1;
           int NextBeginIndex = -1;
           if (EndMark) {
              if (cMark *NextBeginMark = fromMarks.GetNextBegin(EndMark))
                 NextBeginIndex = NextBeginMark->Position();
              }
           if (!ProcessSequence(LastEndIndex, BeginMark->Position(), EndIndex, NextBeginIndex))
              break;
           if (!EndMark)
              break; // reached EOF
           LastEndIndex = EndIndex;
           // Switch to the next sequence:
           BeginMark = fromMarks.GetNextBegin(EndMark);
           if (BeginMark) {
              // Split edited files:
              if (Setup.SplitEditedFiles) {
                 if (!SwitchFile(true))
                    break;
                 }
              }
           }
     }
  else
     esyslog("no editing marks found!");
}

// --- cCutter ---------------------------------------------------------------

cCutter::cCutter(const char *FileName)
{
  cuttingThread = NULL;
  error = false;
  originalVersionName = FileName;
}

cCutter::~cCutter()
{
  Stop();
}

cString cCutter::EditedFileName(const char *FileName)
{
  cRecording Recording(FileName);
  cMarks Marks;
  if (Marks.Load(FileName, Recording.FramesPerSecond(), Recording.IsPesRecording())) {
     if (cMark *First = Marks.GetNextBegin())
        Recording.SetStartTime(Recording.Start() + (int(First->Position() / Recording.FramesPerSecond() + 30) / 60) * 60);
     return Recording.PrefixFileName('%');
     }
  return NULL;
}

bool cCutter::Start(void)
{
  if (!cuttingThread) {
     error = false;
     if (*originalVersionName) {
        cRecording Recording(originalVersionName);
        editedVersionName = EditedFileName(originalVersionName);
        if (*editedVersionName) {
           if (strcmp(originalVersionName, editedVersionName) != 0) { // names must be different!
              cRecordingUserCommand::InvokeCommand(RUC_EDITINGRECORDING, editedVersionName, originalVersionName);
              if (cVideoDirectory::RemoveVideoFile(editedVersionName) && MakeDirs(editedVersionName, true)) {
                 Recording.WriteInfo(editedVersionName);
                 cuttingThread = new cCuttingThread(originalVersionName, editedVersionName);
                 return true;
                 }
              }
           }
        }
     }
  return false;
}

void cCutter::Stop(void)
{
  bool Interrupted = cuttingThread && cuttingThread->Active();
  const char *Error = cuttingThread ? cuttingThread->Error() : NULL;
  delete cuttingThread;
  cuttingThread = NULL;
  if ((Interrupted || Error) && *editedVersionName) {
     if (Interrupted)
        isyslog("editing process has been interrupted");
     if (Error)
        esyslog("ERROR: '%s' during editing process", Error);
     if (cReplayControl::NowReplaying() && strcmp(cReplayControl::NowReplaying(), editedVersionName) == 0)
        cControl::Shutdown();
     cVideoDirectory::RemoveVideoFile(editedVersionName);
     LOCK_RECORDINGS_WRITE;
     Recordings->DelByName(editedVersionName);
     }
}

bool cCutter::Active(void)
{
  if (cuttingThread) {
     if (cuttingThread->Active())
        return true;
     error = cuttingThread->Error();
     Stop();
     if (!error)
        cRecordingUserCommand::InvokeCommand(RUC_EDITEDRECORDING, editedVersionName, originalVersionName);
     }
  return false;
}

bool cCutter::Error(void)
{
  return error;
}

#define CUTTINGCHECKINTERVAL 500 // ms between checks for the active cutting process

bool CutRecording(const char *FileName)
{
  if (DirectoryOk(FileName)) {
     cRecording Recording(FileName);
     if (Recording.Name()) {
        cMarks Marks;
        if (Marks.Load(FileName, Recording.FramesPerSecond(), Recording.IsPesRecording()) && Marks.Count()) {
           if (Marks.GetNumSequences()) {
              cCutter Cutter(FileName);
              if (Cutter.Start()) {
                 while (Cutter.Active())
                       cCondWait::SleepMs(CUTTINGCHECKINTERVAL);
                 if (!Cutter.Error())
                    return true;
                 fprintf(stderr, "error while cutting\n");
                 }
              else
                 fprintf(stderr, "can't start editing process\n");
              }
           else
              fprintf(stderr, "'%s' has no editing sequences\n", FileName);
           }
        else
           fprintf(stderr, "'%s' has no editing marks\n", FileName);
        }
     else
        fprintf(stderr, "'%s' is not a recording\n", FileName);
     }
  else
     fprintf(stderr, "'%s' is not a directory\n", FileName);
  return false;
}