summaryrefslogtreecommitdiff
path: root/cutter.c
blob: 21f915600c9ca91a81ceec3ca72c48fe288ddf38 (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
/*
 * 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 2.19 2012/11/26 17:21:14 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);
}

// --- cDanglingPacketStripper -----------------------------------------------

class cDanglingPacketStripper {
private:
  bool processed[MAXPID];
  cPatPmtParser patPmtParser;
public:
  cDanglingPacketStripper(void);
  bool Process(uchar *Data, int Length, int64_t FirstPts);
       ///< Scans the frame given in Data and hides the payloads of any TS packets
       ///< that either didn't start within this frame, or have a PTS that is
       ///< before FirstPts. The TS packets in question are not physically removed
       ///< from Data in order to keep any frame counts and PCR timestamps intact.
       ///< Returns true if any dangling packets have been found.
  };

cDanglingPacketStripper::cDanglingPacketStripper(void)
{
  memset(processed, 0x00, sizeof(processed));
}

bool cDanglingPacketStripper::Process(uchar *Data, int Length, int64_t FirstPts)
{
  bool Found = false;
  while (Length >= TS_SIZE && *Data == TS_SYNC_BYTE) {
        int Pid = TsPid(Data);
        if (Pid == PATPID)
           patPmtParser.ParsePat(Data, TS_SIZE);
        else if (patPmtParser.IsPmtPid(Pid))
           patPmtParser.ParsePmt(Data, TS_SIZE);
        else {
           int64_t Pts = TsGetPts(Data, TS_SIZE);
           if (Pts >= 0)
              processed[Pid] = PtsDiff(FirstPts, Pts) >= 0; // Pts is at or after FirstPts
           if (!processed[Pid]) {
              TsHidePayload(Data);
              Found = true;
              }
           }
        Length -= TS_SIZE;
        Data += TS_SIZE;
        }
  return Found;
}

// --- cPtsFixer -------------------------------------------------------------

class cPtsFixer {
private:
  int delta; // time between two frames
  int64_t last; // the last (i.e. highest) video PTS value seen
  int64_t offset; // offset to add to PTS values
  bool fixCounters; // controls fixing the TS continuity counters (only from the second CutIn up)
  uchar counter[MAXPID]; // the TS continuity counter for each PID
  cPatPmtParser patPmtParser;
public:
  cPtsFixer(void);
  void Setup(double FramesPerSecond);
  void Fix(uchar *Data, int Length, bool CutIn);
  };

cPtsFixer::cPtsFixer(void)
{
  delta = 0;
  last = -1;
  offset = -1;
  fixCounters = false;
  memset(counter, 0x00, sizeof(counter));
}

void cPtsFixer::Setup(double FramesPerSecond)
{
  delta = int(round(PTSTICKS / FramesPerSecond));
}

void cPtsFixer::Fix(uchar *Data, int Length, bool CutIn)
{
  if (!patPmtParser.Vpid()) {
     if (!patPmtParser.ParsePatPmt(Data, Length))
        return;
     }
  // Determine the PTS offset at the beginning of each sequence (except the first one):
  if (CutIn && last >= 0) {
     int64_t Pts = TsGetPts(Data, Length);
     if (Pts >= 0) {
        // offset is calculated so that Pts + offset results in last + delta:
        offset = Pts - PtsAdd(last, delta);
        if (offset <= 0)
           offset = -offset;
        else
           offset = MAX33BIT + 1 - offset;
        }
     fixCounters = true;
     }
  // Keep track of the highest video PTS:
  uchar *p = Data;
  int len = Length;
  while (len >= TS_SIZE && *p == TS_SYNC_BYTE) {
        int Pid = TsPid(p);
        if (Pid == patPmtParser.Vpid()) {
           int64_t Pts = PtsAdd(TsGetPts(p, TS_SIZE), offset); // offset is taken into account here, to make last have the "new" value already!
           if (Pts >= 0 && (last < 0 || PtsDiff(last, Pts) > 0))
              last = Pts;
           }
        // Adjust the TS continuity counter:
        if (fixCounters) {
           if (TsHasPayload(p))
              counter[Pid] = (counter[Pid] + 1) & TS_CONT_CNT_MASK;
           TsSetContinuityCounter(p, counter[Pid]);
           }
        else
           counter[Pid] = TsGetContinuityCounter(p); // collect initial counters
        p += TS_SIZE;
        len -= TS_SIZE;
        }
  // Apply the PTS offset:
  if (offset > 0) {
     uchar *p = Data;
     int len = Length;
     while (len >= TS_SIZE && *p == TS_SYNC_BYTE) {
           // Adjust the various timestamps:
           int64_t Pts = TsGetPts(p, TS_SIZE);
           if (Pts >= 0)
              TsSetPts(p, TS_SIZE, PtsAdd(Pts, offset));
           int64_t Dts = TsGetDts(p, TS_SIZE);
           if (Dts >= 0)
              TsSetDts(p, TS_SIZE, PtsAdd(Dts, offset));
           int64_t Pcr = TsGetPcr(p);
           if (Pcr >= 0) {
              int64_t NewPcr = Pcr + offset * PCRFACTOR;
              if (NewPcr >= MAX27MHZ)
                 NewPcr -= MAX27MHZ + 1;
              TsSetPcr(p, NewPcr);
              }
           p += TS_SIZE;
           len -= TS_SIZE;
           }
     }
}

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

class cCuttingThread : public cThread {
private:
  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;
  cPtsFixer ptsFixer;
  bool suspensionLogged;
  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, int64_t LastPts);
       // 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 LastPts,
       // and add them to the end of the given Data.
  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;
  ptsFixer.Setup(framesPerSecond);
  if (fromMarks.Load(FromFileName, framesPerSecond, isPesRecording) && fromMarks.Count()) {
     numSequences = fromMarks.GetNumSequences();
     if (numSequences > 0) {
        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;
}

bool cCuttingThread::FramesAreEqual(int Index1, int Index2)
{
  bool Independent;
  uchar Buffer1[MAXFRAMESIZE];
  uchar Buffer2[MAXFRAMESIZE];
  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, int64_t LastPts)
{
  bool Processed[MAXPID] = { false };
  int NumIndependentFrames = 0;
  cPatPmtParser PatPmtParser;
  cPacketStorage PacketStorage;
  for (; NumIndependentFrames < 2; Index++) {
      uchar Buffer[MAXFRAMESIZE];
      bool Independent;
      int len;
      if (LoadFrame(Index, Buffer, Independent, len)) {
         if (Independent)
            NumIndependentFrames++;
         uchar *p = Buffer;
         while (len >= TS_SIZE && *p == TS_SYNC_BYTE) {
               int Pid = TsPid(p);
               if (Pid == PATPID)
                  PatPmtParser.ParsePat(p, TS_SIZE);
               else if (PatPmtParser.IsPmtPid(Pid)) {
                  PatPmtParser.ParsePmt(p, TS_SIZE);
                  Processed[PatPmtParser.Vpid()] = true; // we only want non-video packets
                  }
               else if (!Processed[Pid]) {
                  int64_t Pts = TsGetPts(p, TS_SIZE);
                  if (Pts >= 0) {
                     int64_t d = PtsDiff(LastPts, Pts);
                     if (d <= 0) // Pts is before or at LastPts
                        PacketStorage.Flush(Pid, Data, Length, MAXFRAMESIZE);
                     if (d >= 0) { // 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);
                  }
               len -= TS_SIZE;
               p += TS_SIZE;
               }
         }
      else
         break;
      }
}

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):
  cDanglingPacketStripper DanglingPacketStripper;
  int NumIndependentFrames = 0;
  int64_t FirstPts = -1;
  int64_t LastPts = -1;
  for (int Index = BeginIndex; Running() && Index < EndIndex; Index++) {
      uchar Buffer[MAXFRAMESIZE];
      bool Independent;
      int Length;
      if (LoadFrame(Index, Buffer, Independent, Length)) {
         if (!isPesRecording) {
            int64_t Pts = TsGetPts(Buffer, Length);
            if (FirstPts < 0)
               FirstPts = Pts; // the PTS of the first frame in the sequence
            else if (LastPts < 0 || PtsDiff(LastPts, Pts) > 0)
               LastPts = Pts; // the PTS of the frame that is displayed as the very last one of the sequence
            }
         // Fixup data at the beginning of the sequence:
         if (!SeamlessBegin) {
            if (isPesRecording) {
               if (Index == BeginIndex)
                  cRemux::SetBrokenLink(Buffer, Length);
               }
            else if (NumIndependentFrames < 2) {
               if (DanglingPacketStripper.Process(Buffer, Length, FirstPts))
                  NumIndependentFrames = 0; // we search until we find two consecutive I-frames without any more dangling packets
               }
            }
         // Fixup data at the end of the sequence:
         if (!SeamlessEnd) {
            if (Index == EndIndex - 1) {
               if (!isPesRecording)
                  GetPendingPackets(Buffer, Length, EndIndex, LastPts + int(round(PTSTICKS / framesPerSecond))); // adding one frame length to fully cover the very last frame
               }
            }
         // Fixup timestamps and continuity counters:
         if (!isPesRecording) {
            if (numSequences > 1)
              ptsFixer.Fix(Buffer, Length, !SeamlessBegin && Index == BeginIndex);
            }
         // Every file shall start with an independent frame:
         if (Independent) {
            NumIndependentFrames++;
            if (!SwitchFile())
               return false;
            }
         // Write index:
         if (!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 > 0 && 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;
     int LastEndIndex = -1;
     while (BeginMark && Running()) {
           // Suspend cutting if we have severe throughput problems:
           if (Throttled()) {
              cCondWait::SleepMs(100);
              continue;
              }
           // Make sure there is enough disk space:
           AssertFreeDiskSpace(-1);
           // 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;
                 }
              }
           }
     Recordings.TouchUpdate();
     }
  else
     esyslog("no editing marks found!");
}

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

cMutex cCutter::mutex;
cString cCutter::originalVersionName;
cString cCutter::editedVersionName;
cCuttingThread *cCutter::cuttingThread = NULL;
bool cCutter::error = false;
bool cCutter::ended = false;

bool cCutter::Start(const char *FileName)
{
  cMutexLock MutexLock(&mutex);
  if (!cuttingThread) {
     error = false;
     ended = false;
     originalVersionName = FileName;
     cRecording Recording(FileName);

     cMarks FromMarks;
     FromMarks.Load(FileName, Recording.FramesPerSecond(), Recording.IsPesRecording());
     if (cMark *First = FromMarks.GetNextBegin())
        Recording.SetStartTime(Recording.Start() + (int(First->Position() / Recording.FramesPerSecond() + 30) / 60) * 60);

     const char *evn = Recording.PrefixFileName('%');
     if (evn && RemoveVideoFile(evn) && MakeDirs(evn, true)) {
        // XXX this can be removed once RenameVideoFile() follows symlinks (see videodir.c)
        // remove a possible deleted recording with the same name to avoid symlink mixups:
        char *s = strdup(evn);
        char *e = strrchr(s, '.');
        if (e) {
           if (strcmp(e, ".rec") == 0) {
              strcpy(e, ".del");
              RemoveVideoFile(s);
              }
           }
        free(s);
        // XXX
        editedVersionName = evn;
        Recording.WriteInfo();
        Recordings.AddByName(editedVersionName, false);
        cuttingThread = new cCuttingThread(FileName, editedVersionName);
        return true;
        }
     }
  return false;
}

void cCutter::Stop(void)
{
  cMutexLock MutexLock(&mutex);
  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();
     RemoveVideoFile(editedVersionName);
     Recordings.DelByName(editedVersionName);
     }
}

bool cCutter::Active(const char *FileName)
{
  cMutexLock MutexLock(&mutex);
  if (cuttingThread) {
     if (cuttingThread->Active())
        return !FileName || strcmp(FileName, originalVersionName) == 0 || strcmp(FileName, editedVersionName) == 0;
     error = cuttingThread->Error();
     Stop();
     if (!error)
        cRecordingUserCommand::InvokeCommand(RUC_EDITEDRECORDING, editedVersionName, originalVersionName);
     originalVersionName = NULL;
     editedVersionName = NULL;
     ended = true;
     }
  return false;
}

bool cCutter::Error(void)
{
  cMutexLock MutexLock(&mutex);
  bool result = error;
  error = false;
  return result;
}

bool cCutter::Ended(void)
{
  cMutexLock MutexLock(&mutex);
  bool result = ended;
  ended = false;
  return result;
}

#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()) {
              if (cCutter::Start(FileName)) {
                 while (cCutter::Active())
                       cCondWait::SleepMs(CUTTINGCHECKINTERVAL);
                 return true;
                 }
              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;
}