vdr  2.4.7
recording.c
Go to the documentation of this file.
1 /*
2  * recording.c: Recording file handling
3  *
4  * See the main source file 'vdr.c' for copyright information and
5  * how to reach the author.
6  *
7  * $Id: recording.c 4.29 2020/10/30 16:08:29 kls Exp $
8  */
9 
10 #include "recording.h"
11 #include <ctype.h>
12 #include <dirent.h>
13 #include <errno.h>
14 #include <fcntl.h>
15 #define __STDC_FORMAT_MACROS // Required for format specifiers
16 #include <inttypes.h>
17 #include <math.h>
18 #include <stdio.h>
19 #include <string.h>
20 #include <sys/stat.h>
21 #include <unistd.h>
22 #include "channels.h"
23 #include "cutter.h"
24 #include "i18n.h"
25 #include "interface.h"
26 #include "menu.h"
27 #include "remux.h"
28 #include "ringbuffer.h"
29 #include "skins.h"
30 #include "svdrp.h"
31 #include "tools.h"
32 #include "videodir.h"
33 
34 #define SUMMARYFALLBACK
35 
36 #define RECEXT ".rec"
37 #define DELEXT ".del"
38 /* This was the original code, which works fine in a Linux only environment.
39  Unfortunately, because of Windows and its brain dead file system, we have
40  to use a more complicated approach, in order to allow users who have enabled
41  the --vfat command line option to see their recordings even if they forget to
42  enable --vfat when restarting VDR... Gee, do I hate Windows.
43  (kls 2002-07-27)
44 #define DATAFORMAT "%4d-%02d-%02d.%02d:%02d.%02d.%02d" RECEXT
45 #define NAMEFORMAT "%s/%s/" DATAFORMAT
46 */
47 #define DATAFORMATPES "%4d-%02d-%02d.%02d%*c%02d.%02d.%02d" RECEXT
48 #define NAMEFORMATPES "%s/%s/" "%4d-%02d-%02d.%02d.%02d.%02d.%02d" RECEXT
49 #define DATAFORMATTS "%4d-%02d-%02d.%02d.%02d.%d-%d" RECEXT
50 #define NAMEFORMATTS "%s/%s/" DATAFORMATTS
51 
52 #define RESUMEFILESUFFIX "/resume%s%s"
53 #ifdef SUMMARYFALLBACK
54 #define SUMMARYFILESUFFIX "/summary.vdr"
55 #endif
56 #define INFOFILESUFFIX "/info"
57 #define MARKSFILESUFFIX "/marks"
58 
59 #define SORTMODEFILE ".sort"
60 #define TIMERRECFILE ".timer"
61 
62 #define MINDISKSPACE 1024 // MB
63 
64 #define REMOVECHECKDELTA 60 // seconds between checks for removing deleted files
65 #define DELETEDLIFETIME 300 // seconds after which a deleted recording will be actually removed
66 #define DISKCHECKDELTA 100 // seconds between checks for free disk space
67 #define REMOVELATENCY 10 // seconds to wait until next check after removing a file
68 #define MARKSUPDATEDELTA 10 // seconds between checks for updating editing marks
69 #define MININDEXAGE 3600 // seconds before an index file is considered no longer to be written
70 #define MAXREMOVETIME 10 // seconds after which to return from removing deleted recordings
71 
72 #define MAX_LINK_LEVEL 6
73 
74 #define LIMIT_SECS_PER_MB_RADIO 5 // radio recordings typically have more than this
75 
76 int DirectoryPathMax = PATH_MAX - 1;
77 int DirectoryNameMax = NAME_MAX;
78 bool DirectoryEncoding = false;
79 int InstanceId = 0;
80 
81 // --- cRemoveDeletedRecordingsThread ----------------------------------------
82 
84 protected:
85  virtual void Action(void);
86 public:
88  };
89 
91 :cThread("remove deleted recordings", true)
92 {
93 }
94 
96 {
97  // Make sure only one instance of VDR does this:
98  cLockFile LockFile(cVideoDirectory::Name());
99  if (LockFile.Lock()) {
100  time_t StartTime = time(NULL);
101  bool deleted = false;
102  bool interrupted = false;
104  for (cRecording *r = DeletedRecordings->First(); r; ) {
105  if (cIoThrottle::Engaged())
106  interrupted = true;
107  else if (time(NULL) - StartTime > MAXREMOVETIME)
108  interrupted = true; // don't stay here too long
109  else if (cRemote::HasKeys())
110  interrupted = true; // react immediately on user input
111  if (interrupted)
112  break;
113  if (r->Deleted() && time(NULL) - r->Deleted() > DELETEDLIFETIME) {
114  cRecording *next = DeletedRecordings->Next(r);
115  r->Remove();
116  DeletedRecordings->Del(r);
117  r = next;
118  deleted = true;
119  }
120  else
121  r = DeletedRecordings->Next(r);
122  }
123  if (deleted) {
125  if (!interrupted) {
126  const char *IgnoreFiles[] = { SORTMODEFILE, TIMERRECFILE, NULL };
128  }
129  }
130  }
131 }
132 
134 
135 // ---
136 
138 {
139  static time_t LastRemoveCheck = 0;
140  if (time(NULL) - LastRemoveCheck > REMOVECHECKDELTA) {
143  for (const cRecording *r = DeletedRecordings->First(); r; r = DeletedRecordings->Next(r)) {
144  if (r->Deleted() && time(NULL) - r->Deleted() > DELETEDLIFETIME) {
146  break;
147  }
148  }
149  }
150  LastRemoveCheck = time(NULL);
151  }
152 }
153 
154 void AssertFreeDiskSpace(int Priority, bool Force)
155 {
156  static cMutex Mutex;
157  cMutexLock MutexLock(&Mutex);
158  // With every call to this function we try to actually remove
159  // a file, or mark a file for removal ("delete" it), so that
160  // it will get removed during the next call.
161  static time_t LastFreeDiskCheck = 0;
162  int Factor = (Priority == -1) ? 10 : 1;
163  if (Force || time(NULL) - LastFreeDiskCheck > DISKCHECKDELTA / Factor) {
165  // Make sure only one instance of VDR does this:
166  cLockFile LockFile(cVideoDirectory::Name());
167  if (!LockFile.Lock())
168  return;
169  // Remove the oldest file that has been "deleted":
170  isyslog("low disk space while recording, trying to remove a deleted recording...");
171  int NumDeletedRecordings = 0;
172  {
174  NumDeletedRecordings = DeletedRecordings->Count();
175  if (NumDeletedRecordings) {
176  cRecording *r = DeletedRecordings->First();
177  cRecording *r0 = NULL;
178  while (r) {
179  if (r->IsOnVideoDirectoryFileSystem()) { // only remove recordings that will actually increase the free video disk space
180  if (!r0 || r->Start() < r0->Start())
181  r0 = r;
182  }
183  r = DeletedRecordings->Next(r);
184  }
185  if (r0) {
186  if (r0->Remove())
187  LastFreeDiskCheck += REMOVELATENCY / Factor;
188  DeletedRecordings->Del(r0);
189  return;
190  }
191  }
192  }
193  if (NumDeletedRecordings == 0) {
194  // DeletedRecordings was empty, so to be absolutely sure there are no
195  // deleted recordings we need to double check:
196  cRecordings::Update(true);
198  if (DeletedRecordings->Count())
199  return; // the next call will actually remove it
200  }
201  // No "deleted" files to remove, so let's see if we can delete a recording:
202  if (Priority > 0) {
203  isyslog("...no deleted recording found, trying to delete an old recording...");
205  Recordings->SetExplicitModify();
206  if (Recordings->Count()) {
207  cRecording *r = Recordings->First();
208  cRecording *r0 = NULL;
209  while (r) {
210  if (r->IsOnVideoDirectoryFileSystem()) { // only delete recordings that will actually increase the free video disk space
211  if (!r->IsEdited() && r->Lifetime() < MAXLIFETIME) { // edited recordings and recordings with MAXLIFETIME live forever
212  if ((r->Lifetime() == 0 && Priority > r->Priority()) || // the recording has no guaranteed lifetime and the new recording has higher priority
213  (r->Lifetime() > 0 && (time(NULL) - r->Start()) / SECSINDAY >= r->Lifetime())) { // the recording's guaranteed lifetime has expired
214  if (r0) {
215  if (r->Priority() < r0->Priority() || (r->Priority() == r0->Priority() && r->Start() < r0->Start()))
216  r0 = r; // in any case we delete the one with the lowest priority (or the older one in case of equal priorities)
217  }
218  else
219  r0 = r;
220  }
221  }
222  }
223  r = Recordings->Next(r);
224  }
225  if (r0 && r0->Delete()) {
226  Recordings->Del(r0);
227  Recordings->SetModified();
228  return;
229  }
230  }
231  // Unable to free disk space, but there's nothing we can do about that...
232  isyslog("...no old recording found, giving up");
233  }
234  else
235  isyslog("...no deleted recording found, priority %d too low to trigger deleting an old recording", Priority);
236  Skins.QueueMessage(mtWarning, tr("Low disk space!"), 5, -1);
237  }
238  LastFreeDiskCheck = time(NULL);
239  }
240 }
241 
242 // --- cResumeFile -----------------------------------------------------------
243 
244 cResumeFile::cResumeFile(const char *FileName, bool IsPesRecording)
245 {
246  isPesRecording = IsPesRecording;
247  const char *Suffix = isPesRecording ? RESUMEFILESUFFIX ".vdr" : RESUMEFILESUFFIX;
248  fileName = MALLOC(char, strlen(FileName) + strlen(Suffix) + 1);
249  if (fileName) {
250  strcpy(fileName, FileName);
251  sprintf(fileName + strlen(fileName), Suffix, Setup.ResumeID ? "." : "", Setup.ResumeID ? *itoa(Setup.ResumeID) : "");
252  }
253  else
254  esyslog("ERROR: can't allocate memory for resume file name");
255 }
256 
258 {
259  free(fileName);
260 }
261 
263 {
264  int resume = -1;
265  if (fileName) {
266  struct stat st;
267  if (stat(fileName, &st) == 0) {
268  if ((st.st_mode & S_IWUSR) == 0) // no write access, assume no resume
269  return -1;
270  }
271  if (isPesRecording) {
272  int f = open(fileName, O_RDONLY);
273  if (f >= 0) {
274  if (safe_read(f, &resume, sizeof(resume)) != sizeof(resume)) {
275  resume = -1;
277  }
278  close(f);
279  }
280  else if (errno != ENOENT)
282  }
283  else {
284  FILE *f = fopen(fileName, "r");
285  if (f) {
286  cReadLine ReadLine;
287  char *s;
288  int line = 0;
289  while ((s = ReadLine.Read(f)) != NULL) {
290  ++line;
291  char *t = skipspace(s + 1);
292  switch (*s) {
293  case 'I': resume = atoi(t);
294  break;
295  default: ;
296  }
297  }
298  fclose(f);
299  }
300  else if (errno != ENOENT)
302  }
303  }
304  return resume;
305 }
306 
307 bool cResumeFile::Save(int Index)
308 {
309  if (fileName) {
310  if (isPesRecording) {
311  int f = open(fileName, O_WRONLY | O_CREAT | O_TRUNC, DEFFILEMODE);
312  if (f >= 0) {
313  if (safe_write(f, &Index, sizeof(Index)) < 0)
315  close(f);
317  Recordings->ResetResume(fileName);
318  return true;
319  }
320  }
321  else {
322  FILE *f = fopen(fileName, "w");
323  if (f) {
324  fprintf(f, "I %d\n", Index);
325  fclose(f);
327  Recordings->ResetResume(fileName);
328  }
329  else
331  return true;
332  }
333  }
334  return false;
335 }
336 
338 {
339  if (fileName) {
340  if (remove(fileName) == 0) {
342  Recordings->ResetResume(fileName);
343  }
344  else if (errno != ENOENT)
346  }
347 }
348 
349 // --- cRecordingInfo --------------------------------------------------------
350 
351 cRecordingInfo::cRecordingInfo(const cChannel *Channel, const cEvent *Event)
352 {
353  channelID = Channel ? Channel->GetChannelID() : tChannelID::InvalidID;
354  channelName = Channel ? strdup(Channel->Name()) : NULL;
355  ownEvent = Event ? NULL : new cEvent(0);
356  event = ownEvent ? ownEvent : Event;
357  aux = NULL;
361  fileName = NULL;
362  if (Channel) {
363  // Since the EPG data's component records can carry only a single
364  // language code, let's see whether the channel's PID data has
365  // more information:
367  if (!Components)
368  Components = new cComponents;
369  for (int i = 0; i < MAXAPIDS; i++) {
370  const char *s = Channel->Alang(i);
371  if (*s) {
372  tComponent *Component = Components->GetComponent(i, 2, 3);
373  if (!Component)
374  Components->SetComponent(Components->NumComponents(), 2, 3, s, NULL);
375  else if (strlen(s) > strlen(Component->language))
376  strn0cpy(Component->language, s, sizeof(Component->language));
377  }
378  }
379  // There's no "multiple languages" for Dolby Digital tracks, but
380  // we do the same procedure here, too, in case there is no component
381  // information at all:
382  for (int i = 0; i < MAXDPIDS; i++) {
383  const char *s = Channel->Dlang(i);
384  if (*s) {
385  tComponent *Component = Components->GetComponent(i, 4, 0); // AC3 component according to the DVB standard
386  if (!Component)
387  Component = Components->GetComponent(i, 2, 5); // fallback "Dolby" component according to the "Premiere pseudo standard"
388  if (!Component)
389  Components->SetComponent(Components->NumComponents(), 2, 5, s, NULL);
390  else if (strlen(s) > strlen(Component->language))
391  strn0cpy(Component->language, s, sizeof(Component->language));
392  }
393  }
394  // The same applies to subtitles:
395  for (int i = 0; i < MAXSPIDS; i++) {
396  const char *s = Channel->Slang(i);
397  if (*s) {
398  tComponent *Component = Components->GetComponent(i, 3, 3);
399  if (!Component)
400  Components->SetComponent(Components->NumComponents(), 3, 3, s, NULL);
401  else if (strlen(s) > strlen(Component->language))
402  strn0cpy(Component->language, s, sizeof(Component->language));
403  }
404  }
405  if (Components != event->Components())
406  ((cEvent *)event)->SetComponents(Components);
407  }
408 }
409 
410 cRecordingInfo::cRecordingInfo(const char *FileName)
411 {
413  channelName = NULL;
414  ownEvent = new cEvent(0);
415  event = ownEvent;
416  aux = NULL;
420  fileName = strdup(cString::sprintf("%s%s", FileName, INFOFILESUFFIX));
421 }
422 
424 {
425  delete ownEvent;
426  free(aux);
427  free(channelName);
428  free(fileName);
429 }
430 
431 void cRecordingInfo::SetData(const char *Title, const char *ShortText, const char *Description)
432 {
433  if (Title)
434  ((cEvent *)event)->SetTitle(Title);
435  if (ShortText)
436  ((cEvent *)event)->SetShortText(ShortText);
437  if (Description)
438  ((cEvent *)event)->SetDescription(Description);
439 }
440 
441 void cRecordingInfo::SetAux(const char *Aux)
442 {
443  free(aux);
444  aux = Aux ? strdup(Aux) : NULL;
445 }
446 
447 void cRecordingInfo::SetFramesPerSecond(double FramesPerSecond)
448 {
450 }
451 
452 void cRecordingInfo::SetFileName(const char *FileName)
453 {
454  bool IsPesRecording = fileName && endswith(fileName, ".vdr");
455  free(fileName);
456  fileName = strdup(cString::sprintf("%s%s", FileName, IsPesRecording ? INFOFILESUFFIX ".vdr" : INFOFILESUFFIX));
457 }
458 
459 bool cRecordingInfo::Read(FILE *f)
460 {
461  if (ownEvent) {
462  cReadLine ReadLine;
463  char *s;
464  int line = 0;
465  while ((s = ReadLine.Read(f)) != NULL) {
466  ++line;
467  char *t = skipspace(s + 1);
468  switch (*s) {
469  case 'C': {
470  char *p = strchr(t, ' ');
471  if (p) {
472  free(channelName);
473  channelName = strdup(compactspace(p));
474  *p = 0; // strips optional channel name
475  }
476  if (*t)
478  }
479  break;
480  case 'E': {
481  unsigned int EventID;
482  time_t StartTime;
483  int Duration;
484  unsigned int TableID = 0;
485  unsigned int Version = 0xFF;
486  int n = sscanf(t, "%u %ld %d %X %X", &EventID, &StartTime, &Duration, &TableID, &Version);
487  if (n >= 3 && n <= 5) {
488  ownEvent->SetEventID(EventID);
489  ownEvent->SetStartTime(StartTime);
490  ownEvent->SetDuration(Duration);
491  ownEvent->SetTableID(uchar(TableID));
492  ownEvent->SetVersion(uchar(Version));
493  }
494  }
495  break;
496  case 'F': framesPerSecond = atod(t);
497  break;
498  case 'L': lifetime = atoi(t);
499  break;
500  case 'P': priority = atoi(t);
501  break;
502  case '@': free(aux);
503  aux = strdup(t);
504  break;
505  case '#': break; // comments are ignored
506  default: if (!ownEvent->Parse(s)) {
507  esyslog("ERROR: EPG data problem in line %d", line);
508  return false;
509  }
510  break;
511  }
512  }
513  return true;
514  }
515  return false;
516 }
517 
518 bool cRecordingInfo::Write(FILE *f, const char *Prefix) const
519 {
520  if (channelID.Valid())
521  fprintf(f, "%sC %s%s%s\n", Prefix, *channelID.ToString(), channelName ? " " : "", channelName ? channelName : "");
522  event->Dump(f, Prefix, true);
523  fprintf(f, "%sF %s\n", Prefix, *dtoa(framesPerSecond, "%.10g"));
524  fprintf(f, "%sP %d\n", Prefix, priority);
525  fprintf(f, "%sL %d\n", Prefix, lifetime);
526  if (aux)
527  fprintf(f, "%s@ %s\n", Prefix, aux);
528  return true;
529 }
530 
532 {
533  bool Result = false;
534  if (fileName) {
535  FILE *f = fopen(fileName, "r");
536  if (f) {
537  if (Read(f))
538  Result = true;
539  else
540  esyslog("ERROR: EPG data problem in file %s", fileName);
541  fclose(f);
542  }
543  else if (errno != ENOENT)
545  }
546  return Result;
547 }
548 
549 bool cRecordingInfo::Write(void) const
550 {
551  bool Result = false;
552  if (fileName) {
553  cSafeFile f(fileName);
554  if (f.Open()) {
555  if (Write(f))
556  Result = true;
557  f.Close();
558  }
559  else
561  }
562  return Result;
563 }
564 
565 // --- cRecording ------------------------------------------------------------
566 
567 #define RESUME_NOT_INITIALIZED (-2)
568 
569 struct tCharExchange { char a; char b; };
571  { FOLDERDELIMCHAR, '/' },
572  { '/', FOLDERDELIMCHAR },
573  { ' ', '_' },
574  // backwards compatibility:
575  { '\'', '\'' },
576  { '\'', '\x01' },
577  { '/', '\x02' },
578  { 0, 0 }
579  };
580 
581 const char *InvalidChars = "\"\\/:*?|<>#";
582 
583 bool NeedsConversion(const char *p)
584 {
585  return DirectoryEncoding &&
586  (strchr(InvalidChars, *p) // characters that can't be part of a Windows file/directory name
587  || *p == '.' && (!*(p + 1) || *(p + 1) == FOLDERDELIMCHAR)); // Windows can't handle '.' at the end of file/directory names
588 }
589 
590 char *ExchangeChars(char *s, bool ToFileSystem)
591 {
592  char *p = s;
593  while (*p) {
594  if (DirectoryEncoding) {
595  // Some file systems can't handle all characters, so we
596  // have to take extra efforts to encode/decode them:
597  if (ToFileSystem) {
598  switch (*p) {
599  // characters that can be mapped to other characters:
600  case ' ': *p = '_'; break;
601  case FOLDERDELIMCHAR: *p = '/'; break;
602  case '/': *p = FOLDERDELIMCHAR; break;
603  // characters that have to be encoded:
604  default:
605  if (NeedsConversion(p)) {
606  int l = p - s;
607  if (char *NewBuffer = (char *)realloc(s, strlen(s) + 10)) {
608  s = NewBuffer;
609  p = s + l;
610  char buf[4];
611  sprintf(buf, "#%02X", (unsigned char)*p);
612  memmove(p + 2, p, strlen(p) + 1);
613  memcpy(p, buf, 3);
614  p += 2;
615  }
616  else
617  esyslog("ERROR: out of memory");
618  }
619  }
620  }
621  else {
622  switch (*p) {
623  // mapped characters:
624  case '_': *p = ' '; break;
625  case FOLDERDELIMCHAR: *p = '/'; break;
626  case '/': *p = FOLDERDELIMCHAR; break;
627  // encoded characters:
628  case '#': {
629  if (strlen(p) > 2 && isxdigit(*(p + 1)) && isxdigit(*(p + 2))) {
630  char buf[3];
631  sprintf(buf, "%c%c", *(p + 1), *(p + 2));
632  uchar c = uchar(strtol(buf, NULL, 16));
633  if (c) {
634  *p = c;
635  memmove(p + 1, p + 3, strlen(p) - 2);
636  }
637  }
638  }
639  break;
640  // backwards compatibility:
641  case '\x01': *p = '\''; break;
642  case '\x02': *p = '/'; break;
643  case '\x03': *p = ':'; break;
644  default: ;
645  }
646  }
647  }
648  else {
649  for (struct tCharExchange *ce = CharExchange; ce->a && ce->b; ce++) {
650  if (*p == (ToFileSystem ? ce->a : ce->b)) {
651  *p = ToFileSystem ? ce->b : ce->a;
652  break;
653  }
654  }
655  }
656  p++;
657  }
658  return s;
659 }
660 
661 char *LimitNameLengths(char *s, int PathMax, int NameMax)
662 {
663  // Limits the total length of the directory path in 's' to PathMax, and each
664  // individual directory name to NameMax. The lengths of characters that need
665  // conversion when using 's' as a file name are taken into account accordingly.
666  // If a directory name exceeds NameMax, it will be truncated. If the whole
667  // directory path exceeds PathMax, individual directory names will be shortened
668  // (from right to left) until the limit is met, or until the currently handled
669  // directory name consists of only a single character. All operations are performed
670  // directly on the given 's', which may become shorter (but never longer) than
671  // the original value.
672  // Returns a pointer to 's'.
673  int Length = strlen(s);
674  int PathLength = 0;
675  // Collect the resulting lengths of each character:
676  bool NameTooLong = false;
677  int8_t a[Length];
678  int n = 0;
679  int NameLength = 0;
680  for (char *p = s; *p; p++) {
681  if (*p == FOLDERDELIMCHAR) {
682  a[n] = -1; // FOLDERDELIMCHAR is a single character, neg. sign marks it
683  NameTooLong |= NameLength > NameMax;
684  NameLength = 0;
685  PathLength += 1;
686  }
687  else if (NeedsConversion(p)) {
688  a[n] = 3; // "#xx"
689  NameLength += 3;
690  PathLength += 3;
691  }
692  else {
693  int8_t l = Utf8CharLen(p);
694  a[n] = l;
695  NameLength += l;
696  PathLength += l;
697  while (l-- > 1) {
698  a[++n] = 0;
699  p++;
700  }
701  }
702  n++;
703  }
704  NameTooLong |= NameLength > NameMax;
705  // Limit names to NameMax:
706  if (NameTooLong) {
707  while (n > 0) {
708  // Calculate the length of the current name:
709  int NameLength = 0;
710  int i = n;
711  int b = i;
712  while (i-- > 0 && a[i] >= 0) {
713  NameLength += a[i];
714  b = i;
715  }
716  // Shorten the name if necessary:
717  if (NameLength > NameMax) {
718  int l = 0;
719  i = n;
720  while (i-- > 0 && a[i] >= 0) {
721  l += a[i];
722  if (NameLength - l <= NameMax) {
723  memmove(s + i, s + n, Length - n + 1);
724  memmove(a + i, a + n, Length - n + 1);
725  Length -= n - i;
726  PathLength -= l;
727  break;
728  }
729  }
730  }
731  // Switch to the next name:
732  n = b - 1;
733  }
734  }
735  // Limit path to PathMax:
736  n = Length;
737  while (PathLength > PathMax && n > 0) {
738  // Calculate how much to cut off the current name:
739  int i = n;
740  int b = i;
741  int l = 0;
742  while (--i > 0 && a[i - 1] >= 0) {
743  if (a[i] > 0) {
744  l += a[i];
745  b = i;
746  if (PathLength - l <= PathMax)
747  break;
748  }
749  }
750  // Shorten the name if necessary:
751  if (l > 0) {
752  memmove(s + b, s + n, Length - n + 1);
753  Length -= n - b;
754  PathLength -= l;
755  }
756  // Switch to the next name:
757  n = i - 1;
758  }
759  return s;
760 }
761 
762 cRecording::cRecording(cTimer *Timer, const cEvent *Event)
763 {
764  id = 0;
766  titleBuffer = NULL;
768  fileName = NULL;
769  name = NULL;
770  fileSizeMB = -1; // unknown
771  channel = Timer->Channel()->Number();
773  isPesRecording = false;
774  isOnVideoDirectoryFileSystem = -1; // unknown
776  numFrames = -1;
777  deleted = 0;
778  // set up the actual name:
779  const char *Title = Event ? Event->Title() : NULL;
780  const char *Subtitle = Event ? Event->ShortText() : NULL;
781  if (isempty(Title))
782  Title = Timer->Channel()->Name();
783  if (isempty(Subtitle))
784  Subtitle = " ";
785  const char *macroTITLE = strstr(Timer->File(), TIMERMACRO_TITLE);
786  const char *macroEPISODE = strstr(Timer->File(), TIMERMACRO_EPISODE);
787  if (macroTITLE || macroEPISODE) {
788  name = strdup(Timer->File());
790  name = strreplace(name, TIMERMACRO_EPISODE, Subtitle);
791  // avoid blanks at the end:
792  int l = strlen(name);
793  while (l-- > 2) {
794  if (name[l] == ' ' && name[l - 1] != FOLDERDELIMCHAR)
795  name[l] = 0;
796  else
797  break;
798  }
799  if (Timer->IsSingleEvent())
800  Timer->SetFile(name); // this was an instant recording, so let's set the actual data
801  }
802  else if (Timer->IsSingleEvent() || !Setup.UseSubtitle)
803  name = strdup(Timer->File());
804  else
805  name = strdup(cString::sprintf("%s%c%s", Timer->File(), FOLDERDELIMCHAR, Subtitle));
806  // substitute characters that would cause problems in file names:
807  strreplace(name, '\n', ' ');
808  start = Timer->StartTime();
809  priority = Timer->Priority();
810  lifetime = Timer->Lifetime();
811  // handle info:
812  info = new cRecordingInfo(Timer->Channel(), Event);
813  info->SetAux(Timer->Aux());
816 }
817 
818 cRecording::cRecording(const char *FileName)
819 {
820  id = 0;
822  fileSizeMB = -1; // unknown
823  channel = -1;
824  instanceId = -1;
825  priority = MAXPRIORITY; // assume maximum in case there is no info file
827  isPesRecording = false;
828  isOnVideoDirectoryFileSystem = -1; // unknown
830  numFrames = -1;
831  deleted = 0;
832  titleBuffer = NULL;
834  FileName = fileName = strdup(FileName);
835  if (*(fileName + strlen(fileName) - 1) == '/')
836  *(fileName + strlen(fileName) - 1) = 0;
837  if (strstr(FileName, cVideoDirectory::Name()) == FileName)
838  FileName += strlen(cVideoDirectory::Name()) + 1;
839  const char *p = strrchr(FileName, '/');
840 
841  name = NULL;
843  if (p) {
844  time_t now = time(NULL);
845  struct tm tm_r;
846  struct tm t = *localtime_r(&now, &tm_r); // this initializes the time zone in 't'
847  t.tm_isdst = -1; // makes sure mktime() will determine the correct DST setting
848  if (7 == sscanf(p + 1, DATAFORMATTS, &t.tm_year, &t.tm_mon, &t.tm_mday, &t.tm_hour, &t.tm_min, &channel, &instanceId)
849  || 7 == sscanf(p + 1, DATAFORMATPES, &t.tm_year, &t.tm_mon, &t.tm_mday, &t.tm_hour, &t.tm_min, &priority, &lifetime)) {
850  t.tm_year -= 1900;
851  t.tm_mon--;
852  t.tm_sec = 0;
853  start = mktime(&t);
854  name = MALLOC(char, p - FileName + 1);
855  strncpy(name, FileName, p - FileName);
856  name[p - FileName] = 0;
857  name = ExchangeChars(name, false);
859  }
860  else
861  return;
862  GetResume();
863  // read an optional info file:
864  cString InfoFileName = cString::sprintf("%s%s", fileName, isPesRecording ? INFOFILESUFFIX ".vdr" : INFOFILESUFFIX);
865  FILE *f = fopen(InfoFileName, "r");
866  if (f) {
867  if (!info->Read(f))
868  esyslog("ERROR: EPG data problem in file %s", *InfoFileName);
869  else if (!isPesRecording) {
873  }
874  fclose(f);
875  }
876  else if (errno == ENOENT)
878  else
879  LOG_ERROR_STR(*InfoFileName);
880 #ifdef SUMMARYFALLBACK
881  // fall back to the old 'summary.vdr' if there was no 'info.vdr':
882  if (isempty(info->Title())) {
883  cString SummaryFileName = cString::sprintf("%s%s", fileName, SUMMARYFILESUFFIX);
884  FILE *f = fopen(SummaryFileName, "r");
885  if (f) {
886  int line = 0;
887  char *data[3] = { NULL };
888  cReadLine ReadLine;
889  char *s;
890  while ((s = ReadLine.Read(f)) != NULL) {
891  if (*s || line > 1) {
892  if (data[line]) {
893  int len = strlen(s);
894  len += strlen(data[line]) + 1;
895  if (char *NewBuffer = (char *)realloc(data[line], len + 1)) {
896  data[line] = NewBuffer;
897  strcat(data[line], "\n");
898  strcat(data[line], s);
899  }
900  else
901  esyslog("ERROR: out of memory");
902  }
903  else
904  data[line] = strdup(s);
905  }
906  else
907  line++;
908  }
909  fclose(f);
910  if (!data[2]) {
911  data[2] = data[1];
912  data[1] = NULL;
913  }
914  else if (data[1] && data[2]) {
915  // if line 1 is too long, it can't be the short text,
916  // so assume the short text is missing and concatenate
917  // line 1 and line 2 to be the long text:
918  int len = strlen(data[1]);
919  if (len > 80) {
920  if (char *NewBuffer = (char *)realloc(data[1], len + 1 + strlen(data[2]) + 1)) {
921  data[1] = NewBuffer;
922  strcat(data[1], "\n");
923  strcat(data[1], data[2]);
924  free(data[2]);
925  data[2] = data[1];
926  data[1] = NULL;
927  }
928  else
929  esyslog("ERROR: out of memory");
930  }
931  }
932  info->SetData(data[0], data[1], data[2]);
933  for (int i = 0; i < 3; i ++)
934  free(data[i]);
935  }
936  else if (errno != ENOENT)
937  LOG_ERROR_STR(*SummaryFileName);
938  }
939 #endif
940  }
941 }
942 
944 {
945  free(titleBuffer);
946  free(sortBufferName);
947  free(sortBufferTime);
948  free(fileName);
949  free(name);
950  delete info;
951 }
952 
953 char *cRecording::StripEpisodeName(char *s, bool Strip)
954 {
955  char *t = s, *s1 = NULL, *s2 = NULL;
956  while (*t) {
957  if (*t == '/') {
958  if (s1) {
959  if (s2)
960  s1 = s2;
961  s2 = t;
962  }
963  else
964  s1 = t;
965  }
966  t++;
967  }
968  if (s1 && s2) {
969  // To have folders sorted before plain recordings, the '/' s1 points to
970  // is replaced by the character '1'. All other slashes will be replaced
971  // by '0' in SortName() (see below), which will result in the desired
972  // sequence ('0' and '1' are reversed in case of rsdDescending):
973  *s1 = (Setup.RecSortingDirection == rsdAscending) ? '1' : '0';
974  if (Strip) {
975  s1++;
976  memmove(s1, s2, t - s2 + 1);
977  }
978  }
979  return s;
980 }
981 
982 char *cRecording::SortName(void) const
983 {
985  if (!*sb) {
987  char buf[32];
988  struct tm tm_r;
989  strftime(buf, sizeof(buf), "%Y%m%d%H%I", localtime_r(&start, &tm_r));
990  *sb = strdup(buf);
991  }
992  else {
993  char *s = strdup(FileName() + strlen(cVideoDirectory::Name()));
996  strreplace(s, '/', (Setup.RecSortingDirection == rsdAscending) ? '0' : '1'); // some locales ignore '/' when sorting
997  int l = strxfrm(NULL, s, 0) + 1;
998  *sb = MALLOC(char, l);
999  strxfrm(*sb, s, l);
1000  free(s);
1001  }
1002  }
1003  return *sb;
1004 }
1005 
1007 {
1008  free(sortBufferName);
1009  free(sortBufferTime);
1010  sortBufferName = sortBufferTime = NULL;
1011 }
1012 
1013 void cRecording::SetId(int Id)
1014 {
1015  id = Id;
1016 }
1017 
1018 int cRecording::GetResume(void) const
1019 {
1020  if (resume == RESUME_NOT_INITIALIZED) {
1021  cResumeFile ResumeFile(FileName(), isPesRecording);
1022  resume = ResumeFile.Read();
1023  }
1024  return resume;
1025 }
1026 
1027 int cRecording::Compare(const cListObject &ListObject) const
1028 {
1029  cRecording *r = (cRecording *)&ListObject;
1031  return strcmp(SortName(), r->SortName());
1032  else
1033  return strcmp(r->SortName(), SortName());
1034 }
1035 
1036 bool cRecording::IsInPath(const char *Path) const
1037 {
1038  if (isempty(Path))
1039  return true;
1040  int l = strlen(Path);
1041  return strncmp(Path, name, l) == 0 && (name[l] == FOLDERDELIMCHAR);
1042 }
1043 
1045 {
1046  if (char *s = strrchr(name, FOLDERDELIMCHAR))
1047  return cString(name, s);
1048  return "";
1049 }
1050 
1052 {
1053  if (char *s = strrchr(name, FOLDERDELIMCHAR))
1054  return cString(s + 1);
1055  return name;
1056 }
1057 
1058 const char *cRecording::FileName(void) const
1059 {
1060  if (!fileName) {
1061  struct tm tm_r;
1062  struct tm *t = localtime_r(&start, &tm_r);
1063  const char *fmt = isPesRecording ? NAMEFORMATPES : NAMEFORMATTS;
1064  int ch = isPesRecording ? priority : channel;
1065  int ri = isPesRecording ? lifetime : instanceId;
1066  char *Name = LimitNameLengths(strdup(name), DirectoryPathMax - strlen(cVideoDirectory::Name()) - 1 - 42, DirectoryNameMax); // 42 = length of an actual recording directory name (generated with DATAFORMATTS) plus some reserve
1067  if (strcmp(Name, name) != 0)
1068  dsyslog("recording file name '%s' truncated to '%s'", name, Name);
1069  Name = ExchangeChars(Name, true);
1070  fileName = strdup(cString::sprintf(fmt, cVideoDirectory::Name(), Name, t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min, ch, ri));
1071  free(Name);
1072  }
1073  return fileName;
1074 }
1075 
1076 const char *cRecording::Title(char Delimiter, bool NewIndicator, int Level) const
1077 {
1078  char New = NewIndicator && IsNew() ? '*' : ' ';
1079  free(titleBuffer);
1080  titleBuffer = NULL;
1081  if (Level < 0 || Level == HierarchyLevels()) {
1082  struct tm tm_r;
1083  struct tm *t = localtime_r(&start, &tm_r);
1084  char *s;
1085  if (Level > 0 && (s = strrchr(name, FOLDERDELIMCHAR)) != NULL)
1086  s++;
1087  else
1088  s = name;
1089  cString Length("");
1090  if (NewIndicator) {
1091  int Minutes = max(0, (LengthInSeconds() + 30) / 60);
1092  Length = cString::sprintf("%c%d:%02d",
1093  Delimiter,
1094  Minutes / 60,
1095  Minutes % 60
1096  );
1097  }
1098  titleBuffer = strdup(cString::sprintf("%02d.%02d.%02d%c%02d:%02d%s%c%c%s",
1099  t->tm_mday,
1100  t->tm_mon + 1,
1101  t->tm_year % 100,
1102  Delimiter,
1103  t->tm_hour,
1104  t->tm_min,
1105  *Length,
1106  New,
1107  Delimiter,
1108  s));
1109  // let's not display a trailing FOLDERDELIMCHAR:
1110  if (!NewIndicator)
1112  s = &titleBuffer[strlen(titleBuffer) - 1];
1113  if (*s == FOLDERDELIMCHAR)
1114  *s = 0;
1115  }
1116  else if (Level < HierarchyLevels()) {
1117  const char *s = name;
1118  const char *p = s;
1119  while (*++s) {
1120  if (*s == FOLDERDELIMCHAR) {
1121  if (Level--)
1122  p = s + 1;
1123  else
1124  break;
1125  }
1126  }
1127  titleBuffer = MALLOC(char, s - p + 3);
1128  *titleBuffer = Delimiter;
1129  *(titleBuffer + 1) = Delimiter;
1130  strn0cpy(titleBuffer + 2, p, s - p + 1);
1131  }
1132  else
1133  return "";
1134  return titleBuffer;
1135 }
1136 
1137 const char *cRecording::PrefixFileName(char Prefix)
1138 {
1140  if (*p) {
1141  free(fileName);
1142  fileName = strdup(p);
1143  return fileName;
1144  }
1145  return NULL;
1146 }
1147 
1149 {
1150  const char *s = name;
1151  int level = 0;
1152  while (*++s) {
1153  if (*s == FOLDERDELIMCHAR)
1154  level++;
1155  }
1156  return level;
1157 }
1158 
1159 bool cRecording::IsEdited(void) const
1160 {
1161  const char *s = strrchr(name, FOLDERDELIMCHAR);
1162  s = !s ? name : s + 1;
1163  return *s == '%';
1164 }
1165 
1167 {
1171 }
1172 
1173 bool cRecording::HasMarks(void) const
1174 {
1175  return access(cMarks::MarksFileName(this), F_OK) == 0;
1176 }
1177 
1179 {
1180  return cMarks::DeleteMarksFile(this);
1181 }
1182 
1184 {
1185  info->Read();
1186  priority = info->priority;
1187  lifetime = info->lifetime;
1189 }
1190 
1191 bool cRecording::WriteInfo(const char *OtherFileName)
1192 {
1193  cString InfoFileName = cString::sprintf("%s%s", OtherFileName ? OtherFileName : FileName(), isPesRecording ? INFOFILESUFFIX ".vdr" : INFOFILESUFFIX);
1194  cSafeFile f(InfoFileName);
1195  if (f.Open()) {
1196  info->Write(f);
1197  f.Close();
1198  }
1199  else
1200  LOG_ERROR_STR(*InfoFileName);
1201  return true;
1202 }
1203 
1204 void cRecording::SetStartTime(time_t Start)
1205 {
1206  start = Start;
1207  free(fileName);
1208  fileName = NULL;
1209 }
1210 
1211 bool cRecording::ChangePriorityLifetime(int NewPriority, int NewLifetime)
1212 {
1213  if (NewPriority != Priority() || NewLifetime != Lifetime()) {
1214  dsyslog("changing priority/lifetime of '%s' to %d/%d", Name(), NewPriority, NewLifetime);
1215  if (IsPesRecording()) {
1216  cString OldFileName = FileName();
1217  priority = NewPriority;
1218  lifetime = NewLifetime;
1219  free(fileName);
1220  fileName = NULL;
1221  cString NewFileName = FileName();
1222  if (!cVideoDirectory::RenameVideoFile(OldFileName, NewFileName))
1223  return false;
1224  info->SetFileName(NewFileName);
1225  }
1226  else {
1227  priority = info->priority = NewPriority;
1228  lifetime = info->lifetime = NewLifetime;
1229  if (!WriteInfo())
1230  return false;
1231  }
1232  }
1233  return true;
1234 }
1235 
1236 bool cRecording::ChangeName(const char *NewName)
1237 {
1238  if (strcmp(NewName, Name())) {
1239  dsyslog("changing name of '%s' to '%s'", Name(), NewName);
1240  cString OldName = Name();
1241  cString OldFileName = FileName();
1242  free(fileName);
1243  fileName = NULL;
1244  free(name);
1245  name = strdup(NewName);
1246  cString NewFileName = FileName();
1247  bool Exists = access(NewFileName, F_OK) == 0;
1248  if (Exists)
1249  esyslog("ERROR: recording '%s' already exists", NewName);
1250  if (Exists || !(MakeDirs(NewFileName, true) && cVideoDirectory::MoveVideoFile(OldFileName, NewFileName))) {
1251  free(name);
1252  name = strdup(OldName);
1253  free(fileName);
1254  fileName = strdup(OldFileName);
1255  return false;
1256  }
1257  isOnVideoDirectoryFileSystem = -1; // it might have been moved to a different file system
1258  ClearSortName();
1259  }
1260  return true;
1261 }
1262 
1264 {
1265  bool result = true;
1266  char *NewName = strdup(FileName());
1267  char *ext = strrchr(NewName, '.');
1268  if (ext && strcmp(ext, RECEXT) == 0) {
1269  strncpy(ext, DELEXT, strlen(ext));
1270  if (access(NewName, F_OK) == 0) {
1271  // the new name already exists, so let's remove that one first:
1272  isyslog("removing recording '%s'", NewName);
1274  }
1275  isyslog("deleting recording '%s'", FileName());
1276  if (access(FileName(), F_OK) == 0) {
1277  result = cVideoDirectory::RenameVideoFile(FileName(), NewName);
1279  }
1280  else {
1281  isyslog("recording '%s' vanished", FileName());
1282  result = true; // well, we were going to delete it, anyway
1283  }
1284  }
1285  free(NewName);
1286  return result;
1287 }
1288 
1290 {
1291  // let's do a final safety check here:
1292  if (!endswith(FileName(), DELEXT)) {
1293  esyslog("attempt to remove recording %s", FileName());
1294  return false;
1295  }
1296  isyslog("removing recording %s", FileName());
1298 }
1299 
1301 {
1302  bool result = true;
1303  char *NewName = strdup(FileName());
1304  char *ext = strrchr(NewName, '.');
1305  if (ext && strcmp(ext, DELEXT) == 0) {
1306  strncpy(ext, RECEXT, strlen(ext));
1307  if (access(NewName, F_OK) == 0) {
1308  // the new name already exists, so let's not remove that one:
1309  esyslog("ERROR: attempt to undelete '%s', while recording '%s' exists", FileName(), NewName);
1310  result = false;
1311  }
1312  else {
1313  isyslog("undeleting recording '%s'", FileName());
1314  if (access(FileName(), F_OK) == 0)
1315  result = cVideoDirectory::RenameVideoFile(FileName(), NewName);
1316  else {
1317  isyslog("deleted recording '%s' vanished", FileName());
1318  result = false;
1319  }
1320  }
1321  }
1322  free(NewName);
1323  return result;
1324 }
1325 
1326 int cRecording::IsInUse(void) const
1327 {
1328  int Use = ruNone;
1330  Use |= ruTimer;
1332  Use |= ruReplay;
1334  return Use;
1335 }
1336 
1337 void cRecording::ResetResume(void) const
1338 {
1340 }
1341 
1342 int cRecording::NumFrames(void) const
1343 {
1344  if (numFrames < 0) {
1347  return nf; // check again later for ongoing recordings
1348  numFrames = nf;
1349  }
1350  return numFrames;
1351 }
1352 
1354 {
1355  int nf = NumFrames();
1356  if (nf >= 0)
1357  return int(nf / FramesPerSecond());
1358  return -1;
1359 }
1360 
1361 int cRecording::FileSizeMB(void) const
1362 {
1363  if (fileSizeMB < 0) {
1364  int fs = DirSizeMB(FileName());
1366  return fs; // check again later for ongoing recordings
1367  fileSizeMB = fs;
1368  }
1369  return fileSizeMB;
1370 }
1371 
1372 // --- cVideoDirectoryScannerThread ------------------------------------------
1373 
1375 private:
1378  int count;
1379  bool initial;
1380  void ScanVideoDir(const char *DirName, int LinkLevel = 0, int DirLevel = 0);
1381 protected:
1382  virtual void Action(void);
1383 public:
1384  cVideoDirectoryScannerThread(cRecordings *Recordings, cRecordings *DeletedRecordings);
1386  };
1387 
1389 :cThread("video directory scanner", true)
1390 {
1391  recordings = Recordings;
1392  deletedRecordings = DeletedRecordings;
1393  count = 0;
1394  initial = true;
1395 }
1396 
1398 {
1399  Cancel(3);
1400 }
1401 
1403 {
1404  cStateKey StateKey;
1405  recordings->Lock(StateKey);
1406  count = recordings->Count();
1407  initial = count == 0; // no name checking if the list is initially empty
1408  StateKey.Remove();
1409  deletedRecordings->Lock(StateKey, true);
1411  StateKey.Remove();
1413 }
1414 
1415 void cVideoDirectoryScannerThread::ScanVideoDir(const char *DirName, int LinkLevel, int DirLevel)
1416 {
1417  // Find any new recordings:
1418  cReadDir d(DirName);
1419  struct dirent *e;
1420  while (Running() && (e = d.Next()) != NULL) {
1421  if (cIoThrottle::Engaged())
1422  cCondWait::SleepMs(100);
1423  cString buffer = AddDirectory(DirName, e->d_name);
1424  struct stat st;
1425  if (lstat(buffer, &st) == 0) {
1426  int Link = 0;
1427  if (S_ISLNK(st.st_mode)) {
1428  if (LinkLevel > MAX_LINK_LEVEL) {
1429  isyslog("max link level exceeded - not scanning %s", *buffer);
1430  continue;
1431  }
1432  Link = 1;
1433  if (stat(buffer, &st) != 0)
1434  continue;
1435  }
1436  if (S_ISDIR(st.st_mode)) {
1437  cRecordings *Recordings = NULL;
1438  if (endswith(buffer, RECEXT))
1439  Recordings = recordings;
1440  else if (endswith(buffer, DELEXT))
1441  Recordings = deletedRecordings;
1442  if (Recordings) {
1443  cStateKey StateKey;
1444  Recordings->Lock(StateKey, true);
1445  if (initial && count != recordings->Count()) {
1446  dsyslog("activated name checking for initial read of video directory");
1447  initial = false;
1448  }
1449  if (Recordings == deletedRecordings || initial || !Recordings->GetByName(buffer)) {
1450  cRecording *r = new cRecording(buffer);
1451  if (r->Name()) {
1452  r->NumFrames(); // initializes the numFrames member
1453  r->FileSizeMB(); // initializes the fileSizeMB member
1454  r->IsOnVideoDirectoryFileSystem(); // initializes the isOnVideoDirectoryFileSystem member
1455  if (Recordings == deletedRecordings)
1456  r->SetDeleted();
1457  Recordings->Add(r);
1458  count = recordings->Count();
1459  }
1460  else
1461  delete r;
1462  }
1463  StateKey.Remove();
1464  }
1465  else
1466  ScanVideoDir(buffer, LinkLevel + Link, DirLevel + 1);
1467  }
1468  }
1469  }
1470  // Handle any vanished recordings:
1471  if (!initial && DirLevel == 0) {
1472  cStateKey StateKey;
1473  recordings->Lock(StateKey, true);
1474  for (cRecording *Recording = recordings->First(); Recording; ) {
1475  cRecording *r = Recording;
1476  Recording = recordings->Next(Recording);
1477  if (access(r->FileName(), F_OK) != 0)
1478  recordings->Del(r);
1479  }
1480  StateKey.Remove();
1481  }
1482 }
1483 
1484 // --- cRecordings -----------------------------------------------------------
1485 
1489 char *cRecordings::updateFileName = NULL;
1491 time_t cRecordings::lastUpdate = 0;
1492 
1494 :cList<cRecording>(Deleted ? "4 DelRecs" : "3 Recordings")
1495 {
1496 }
1497 
1499 {
1500  // The first one to be destructed deletes it:
1503 }
1504 
1506 {
1507  if (!updateFileName)
1508  updateFileName = strdup(AddDirectory(cVideoDirectory::Name(), ".update"));
1509  return updateFileName;
1510 }
1511 
1513 {
1514  bool needsUpdate = NeedsUpdate();
1516  if (!needsUpdate)
1517  lastUpdate = time(NULL); // make sure we don't trigger ourselves
1518 }
1519 
1521 {
1522  time_t lastModified = LastModifiedTime(UpdateFileName());
1523  if (lastModified > time(NULL))
1524  return false; // somebody's clock isn't running correctly
1525  return lastUpdate < lastModified;
1526 }
1527 
1528 void cRecordings::Update(bool Wait)
1529 {
1532  lastUpdate = time(NULL); // doing this first to make sure we don't miss anything
1534  if (Wait) {
1536  cCondWait::SleepMs(100);
1537  }
1538 }
1539 
1540 const cRecording *cRecordings::GetById(int Id) const
1541 {
1542  for (const cRecording *Recording = First(); Recording; Recording = Next(Recording)) {
1543  if (Recording->Id() == Id)
1544  return Recording;
1545  }
1546  return NULL;
1547 }
1548 
1549 const cRecording *cRecordings::GetByName(const char *FileName) const
1550 {
1551  if (FileName) {
1552  for (const cRecording *Recording = First(); Recording; Recording = Next(Recording)) {
1553  if (strcmp(Recording->FileName(), FileName) == 0)
1554  return Recording;
1555  }
1556  }
1557  return NULL;
1558 }
1559 
1561 {
1562  Recording->SetId(++lastRecordingId);
1563  cList<cRecording>::Add(Recording);
1564 }
1565 
1566 void cRecordings::AddByName(const char *FileName, bool TriggerUpdate)
1567 {
1568  if (!GetByName(FileName)) {
1569  Add(new cRecording(FileName));
1570  if (TriggerUpdate)
1571  TouchUpdate();
1572  }
1573 }
1574 
1575 void cRecordings::DelByName(const char *FileName)
1576 {
1577  cRecording *Recording = GetByName(FileName);
1578  cRecording *dummy = NULL;
1579  if (!Recording)
1580  Recording = dummy = new cRecording(FileName); // allows us to use a FileName that is not in the Recordings list
1582  if (!dummy)
1583  Del(Recording, false);
1584  char *ext = strrchr(Recording->fileName, '.');
1585  if (ext) {
1586  strncpy(ext, DELEXT, strlen(ext));
1587  if (access(Recording->FileName(), F_OK) == 0) {
1588  Recording->SetDeleted();
1589  DeletedRecordings->Add(Recording);
1590  Recording = NULL; // to prevent it from being deleted below
1591  }
1592  }
1593  delete Recording;
1594  TouchUpdate();
1595 }
1596 
1597 void cRecordings::UpdateByName(const char *FileName)
1598 {
1599  if (cRecording *Recording = GetByName(FileName))
1600  Recording->ReadInfo();
1601 }
1602 
1604 {
1605  int size = 0;
1606  for (const cRecording *Recording = First(); Recording; Recording = Next(Recording)) {
1607  int FileSizeMB = Recording->FileSizeMB();
1608  if (FileSizeMB > 0 && Recording->IsOnVideoDirectoryFileSystem())
1609  size += FileSizeMB;
1610  }
1611  return size;
1612 }
1613 
1614 double cRecordings::MBperMinute(void) const
1615 {
1616  int size = 0;
1617  int length = 0;
1618  for (const cRecording *Recording = First(); Recording; Recording = Next(Recording)) {
1619  if (Recording->IsOnVideoDirectoryFileSystem()) {
1620  int FileSizeMB = Recording->FileSizeMB();
1621  if (FileSizeMB > 0) {
1622  int LengthInSeconds = Recording->LengthInSeconds();
1623  if (LengthInSeconds > 0) {
1624  if (LengthInSeconds / FileSizeMB < LIMIT_SECS_PER_MB_RADIO) { // don't count radio recordings
1625  size += FileSizeMB;
1626  length += LengthInSeconds;
1627  }
1628  }
1629  }
1630  }
1631  }
1632  return (size && length) ? double(size) * 60 / length : -1;
1633 }
1634 
1635 int cRecordings::PathIsInUse(const char *Path) const
1636 {
1637  int Use = ruNone;
1638  for (const cRecording *Recording = First(); Recording; Recording = Next(Recording)) {
1639  if (Recording->IsInPath(Path))
1640  Use |= Recording->IsInUse();
1641  }
1642  return Use;
1643 }
1644 
1645 int cRecordings::GetNumRecordingsInPath(const char *Path) const
1646 {
1647  int n = 0;
1648  for (const cRecording *Recording = First(); Recording; Recording = Next(Recording)) {
1649  if (Recording->IsInPath(Path))
1650  n++;
1651  }
1652  return n;
1653 }
1654 
1655 bool cRecordings::MoveRecordings(const char *OldPath, const char *NewPath)
1656 {
1657  if (OldPath && NewPath && strcmp(OldPath, NewPath)) {
1658  dsyslog("moving '%s' to '%s'", OldPath, NewPath);
1659  bool Moved = false;
1660  for (cRecording *Recording = First(); Recording; Recording = Next(Recording)) {
1661  if (Recording->IsInPath(OldPath)) {
1662  const char *p = Recording->Name() + strlen(OldPath);
1663  cString NewName = cString::sprintf("%s%s", NewPath, p);
1664  if (!Recording->ChangeName(NewName))
1665  return false;
1666  Moved = true;
1667  }
1668  }
1669  if (Moved)
1670  TouchUpdate();
1671  }
1672  return true;
1673 }
1674 
1675 void cRecordings::ResetResume(const char *ResumeFileName)
1676 {
1677  for (cRecording *Recording = First(); Recording; Recording = Next(Recording)) {
1678  if (!ResumeFileName || strncmp(ResumeFileName, Recording->FileName(), strlen(Recording->FileName())) == 0)
1679  Recording->ResetResume();
1680  }
1681 }
1682 
1684 {
1685  for (cRecording *Recording = First(); Recording; Recording = Next(Recording))
1686  Recording->ClearSortName();
1687 }
1688 
1689 // --- cDirCopier ------------------------------------------------------------
1690 
1691 class cDirCopier : public cThread {
1692 private:
1695  bool error;
1697  bool Throttled(void);
1698  virtual void Action(void);
1699 public:
1700  cDirCopier(const char *DirNameSrc, const char *DirNameDst);
1701  virtual ~cDirCopier();
1702  bool Error(void) { return error; }
1703  };
1704 
1705 cDirCopier::cDirCopier(const char *DirNameSrc, const char *DirNameDst)
1706 :cThread("file copier", true)
1707 {
1708  dirNameSrc = DirNameSrc;
1709  dirNameDst = DirNameDst;
1710  error = true; // prepare for the worst!
1711  suspensionLogged = false;
1712 }
1713 
1715 {
1716  Cancel(3);
1717 }
1718 
1720 {
1721  if (cIoThrottle::Engaged()) {
1722  if (!suspensionLogged) {
1723  dsyslog("suspending copy thread");
1724  suspensionLogged = true;
1725  }
1726  return true;
1727  }
1728  else if (suspensionLogged) {
1729  dsyslog("resuming copy thread");
1730  suspensionLogged = false;
1731  }
1732  return false;
1733 }
1734 
1736 {
1737  if (DirectoryOk(dirNameDst, true)) {
1738  cReadDir d(dirNameSrc);
1739  if (d.Ok()) {
1740  dsyslog("copying directory '%s' to '%s'", *dirNameSrc, *dirNameDst);
1741  dirent *e = NULL;
1742  cString FileNameSrc;
1743  cString FileNameDst;
1744  int From = -1;
1745  int To = -1;
1746  size_t BufferSize = BUFSIZ;
1747  uchar *Buffer = NULL;
1748  while (Running()) {
1749  // Suspend copying if we have severe throughput problems:
1750  if (Throttled()) {
1751  cCondWait::SleepMs(100);
1752  continue;
1753  }
1754  // Copy all files in the source directory to the destination directory:
1755  if (e) {
1756  // We're currently copying a file:
1757  if (!Buffer) {
1758  esyslog("ERROR: no buffer");
1759  break;
1760  }
1761  size_t Read = safe_read(From, Buffer, BufferSize);
1762  if (Read > 0) {
1763  size_t Written = safe_write(To, Buffer, Read);
1764  if (Written != Read) {
1765  esyslog("ERROR: can't write to destination file '%s': %m", *FileNameDst);
1766  break;
1767  }
1768  }
1769  else if (Read == 0) { // EOF on From
1770  e = NULL; // triggers switch to next entry
1771  if (fsync(To) < 0) {
1772  esyslog("ERROR: can't sync destination file '%s': %m", *FileNameDst);
1773  break;
1774  }
1775  if (close(From) < 0) {
1776  esyslog("ERROR: can't close source file '%s': %m", *FileNameSrc);
1777  break;
1778  }
1779  if (close(To) < 0) {
1780  esyslog("ERROR: can't close destination file '%s': %m", *FileNameDst);
1781  break;
1782  }
1783  // Plausibility check:
1784  off_t FileSizeSrc = FileSize(FileNameSrc);
1785  off_t FileSizeDst = FileSize(FileNameDst);
1786  if (FileSizeSrc != FileSizeDst) {
1787  esyslog("ERROR: file size discrepancy: %" PRId64 " != %" PRId64, FileSizeSrc, FileSizeDst);
1788  break;
1789  }
1790  }
1791  else {
1792  esyslog("ERROR: can't read from source file '%s': %m", *FileNameSrc);
1793  break;
1794  }
1795  }
1796  else if ((e = d.Next()) != NULL) {
1797  // We're switching to the next directory entry:
1798  FileNameSrc = AddDirectory(dirNameSrc, e->d_name);
1799  FileNameDst = AddDirectory(dirNameDst, e->d_name);
1800  struct stat st;
1801  if (stat(FileNameSrc, &st) < 0) {
1802  esyslog("ERROR: can't access source file '%s': %m", *FileNameSrc);
1803  break;
1804  }
1805  if (!(S_ISREG(st.st_mode) || S_ISLNK(st.st_mode))) {
1806  esyslog("ERROR: source file '%s' is neither a regular file nor a symbolic link", *FileNameSrc);
1807  break;
1808  }
1809  dsyslog("copying file '%s' to '%s'", *FileNameSrc, *FileNameDst);
1810  if (!Buffer) {
1811  BufferSize = max(size_t(st.st_blksize * 10), size_t(BUFSIZ));
1812  Buffer = MALLOC(uchar, BufferSize);
1813  if (!Buffer) {
1814  esyslog("ERROR: out of memory");
1815  break;
1816  }
1817  }
1818  if (access(FileNameDst, F_OK) == 0) {
1819  esyslog("ERROR: destination file '%s' already exists", *FileNameDst);
1820  break;
1821  }
1822  if ((From = open(FileNameSrc, O_RDONLY)) < 0) {
1823  esyslog("ERROR: can't open source file '%s': %m", *FileNameSrc);
1824  break;
1825  }
1826  if ((To = open(FileNameDst, O_WRONLY | O_CREAT | O_EXCL, DEFFILEMODE)) < 0) {
1827  esyslog("ERROR: can't open destination file '%s': %m", *FileNameDst);
1828  close(From);
1829  break;
1830  }
1831  }
1832  else {
1833  // We're done:
1834  free(Buffer);
1835  dsyslog("done copying directory '%s' to '%s'", *dirNameSrc, *dirNameDst);
1836  error = false;
1837  return;
1838  }
1839  }
1840  free(Buffer);
1841  close(From); // just to be absolutely sure
1842  close(To);
1843  isyslog("copying directory '%s' to '%s' ended prematurely", *dirNameSrc, *dirNameDst);
1844  }
1845  else
1846  esyslog("ERROR: can't open '%s'", *dirNameSrc);
1847  }
1848  else
1849  esyslog("ERROR: can't access '%s'", *dirNameDst);
1850 }
1851 
1852 // --- cRecordingsHandlerEntry -----------------------------------------------
1853 
1855 private:
1856  int usage;
1861  bool error;
1862  void ClearPending(void) { usage &= ~ruPending; }
1863 public:
1864  cRecordingsHandlerEntry(int Usage, const char *FileNameSrc, const char *FileNameDst);
1866  int Usage(const char *FileName = NULL) const;
1867  bool Error(void) const { return error; }
1868  void SetCanceled(void) { usage |= ruCanceled; }
1869  const char *FileNameSrc(void) const { return fileNameSrc; }
1870  const char *FileNameDst(void) const { return fileNameDst; }
1871  bool Active(cRecordings *Recordings);
1872  void Cleanup(cRecordings *Recordings);
1873  };
1874 
1875 cRecordingsHandlerEntry::cRecordingsHandlerEntry(int Usage, const char *FileNameSrc, const char *FileNameDst)
1876 {
1877  usage = Usage;
1880  cutter = NULL;
1881  copier = NULL;
1882  error = false;
1883 }
1884 
1886 {
1887  delete cutter;
1888  delete copier;
1889 }
1890 
1891 int cRecordingsHandlerEntry::Usage(const char *FileName) const
1892 {
1893  int u = usage;
1894  if (FileName && *FileName) {
1895  if (strcmp(FileName, fileNameSrc) == 0)
1896  u |= ruSrc;
1897  else if (strcmp(FileName, fileNameDst) == 0)
1898  u |= ruDst;
1899  }
1900  return u;
1901 }
1902 
1904 {
1905  if ((usage & ruCanceled) != 0)
1906  return false;
1907  // First test whether there is an ongoing operation:
1908  if (cutter) {
1909  if (cutter->Active())
1910  return true;
1911  error = cutter->Error();
1912  delete cutter;
1913  cutter = NULL;
1914  }
1915  else if (copier) {
1916  if (copier->Active())
1917  return true;
1918  error = copier->Error();
1919  delete copier;
1920  copier = NULL;
1921  }
1922  // Now check if there is something to start:
1923  if ((Usage() & ruPending) != 0) {
1924  if ((Usage() & ruCut) != 0) {
1925  cutter = new cCutter(FileNameSrc());
1926  cutter->Start();
1927  Recordings->AddByName(FileNameDst(), false);
1928  }
1929  else if ((Usage() & (ruMove | ruCopy)) != 0) {
1931  copier->Start();
1932  }
1933  ClearPending();
1934  Recordings->SetModified(); // to trigger a state change
1935  return true;
1936  }
1937  // We're done:
1938  if (!error && (usage & ruMove) != 0) {
1939  cRecording Recording(FileNameSrc());
1940  if (Recording.Delete())
1941  Recordings->DelByName(Recording.FileName());
1942  }
1943  Recordings->SetModified(); // to trigger a state change
1944  Recordings->TouchUpdate();
1945  return false;
1946 }
1947 
1949 {
1950  if ((usage & ruCut)) { // this was a cut operation...
1951  if (cutter) { // ...which had not yet ended
1952  delete cutter;
1953  cutter = NULL;
1955  Recordings->DelByName(fileNameDst);
1956  }
1957  }
1958  if ((usage & (ruMove | ruCopy)) // this was a move/copy operation...
1959  && ((usage & ruPending) // ...which had not yet started...
1960  || copier // ...or not yet finished...
1961  || error)) { // ...or finished with error
1962  if (copier) {
1963  delete copier;
1964  copier = NULL;
1965  }
1967  if ((usage & ruMove) != 0)
1968  Recordings->AddByName(fileNameSrc);
1969  Recordings->DelByName(fileNameDst);
1970  }
1971 }
1972 
1973 // --- cRecordingsHandler ----------------------------------------------------
1974 
1976 
1978 :cThread("recordings handler")
1979 {
1980  finished = true;
1981  error = false;
1982 }
1983 
1985 {
1986  Cancel(3);
1987 }
1988 
1990 {
1991  while (Running()) {
1992  bool Sleep = false;
1993  {
1995  Recordings->SetExplicitModify();
1996  cMutexLock MutexLock(&mutex);
1998  if (!r->Active(Recordings)) {
1999  error |= r->Error();
2000  r->Cleanup(Recordings);
2001  operations.Del(r);
2002  }
2003  else
2004  Sleep = true;
2005  }
2006  else
2007  break;
2008  }
2009  if (Sleep)
2010  cCondWait::SleepMs(100);
2011  }
2012 }
2013 
2015 {
2016  if (FileName && *FileName) {
2017  for (cRecordingsHandlerEntry *r = operations.First(); r; r = operations.Next(r)) {
2018  if ((r->Usage() & ruCanceled) != 0)
2019  continue;
2020  if (strcmp(FileName, r->FileNameSrc()) == 0 || strcmp(FileName, r->FileNameDst()) == 0)
2021  return r;
2022  }
2023  }
2024  return NULL;
2025 }
2026 
2027 bool cRecordingsHandler::Add(int Usage, const char *FileNameSrc, const char *FileNameDst)
2028 {
2029  dsyslog("recordings handler add %d '%s' '%s'", Usage, FileNameSrc, FileNameDst);
2030  cMutexLock MutexLock(&mutex);
2031  if (Usage == ruCut || Usage == ruMove || Usage == ruCopy) {
2032  if (FileNameSrc && *FileNameSrc) {
2033  if (Usage == ruCut || FileNameDst && *FileNameDst) {
2034  cString fnd;
2035  if (Usage == ruCut && !FileNameDst)
2036  FileNameDst = fnd = cCutter::EditedFileName(FileNameSrc);
2037  if (!Get(FileNameSrc) && !Get(FileNameDst)) {
2038  Usage |= ruPending;
2039  operations.Add(new cRecordingsHandlerEntry(Usage, FileNameSrc, FileNameDst));
2040  finished = false;
2041  Start();
2042  return true;
2043  }
2044  else
2045  esyslog("ERROR: file name already present in recordings handler add %d '%s' '%s'", Usage, FileNameSrc, FileNameDst);
2046  }
2047  else
2048  esyslog("ERROR: missing dst file name in recordings handler add %d '%s' '%s'", Usage, FileNameSrc, FileNameDst);
2049  }
2050  else
2051  esyslog("ERROR: missing src file name in recordings handler add %d '%s' '%s'", Usage, FileNameSrc, FileNameDst);
2052  }
2053  else
2054  esyslog("ERROR: invalid usage in recordings handler add %d '%s' '%s'", Usage, FileNameSrc, FileNameDst);
2055  return false;
2056 }
2057 
2058 void cRecordingsHandler::Del(const char *FileName)
2059 {
2060  cMutexLock MutexLock(&mutex);
2061  if (cRecordingsHandlerEntry *r = Get(FileName))
2062  r->SetCanceled();
2063 }
2064 
2066 {
2067  cMutexLock MutexLock(&mutex);
2068  for (cRecordingsHandlerEntry *r = operations.First(); r; r = operations.Next(r))
2069  r->SetCanceled();
2070 }
2071 
2072 int cRecordingsHandler::GetUsage(const char *FileName)
2073 {
2074  cMutexLock MutexLock(&mutex);
2075  if (cRecordingsHandlerEntry *r = Get(FileName))
2076  return r->Usage(FileName);
2077  return ruNone;
2078 }
2079 
2081 {
2082  cMutexLock MutexLock(&mutex);
2083  if (!finished && operations.Count() == 0) {
2084  finished = true;
2085  Error = error;
2086  error = false;
2087  return true;
2088  }
2089  return false;
2090 }
2091 
2092 // --- cMark -----------------------------------------------------------------
2093 
2096 
2097 cMark::cMark(int Position, const char *Comment, double FramesPerSecond)
2098 {
2099  position = Position;
2100  comment = Comment;
2101  framesPerSecond = FramesPerSecond;
2102 }
2103 
2105 {
2106 }
2107 
2109 {
2110  return cString::sprintf("%s%s%s", *IndexToHMSF(position, true, framesPerSecond), Comment() ? " " : "", Comment() ? Comment() : "");
2111 }
2112 
2113 bool cMark::Parse(const char *s)
2114 {
2115  comment = NULL;
2118  const char *p = strchr(s, ' ');
2119  if (p) {
2120  p = skipspace(p);
2121  if (*p)
2122  comment = strdup(p);
2123  }
2124  return true;
2125 }
2126 
2127 bool cMark::Save(FILE *f)
2128 {
2129  return fprintf(f, "%s\n", *ToText()) > 0;
2130 }
2131 
2132 // --- cMarks ----------------------------------------------------------------
2133 
2135 {
2136  return AddDirectory(Recording->FileName(), Recording->IsPesRecording() ? MARKSFILESUFFIX ".vdr" : MARKSFILESUFFIX);
2137 }
2138 
2139 bool cMarks::DeleteMarksFile(const cRecording *Recording)
2140 {
2141  if (remove(cMarks::MarksFileName(Recording)) < 0) {
2142  if (errno != ENOENT) {
2143  LOG_ERROR_STR(Recording->FileName());
2144  return false;
2145  }
2146  }
2147  return true;
2148 }
2149 
2150 bool cMarks::Load(const char *RecordingFileName, double FramesPerSecond, bool IsPesRecording)
2151 {
2152  recordingFileName = RecordingFileName;
2153  fileName = AddDirectory(RecordingFileName, IsPesRecording ? MARKSFILESUFFIX ".vdr" : MARKSFILESUFFIX);
2154  framesPerSecond = FramesPerSecond;
2155  isPesRecording = IsPesRecording;
2156  nextUpdate = 0;
2157  lastFileTime = -1; // the first call to Load() must take place!
2158  lastChange = 0;
2159  return Update();
2160 }
2161 
2162 bool cMarks::Update(void)
2163 {
2164  time_t t = time(NULL);
2165  if (t > nextUpdate && *fileName) {
2166  time_t LastModified = LastModifiedTime(fileName);
2167  if (LastModified != lastFileTime) // change detected, or first run
2168  lastChange = LastModified > 0 ? LastModified : t;
2169  int d = t - lastChange;
2170  if (d < 60)
2171  d = 1; // check frequently if the file has just been modified
2172  else if (d < 3600)
2173  d = 10; // older files are checked less frequently
2174  else
2175  d /= 360; // phase out checking for very old files
2176  nextUpdate = t + d;
2177  if (LastModified != lastFileTime) { // change detected, or first run
2178  lastFileTime = LastModified;
2179  if (lastFileTime == t)
2180  lastFileTime--; // make sure we don't miss updates in the remaining second
2184  Align();
2185  Sort();
2186  return true;
2187  }
2188  }
2189  }
2190  return false;
2191 }
2192 
2193 bool cMarks::Save(void)
2194 {
2195  if (cConfig<cMark>::Save()) {
2197  return true;
2198  }
2199  return false;
2200 }
2201 
2202 void cMarks::Align(void)
2203 {
2204  cIndexFile IndexFile(recordingFileName, false, isPesRecording);
2205  for (cMark *m = First(); m; m = Next(m)) {
2206  int p = IndexFile.GetClosestIFrame(m->Position());
2207  if (m->Position() - p) {
2208  //isyslog("aligned editing mark %s to %s (off by %d frame%s)", *IndexToHMSF(m->Position(), true, framesPerSecond), *IndexToHMSF(p, true, framesPerSecond), m->Position() - p, abs(m->Position() - p) > 1 ? "s" : "");
2209  m->SetPosition(p);
2210  }
2211  }
2212 }
2213 
2214 void cMarks::Sort(void)
2215 {
2216  for (cMark *m1 = First(); m1; m1 = Next(m1)) {
2217  for (cMark *m2 = Next(m1); m2; m2 = Next(m2)) {
2218  if (m2->Position() < m1->Position()) {
2219  swap(m1->position, m2->position);
2220  swap(m1->comment, m2->comment);
2221  }
2222  }
2223  }
2224 }
2225 
2226 void cMarks::Add(int Position)
2227 {
2228  cConfig<cMark>::Add(new cMark(Position, NULL, framesPerSecond));
2229  Sort();
2230 }
2231 
2232 const cMark *cMarks::Get(int Position) const
2233 {
2234  for (const cMark *mi = First(); mi; mi = Next(mi)) {
2235  if (mi->Position() == Position)
2236  return mi;
2237  }
2238  return NULL;
2239 }
2240 
2241 const cMark *cMarks::GetPrev(int Position) const
2242 {
2243  for (const cMark *mi = Last(); mi; mi = Prev(mi)) {
2244  if (mi->Position() < Position)
2245  return mi;
2246  }
2247  return NULL;
2248 }
2249 
2250 const cMark *cMarks::GetNext(int Position) const
2251 {
2252  for (const cMark *mi = First(); mi; mi = Next(mi)) {
2253  if (mi->Position() > Position)
2254  return mi;
2255  }
2256  return NULL;
2257 }
2258 
2259 const cMark *cMarks::GetNextBegin(const cMark *EndMark) const
2260 {
2261  const cMark *BeginMark = EndMark ? Next(EndMark) : First();
2262  if (BeginMark && EndMark && BeginMark->Position() == EndMark->Position()) {
2263  while (const cMark *NextMark = Next(BeginMark)) {
2264  if (BeginMark->Position() == NextMark->Position()) { // skip Begin/End at the same position
2265  if (!(BeginMark = Next(NextMark)))
2266  break;
2267  }
2268  else
2269  break;
2270  }
2271  }
2272  return BeginMark;
2273 }
2274 
2275 const cMark *cMarks::GetNextEnd(const cMark *BeginMark) const
2276 {
2277  if (!BeginMark)
2278  return NULL;
2279  const cMark *EndMark = Next(BeginMark);
2280  if (EndMark && BeginMark && BeginMark->Position() == EndMark->Position()) {
2281  while (const cMark *NextMark = Next(EndMark)) {
2282  if (EndMark->Position() == NextMark->Position()) { // skip End/Begin at the same position
2283  if (!(EndMark = Next(NextMark)))
2284  break;
2285  }
2286  else
2287  break;
2288  }
2289  }
2290  return EndMark;
2291 }
2292 
2294 {
2295  int NumSequences = 0;
2296  if (const cMark *BeginMark = GetNextBegin()) {
2297  while (const cMark *EndMark = GetNextEnd(BeginMark)) {
2298  NumSequences++;
2299  BeginMark = GetNextBegin(EndMark);
2300  }
2301  if (BeginMark) {
2302  NumSequences++; // the last sequence had no actual "end" mark
2303  if (NumSequences == 1 && BeginMark->Position() == 0)
2304  NumSequences = 0; // there is only one actual "begin" mark at offset zero, and no actual "end" mark
2305  }
2306  }
2307  return NumSequences;
2308 }
2309 
2310 // --- cRecordingUserCommand -------------------------------------------------
2311 
2312 const char *cRecordingUserCommand::command = NULL;
2313 
2314 void cRecordingUserCommand::InvokeCommand(const char *State, const char *RecordingFileName, const char *SourceFileName)
2315 {
2316  if (command) {
2317  cString cmd;
2318  if (SourceFileName)
2319  cmd = cString::sprintf("%s %s \"%s\" \"%s\"", command, State, *strescape(RecordingFileName, "\\\"$"), *strescape(SourceFileName, "\\\"$"));
2320  else
2321  cmd = cString::sprintf("%s %s \"%s\"", command, State, *strescape(RecordingFileName, "\\\"$"));
2322  isyslog("executing '%s'", *cmd);
2323  SystemExec(cmd);
2324  }
2325 }
2326 
2327 // --- cIndexFileGenerator ---------------------------------------------------
2328 
2329 #define IFG_BUFFER_SIZE KILOBYTE(100)
2330 
2332 private:
2334  bool update;
2335 protected:
2336  virtual void Action(void);
2337 public:
2338  cIndexFileGenerator(const char *RecordingName, bool Update = false);
2340  };
2341 
2342 cIndexFileGenerator::cIndexFileGenerator(const char *RecordingName, bool Update)
2343 :cThread("index file generator")
2344 ,recordingName(RecordingName)
2345 {
2346  update = Update;
2347  Start();
2348 }
2349 
2351 {
2352  Cancel(3);
2353 }
2354 
2356 {
2357  bool IndexFileComplete = false;
2358  bool IndexFileWritten = false;
2359  bool Rewind = false;
2360  cFileName FileName(recordingName, false);
2361  cUnbufferedFile *ReplayFile = FileName.Open();
2363  cPatPmtParser PatPmtParser;
2364  cFrameDetector FrameDetector;
2365  cIndexFile IndexFile(recordingName, true, false, false, true);
2366  int BufferChunks = KILOBYTE(1); // no need to read a lot at the beginning when parsing PAT/PMT
2367  off_t FileSize = 0;
2368  off_t FrameOffset = -1;
2369  uint16_t FileNumber = 1;
2370  off_t FileOffset = 0;
2371  int Last = -1;
2372  if (update) {
2373  // Look for current index and position to end of it if present:
2374  bool Independent;
2375  int Length;
2376  Last = IndexFile.Last();
2377  if (Last >= 0 && !IndexFile.Get(Last, &FileNumber, &FileOffset, &Independent, &Length))
2378  Last = -1; // reset Last if an error occurred
2379  if (Last >= 0) {
2380  Rewind = true;
2381  isyslog("updating index file");
2382  }
2383  else
2384  isyslog("generating index file");
2385  }
2386  Skins.QueueMessage(mtInfo, tr("Regenerating index file"));
2387  bool Stuffed = false;
2388  while (Running()) {
2389  // Rewind input file:
2390  if (Rewind) {
2391  ReplayFile = FileName.SetOffset(FileNumber, FileOffset);
2392  FileSize = FileOffset;
2393  Buffer.Clear();
2394  Rewind = false;
2395  }
2396  // Process data:
2397  int Length;
2398  uchar *Data = Buffer.Get(Length);
2399  if (Data) {
2400  if (FrameDetector.Synced()) {
2401  // Step 3 - generate the index:
2402  if (TsPid(Data) == PATPID)
2403  FrameOffset = FileSize; // the PAT/PMT is at the beginning of an I-frame
2404  int Processed = FrameDetector.Analyze(Data, Length);
2405  if (Processed > 0) {
2406  if (FrameDetector.NewFrame()) {
2407  if (IndexFileWritten || Last < 0) // check for first frame and do not write if in update mode
2408  IndexFile.Write(FrameDetector.IndependentFrame(), FileName.Number(), FrameOffset >= 0 ? FrameOffset : FileSize);
2409  FrameOffset = -1;
2410  IndexFileWritten = true;
2411  }
2412  FileSize += Processed;
2413  Buffer.Del(Processed);
2414  }
2415  }
2416  else if (PatPmtParser.Completed()) {
2417  // Step 2 - sync FrameDetector:
2418  int Processed = FrameDetector.Analyze(Data, Length);
2419  if (Processed > 0) {
2420  if (FrameDetector.Synced()) {
2421  // Synced FrameDetector, so rewind for actual processing:
2422  Rewind = true;
2423  }
2424  Buffer.Del(Processed);
2425  }
2426  }
2427  else {
2428  // Step 1 - parse PAT/PMT:
2429  uchar *p = Data;
2430  while (Length >= TS_SIZE) {
2431  int Pid = TsPid(p);
2432  if (Pid == PATPID)
2433  PatPmtParser.ParsePat(p, TS_SIZE);
2434  else if (PatPmtParser.IsPmtPid(Pid))
2435  PatPmtParser.ParsePmt(p, TS_SIZE);
2436  Length -= TS_SIZE;
2437  p += TS_SIZE;
2438  if (PatPmtParser.Completed()) {
2439  // Found pid, so rewind to sync FrameDetector:
2440  FrameDetector.SetPid(PatPmtParser.Vpid() ? PatPmtParser.Vpid() : PatPmtParser.Apid(0), PatPmtParser.Vpid() ? PatPmtParser.Vtype() : PatPmtParser.Atype(0));
2441  BufferChunks = IFG_BUFFER_SIZE;
2442  Rewind = true;
2443  break;
2444  }
2445  }
2446  Buffer.Del(p - Data);
2447  }
2448  }
2449  // Read data:
2450  else if (ReplayFile) {
2451  int Result = Buffer.Read(ReplayFile, BufferChunks);
2452  if (Result == 0) { // EOF
2453  if (Buffer.Available() > 0 && !Stuffed) {
2454  // So the last call to Buffer.Get() returned NULL, but there is still
2455  // data in the buffer, and we're at the end of the current TS file.
2456  // The remaining data in the buffer is less than what's needed for the
2457  // frame detector to analyze frames, so we need to put some stuffing
2458  // packets into the buffer to flush out the rest of the data (otherwise
2459  // any frames within the remaining data would not be seen here):
2460  uchar StuffingPacket[TS_SIZE] = { TS_SYNC_BYTE, 0xFF };
2461  for (int i = 0; i <= MIN_TS_PACKETS_FOR_FRAME_DETECTOR; i++)
2462  Buffer.Put(StuffingPacket, sizeof(StuffingPacket));
2463  Stuffed = true;
2464  }
2465  else {
2466  ReplayFile = FileName.NextFile();
2467  FileSize = 0;
2468  FrameOffset = -1;
2469  Buffer.Clear();
2470  Stuffed = false;
2471  }
2472  }
2473  }
2474  // Recording has been processed:
2475  else {
2476  IndexFileComplete = true;
2477  break;
2478  }
2479  }
2480  if (IndexFileComplete) {
2481  if (IndexFileWritten) {
2482  cRecordingInfo RecordingInfo(recordingName);
2483  if (RecordingInfo.Read()) {
2484  if (FrameDetector.FramesPerSecond() > 0 && !DoubleEqual(RecordingInfo.FramesPerSecond(), FrameDetector.FramesPerSecond())) {
2485  RecordingInfo.SetFramesPerSecond(FrameDetector.FramesPerSecond());
2486  RecordingInfo.Write();
2488  Recordings->UpdateByName(recordingName);
2489  }
2490  }
2491  Skins.QueueMessage(mtInfo, tr("Index file regeneration complete"));
2492  return;
2493  }
2494  else
2495  Skins.QueueMessage(mtError, tr("Index file regeneration failed!"));
2496  }
2497  // Delete the index file if the recording has not been processed entirely:
2498  IndexFile.Delete();
2499 }
2500 
2501 // --- cIndexFile ------------------------------------------------------------
2502 
2503 #define INDEXFILESUFFIX "/index"
2504 
2505 // The maximum time to wait before giving up while catching up on an index file:
2506 #define MAXINDEXCATCHUP 8 // number of retries
2507 #define INDEXCATCHUPWAIT 100 // milliseconds
2508 
2509 struct __attribute__((packed)) tIndexPes {
2510  uint32_t offset;
2511  uchar type;
2512  uchar number;
2513  uint16_t reserved;
2514  };
2515 
2516 struct __attribute__((packed)) tIndexTs {
2517  uint64_t offset:40; // up to 1TB per file (not using off_t here - must definitely be exactly 64 bit!)
2518  int reserved:7; // reserved for future use
2519  int independent:1; // marks frames that can be displayed by themselves (for trick modes)
2520  uint16_t number:16; // up to 64K files per recording
2521  tIndexTs(off_t Offset, bool Independent, uint16_t Number)
2522  {
2523  offset = Offset;
2524  reserved = 0;
2525  independent = Independent;
2526  number = Number;
2527  }
2528  };
2529 
2530 #define MAXWAITFORINDEXFILE 10 // max. time to wait for the regenerated index file (seconds)
2531 #define INDEXFILECHECKINTERVAL 500 // ms between checks for existence of the regenerated index file
2532 #define INDEXFILETESTINTERVAL 10 // ms between tests for the size of the index file in case of pausing live video
2533 
2534 cIndexFile::cIndexFile(const char *FileName, bool Record, bool IsPesRecording, bool PauseLive, bool Update)
2535 :resumeFile(FileName, IsPesRecording)
2536 {
2537  f = -1;
2538  size = 0;
2539  last = -1;
2540  index = NULL;
2541  isPesRecording = IsPesRecording;
2542  indexFileGenerator = NULL;
2543  if (FileName) {
2544  fileName = IndexFileName(FileName, isPesRecording);
2545  if (!Record && PauseLive) {
2546  // Wait until the index file contains at least two frames:
2547  time_t tmax = time(NULL) + MAXWAITFORINDEXFILE;
2548  while (time(NULL) < tmax && FileSize(fileName) < off_t(2 * sizeof(tIndexTs)))
2550  }
2551  int delta = 0;
2552  if (!Record && access(fileName, R_OK) != 0) {
2553  // Index file doesn't exist, so try to regenerate it:
2554  if (!isPesRecording) { // sorry, can only do this for TS recordings
2555  resumeFile.Delete(); // just in case
2556  indexFileGenerator = new cIndexFileGenerator(FileName);
2557  // Wait until the index file exists:
2558  time_t tmax = time(NULL) + MAXWAITFORINDEXFILE;
2559  do {
2560  cCondWait::SleepMs(INDEXFILECHECKINTERVAL); // start with a sleep, to give it a head start
2561  } while (access(fileName, R_OK) != 0 && time(NULL) < tmax);
2562  }
2563  }
2564  if (access(fileName, R_OK) == 0) {
2565  struct stat buf;
2566  if (stat(fileName, &buf) == 0) {
2567  delta = int(buf.st_size % sizeof(tIndexTs));
2568  if (delta) {
2569  delta = sizeof(tIndexTs) - delta;
2570  esyslog("ERROR: invalid file size (%" PRId64 ") in '%s'", buf.st_size, *fileName);
2571  }
2572  last = int((buf.st_size + delta) / sizeof(tIndexTs) - 1);
2573  if ((!Record || Update) && last >= 0) {
2574  size = last + 1;
2575  index = MALLOC(tIndexTs, size);
2576  if (index) {
2577  f = open(fileName, O_RDONLY);
2578  if (f >= 0) {
2579  if (safe_read(f, index, size_t(buf.st_size)) != buf.st_size) {
2580  esyslog("ERROR: can't read from file '%s'", *fileName);
2581  free(index);
2582  index = NULL;
2583  }
2584  else if (isPesRecording)
2586  if (!index || time(NULL) - buf.st_mtime >= MININDEXAGE) {
2587  close(f);
2588  f = -1;
2589  }
2590  // otherwise we don't close f here, see CatchUp()!
2591  }
2592  else
2594  }
2595  else
2596  esyslog("ERROR: can't allocate %zd bytes for index '%s'", size * sizeof(tIndexTs), *fileName);
2597  }
2598  }
2599  else
2600  LOG_ERROR;
2601  }
2602  else if (!Record)
2603  isyslog("missing index file %s", *fileName);
2604  if (Record) {
2605  if ((f = open(fileName, O_WRONLY | O_CREAT | O_APPEND, DEFFILEMODE)) >= 0) {
2606  if (delta) {
2607  esyslog("ERROR: padding index file with %d '0' bytes", delta);
2608  while (delta--)
2609  writechar(f, 0);
2610  }
2611  }
2612  else
2614  }
2615  }
2616 }
2617 
2619 {
2620  if (f >= 0)
2621  close(f);
2622  free(index);
2623  delete indexFileGenerator;
2624 }
2625 
2626 cString cIndexFile::IndexFileName(const char *FileName, bool IsPesRecording)
2627 {
2628  return cString::sprintf("%s%s", FileName, IsPesRecording ? INDEXFILESUFFIX ".vdr" : INDEXFILESUFFIX);
2629 }
2630 
2631 void cIndexFile::ConvertFromPes(tIndexTs *IndexTs, int Count)
2632 {
2633  tIndexPes IndexPes;
2634  while (Count-- > 0) {
2635  memcpy(&IndexPes, IndexTs, sizeof(IndexPes));
2636  IndexTs->offset = IndexPes.offset;
2637  IndexTs->independent = IndexPes.type == 1; // I_FRAME
2638  IndexTs->number = IndexPes.number;
2639  IndexTs++;
2640  }
2641 }
2642 
2643 void cIndexFile::ConvertToPes(tIndexTs *IndexTs, int Count)
2644 {
2645  tIndexPes IndexPes;
2646  while (Count-- > 0) {
2647  IndexPes.offset = uint32_t(IndexTs->offset);
2648  IndexPes.type = uchar(IndexTs->independent ? 1 : 2); // I_FRAME : "not I_FRAME" (exact frame type doesn't matter)
2649  IndexPes.number = uchar(IndexTs->number);
2650  IndexPes.reserved = 0;
2651  memcpy((void *)IndexTs, &IndexPes, sizeof(*IndexTs));
2652  IndexTs++;
2653  }
2654 }
2655 
2656 bool cIndexFile::CatchUp(int Index)
2657 {
2658  // returns true unless something really goes wrong, so that 'index' becomes NULL
2659  if (index && f >= 0) {
2660  cMutexLock MutexLock(&mutex);
2661  // Note that CatchUp() is triggered even if Index is 'last' (and thus valid).
2662  // This is done to make absolutely sure we don't miss any data at the very end.
2663  for (int i = 0; i <= MAXINDEXCATCHUP && (Index < 0 || Index >= last); i++) {
2664  struct stat buf;
2665  if (fstat(f, &buf) == 0) {
2666  int newLast = int(buf.st_size / sizeof(tIndexTs) - 1);
2667  if (newLast > last) {
2668  int NewSize = size;
2669  if (NewSize <= newLast) {
2670  NewSize *= 2;
2671  if (NewSize <= newLast)
2672  NewSize = newLast + 1;
2673  }
2674  if (tIndexTs *NewBuffer = (tIndexTs *)realloc(index, NewSize * sizeof(tIndexTs))) {
2675  size = NewSize;
2676  index = NewBuffer;
2677  int offset = (last + 1) * sizeof(tIndexTs);
2678  int delta = (newLast - last) * sizeof(tIndexTs);
2679  if (lseek(f, offset, SEEK_SET) == offset) {
2680  if (safe_read(f, &index[last + 1], delta) != delta) {
2681  esyslog("ERROR: can't read from index");
2682  free(index);
2683  index = NULL;
2684  close(f);
2685  f = -1;
2686  break;
2687  }
2688  if (isPesRecording)
2689  ConvertFromPes(&index[last + 1], newLast - last);
2690  last = newLast;
2691  }
2692  else
2694  }
2695  else {
2696  esyslog("ERROR: can't realloc() index");
2697  break;
2698  }
2699  }
2700  }
2701  else
2703  if (Index < last)
2704  break;
2705  cCondVar CondVar;
2706  CondVar.TimedWait(mutex, INDEXCATCHUPWAIT);
2707  }
2708  }
2709  return index != NULL;
2710 }
2711 
2712 bool cIndexFile::Write(bool Independent, uint16_t FileNumber, off_t FileOffset)
2713 {
2714  if (f >= 0) {
2715  tIndexTs i(FileOffset, Independent, FileNumber);
2716  if (isPesRecording)
2717  ConvertToPes(&i, 1);
2718  if (safe_write(f, &i, sizeof(i)) < 0) {
2720  close(f);
2721  f = -1;
2722  return false;
2723  }
2724  last++;
2725  }
2726  return f >= 0;
2727 }
2728 
2729 bool cIndexFile::Get(int Index, uint16_t *FileNumber, off_t *FileOffset, bool *Independent, int *Length)
2730 {
2731  if (CatchUp(Index)) {
2732  if (Index >= 0 && Index <= last) {
2733  *FileNumber = index[Index].number;
2734  *FileOffset = index[Index].offset;
2735  if (Independent)
2736  *Independent = index[Index].independent;
2737  if (Length) {
2738  if (Index < last) {
2739  uint16_t fn = index[Index + 1].number;
2740  off_t fo = index[Index + 1].offset;
2741  if (fn == *FileNumber)
2742  *Length = int(fo - *FileOffset);
2743  else
2744  *Length = -1; // this means "everything up to EOF" (the buffer's Read function will act accordingly)
2745  }
2746  else
2747  *Length = -1;
2748  }
2749  return true;
2750  }
2751  }
2752  return false;
2753 }
2754 
2755 int cIndexFile::GetNextIFrame(int Index, bool Forward, uint16_t *FileNumber, off_t *FileOffset, int *Length)
2756 {
2757  if (CatchUp()) {
2758  int d = Forward ? 1 : -1;
2759  for (;;) {
2760  Index += d;
2761  if (Index >= 0 && Index <= last) {
2762  if (index[Index].independent) {
2763  uint16_t fn;
2764  if (!FileNumber)
2765  FileNumber = &fn;
2766  off_t fo;
2767  if (!FileOffset)
2768  FileOffset = &fo;
2769  *FileNumber = index[Index].number;
2770  *FileOffset = index[Index].offset;
2771  if (Length) {
2772  if (Index < last) {
2773  uint16_t fn = index[Index + 1].number;
2774  off_t fo = index[Index + 1].offset;
2775  if (fn == *FileNumber)
2776  *Length = int(fo - *FileOffset);
2777  else
2778  *Length = -1; // this means "everything up to EOF" (the buffer's Read function will act accordingly)
2779  }
2780  else
2781  *Length = -1;
2782  }
2783  return Index;
2784  }
2785  }
2786  else
2787  break;
2788  }
2789  }
2790  return -1;
2791 }
2792 
2794 {
2795  if (last > 0) {
2796  Index = constrain(Index, 0, last);
2797  if (index[Index].independent)
2798  return Index;
2799  int il = Index - 1;
2800  int ih = Index + 1;
2801  for (;;) {
2802  if (il >= 0) {
2803  if (index[il].independent)
2804  return il;
2805  il--;
2806  }
2807  else if (ih > last)
2808  break;
2809  if (ih <= last) {
2810  if (index[ih].independent)
2811  return ih;
2812  ih++;
2813  }
2814  else if (il < 0)
2815  break;
2816  }
2817  }
2818  return 0;
2819 }
2820 
2821 int cIndexFile::Get(uint16_t FileNumber, off_t FileOffset)
2822 {
2823  if (CatchUp()) {
2824  //TODO implement binary search!
2825  int i;
2826  for (i = 0; i <= last; i++) {
2827  if (index[i].number > FileNumber || (index[i].number == FileNumber) && off_t(index[i].offset) >= FileOffset)
2828  break;
2829  }
2830  return i;
2831  }
2832  return -1;
2833 }
2834 
2836 {
2837  return f >= 0;
2838 }
2839 
2841 {
2842  if (*fileName) {
2843  dsyslog("deleting index file '%s'", *fileName);
2844  if (f >= 0) {
2845  close(f);
2846  f = -1;
2847  }
2848  unlink(fileName);
2849  }
2850 }
2851 
2852 int cIndexFile::GetLength(const char *FileName, bool IsPesRecording)
2853 {
2854  struct stat buf;
2855  cString s = IndexFileName(FileName, IsPesRecording);
2856  if (*s && stat(s, &buf) == 0)
2857  return buf.st_size / (IsPesRecording ? sizeof(tIndexTs) : sizeof(tIndexPes));
2858  return -1;
2859 }
2860 
2861 bool GenerateIndex(const char *FileName, bool Update)
2862 {
2863  if (DirectoryOk(FileName)) {
2864  cRecording Recording(FileName);
2865  if (Recording.Name()) {
2866  if (!Recording.IsPesRecording()) {
2867  cString IndexFileName = AddDirectory(FileName, INDEXFILESUFFIX);
2868  if (!Update)
2869  unlink(IndexFileName);
2870  cIndexFileGenerator *IndexFileGenerator = new cIndexFileGenerator(FileName, Update);
2871  while (IndexFileGenerator->Active())
2873  if (access(IndexFileName, R_OK) == 0)
2874  return true;
2875  else
2876  fprintf(stderr, "cannot create '%s'\n", *IndexFileName);
2877  }
2878  else
2879  fprintf(stderr, "'%s' is not a TS recording\n", FileName);
2880  }
2881  else
2882  fprintf(stderr, "'%s' is not a recording\n", FileName);
2883  }
2884  else
2885  fprintf(stderr, "'%s' is not a directory\n", FileName);
2886  return false;
2887 }
2888 
2889 // --- cFileName -------------------------------------------------------------
2890 
2891 #define MAXFILESPERRECORDINGPES 255
2892 #define RECORDFILESUFFIXPES "/%03d.vdr"
2893 #define MAXFILESPERRECORDINGTS 65535
2894 #define RECORDFILESUFFIXTS "/%05d.ts"
2895 #define RECORDFILESUFFIXLEN 20 // some additional bytes for safety...
2896 
2897 cFileName::cFileName(const char *FileName, bool Record, bool Blocking, bool IsPesRecording)
2898 {
2899  file = NULL;
2900  fileNumber = 0;
2901  record = Record;
2902  blocking = Blocking;
2903  isPesRecording = IsPesRecording;
2904  // Prepare the file name:
2905  fileName = MALLOC(char, strlen(FileName) + RECORDFILESUFFIXLEN);
2906  if (!fileName) {
2907  esyslog("ERROR: can't copy file name '%s'", FileName);
2908  return;
2909  }
2910  strcpy(fileName, FileName);
2911  pFileNumber = fileName + strlen(fileName);
2912  SetOffset(1);
2913 }
2914 
2916 {
2917  Close();
2918  free(fileName);
2919 }
2920 
2921 bool cFileName::GetLastPatPmtVersions(int &PatVersion, int &PmtVersion)
2922 {
2923  if (fileName && !isPesRecording) {
2924  // Find the last recording file:
2925  int Number = 1;
2926  for (; Number <= MAXFILESPERRECORDINGTS + 1; Number++) { // +1 to correctly set Number in case there actually are that many files
2928  if (access(fileName, F_OK) != 0) { // file doesn't exist
2929  Number--;
2930  break;
2931  }
2932  }
2933  for (; Number > 0; Number--) {
2934  // Search for a PAT packet from the end of the file:
2935  cPatPmtParser PatPmtParser;
2937  int fd = open(fileName, O_RDONLY | O_LARGEFILE, DEFFILEMODE);
2938  if (fd >= 0) {
2939  off_t pos = lseek(fd, -TS_SIZE, SEEK_END);
2940  while (pos >= 0) {
2941  // Read and parse the PAT/PMT:
2942  uchar buf[TS_SIZE];
2943  while (read(fd, buf, sizeof(buf)) == sizeof(buf)) {
2944  if (buf[0] == TS_SYNC_BYTE) {
2945  int Pid = TsPid(buf);
2946  if (Pid == PATPID)
2947  PatPmtParser.ParsePat(buf, sizeof(buf));
2948  else if (PatPmtParser.IsPmtPid(Pid)) {
2949  PatPmtParser.ParsePmt(buf, sizeof(buf));
2950  if (PatPmtParser.GetVersions(PatVersion, PmtVersion)) {
2951  close(fd);
2952  return true;
2953  }
2954  }
2955  else
2956  break; // PAT/PMT is always in one sequence
2957  }
2958  else
2959  return false;
2960  }
2961  pos = lseek(fd, pos - TS_SIZE, SEEK_SET);
2962  }
2963  close(fd);
2964  }
2965  else
2966  break;
2967  }
2968  }
2969  return false;
2970 }
2971 
2973 {
2974  if (!file) {
2975  int BlockingFlag = blocking ? 0 : O_NONBLOCK;
2976  if (record) {
2977  dsyslog("recording to '%s'", fileName);
2978  file = cVideoDirectory::OpenVideoFile(fileName, O_RDWR | O_CREAT | O_LARGEFILE | BlockingFlag);
2979  if (!file)
2981  }
2982  else {
2983  if (access(fileName, R_OK) == 0) {
2984  dsyslog("playing '%s'", fileName);
2985  file = cUnbufferedFile::Create(fileName, O_RDONLY | O_LARGEFILE | BlockingFlag);
2986  if (!file)
2988  }
2989  else if (errno != ENOENT)
2991  }
2992  }
2993  return file;
2994 }
2995 
2997 {
2998  if (file) {
2999  if (file->Close() < 0)
3001  delete file;
3002  file = NULL;
3003  }
3004 }
3005 
3006 cUnbufferedFile *cFileName::SetOffset(int Number, off_t Offset)
3007 {
3008  if (fileNumber != Number)
3009  Close();
3010  int MaxFilesPerRecording = isPesRecording ? MAXFILESPERRECORDINGPES : MAXFILESPERRECORDINGTS;
3011  if (0 < Number && Number <= MaxFilesPerRecording) {
3012  fileNumber = uint16_t(Number);
3014  if (record) {
3015  if (access(fileName, F_OK) == 0) {
3016  // file exists, check if it has non-zero size
3017  struct stat buf;
3018  if (stat(fileName, &buf) == 0) {
3019  if (buf.st_size != 0)
3020  return SetOffset(Number + 1); // file exists and has non zero size, let's try next suffix
3021  else {
3022  // zero size file, remove it
3023  dsyslog("cFileName::SetOffset: removing zero-sized file %s", fileName);
3024  unlink(fileName);
3025  }
3026  }
3027  else
3028  return SetOffset(Number + 1); // error with fstat - should not happen, just to be on the safe side
3029  }
3030  else if (errno != ENOENT) { // something serious has happened
3032  return NULL;
3033  }
3034  // found a non existing file suffix
3035  }
3036  if (Open()) {
3037  if (!record && Offset >= 0 && file->Seek(Offset, SEEK_SET) != Offset) {
3039  return NULL;
3040  }
3041  }
3042  return file;
3043  }
3044  esyslog("ERROR: max number of files (%d) exceeded", MaxFilesPerRecording);
3045  return NULL;
3046 }
3047 
3049 {
3050  return SetOffset(fileNumber + 1);
3051 }
3052 
3053 // --- Index stuff -----------------------------------------------------------
3054 
3055 cString IndexToHMSF(int Index, bool WithFrame, double FramesPerSecond)
3056 {
3057  const char *Sign = "";
3058  if (Index < 0) {
3059  Index = -Index;
3060  Sign = "-";
3061  }
3062  double Seconds;
3063  int f = int(modf((Index + 0.5) / FramesPerSecond, &Seconds) * FramesPerSecond);
3064  int s = int(Seconds);
3065  int m = s / 60 % 60;
3066  int h = s / 3600;
3067  s %= 60;
3068  return cString::sprintf(WithFrame ? "%s%d:%02d:%02d.%02d" : "%s%d:%02d:%02d", Sign, h, m, s, f);
3069 }
3070 
3071 int HMSFToIndex(const char *HMSF, double FramesPerSecond)
3072 {
3073  int h, m, s, f = 0;
3074  int n = sscanf(HMSF, "%d:%d:%d.%d", &h, &m, &s, &f);
3075  if (n == 1)
3076  return h; // plain frame number
3077  if (n >= 3)
3078  return int(round((h * 3600 + m * 60 + s) * FramesPerSecond)) + f;
3079  return 0;
3080 }
3081 
3082 int SecondsToFrames(int Seconds, double FramesPerSecond)
3083 {
3084  return int(round(Seconds * FramesPerSecond));
3085 }
3086 
3087 // --- ReadFrame -------------------------------------------------------------
3088 
3089 int ReadFrame(cUnbufferedFile *f, uchar *b, int Length, int Max)
3090 {
3091  if (Length == -1)
3092  Length = Max; // this means we read up to EOF (see cIndex)
3093  else if (Length > Max) {
3094  esyslog("ERROR: frame larger than buffer (%d > %d)", Length, Max);
3095  Length = Max;
3096  }
3097  int r = f->Read(b, Length);
3098  if (r < 0)
3099  LOG_ERROR;
3100  return r;
3101 }
3102 
3103 // --- Recordings Sort Mode --------------------------------------------------
3104 
3106 
3107 bool HasRecordingsSortMode(const char *Directory)
3108 {
3109  return access(AddDirectory(Directory, SORTMODEFILE), R_OK) == 0;
3110 }
3111 
3112 void GetRecordingsSortMode(const char *Directory)
3113 {
3115  if (FILE *f = fopen(AddDirectory(Directory, SORTMODEFILE), "r")) {
3116  char buf[8];
3117  if (fgets(buf, sizeof(buf), f))
3119  fclose(f);
3120  }
3121 }
3122 
3123 void SetRecordingsSortMode(const char *Directory, eRecordingsSortMode SortMode)
3124 {
3125  if (FILE *f = fopen(AddDirectory(Directory, SORTMODEFILE), "w")) {
3126  fputs(cString::sprintf("%d\n", SortMode), f);
3127  fclose(f);
3128  }
3129 }
3130 
3131 void IncRecordingsSortMode(const char *Directory)
3132 {
3133  GetRecordingsSortMode(Directory);
3138 }
3139 
3140 // --- Recording Timer Indicator ---------------------------------------------
3141 
3142 void SetRecordingTimerId(const char *Directory, const char *TimerId)
3143 {
3144  cString FileName = AddDirectory(Directory, TIMERRECFILE);
3145  if (TimerId) {
3146  dsyslog("writing timer id '%s' to %s", TimerId, *FileName);
3147  if (FILE *f = fopen(FileName, "w")) {
3148  fprintf(f, "%s\n", TimerId);
3149  fclose(f);
3150  }
3151  else
3152  LOG_ERROR_STR(*FileName);
3153  }
3154  else {
3155  dsyslog("removing %s", *FileName);
3156  unlink(FileName);
3157  }
3158 }
3159 
3160 cString GetRecordingTimerId(const char *Directory)
3161 {
3162  cString FileName = AddDirectory(Directory, TIMERRECFILE);
3163  const char *Id = NULL;
3164  if (FILE *f = fopen(FileName, "r")) {
3165  char buf[HOST_NAME_MAX + 10]; // +10 for numeric timer id and '@'
3166  if (fgets(buf, sizeof(buf), f)) {
3167  stripspace(buf);
3168  Id = buf;
3169  }
3170  fclose(f);
3171  }
3172  return Id;
3173 }
#define MAXDPIDS
Definition: channels.h:32
#define MAXAPIDS
Definition: channels.h:31
#define MAXSPIDS
Definition: channels.h:33
const char * Alang(int i) const
Definition: channels.h:163
int Number(void) const
Definition: channels.h:179
const char * Name(void) const
Definition: channels.c:108
tChannelID GetChannelID(void) const
Definition: channels.h:190
const char * Slang(int i) const
Definition: channels.h:165
const char * Dlang(int i) const
Definition: channels.h:164
tComponent * GetComponent(int Index, uchar Stream, uchar Type)
Definition: epg.c:97
int NumComponents(void) const
Definition: epg.h:59
void SetComponent(int Index, const char *s)
Definition: epg.c:77
bool TimedWait(cMutex &Mutex, int TimeoutMs)
Definition: thread.c:132
static void SleepMs(int TimeoutMs)
Creates a cCondWait object and uses it to sleep for TimeoutMs milliseconds, immediately giving up the...
Definition: thread.c:72
Definition: cutter.h:18
bool Start(void)
Starts the actual cutting process.
Definition: cutter.c:668
bool Error(void)
Returns true if an error occurred while cutting the recording.
Definition: cutter.c:719
bool Active(void)
Returns true if the cutter is currently active.
Definition: cutter.c:706
static cString EditedFileName(const char *FileName)
Returns the full path name of the edited version of the recording with the given FileName.
Definition: cutter.c:656
cDirCopier(const char *DirNameSrc, const char *DirNameDst)
Definition: recording.c:1705
cString dirNameDst
Definition: recording.c:1694
bool suspensionLogged
Definition: recording.c:1696
virtual ~cDirCopier()
Definition: recording.c:1714
bool Throttled(void)
Definition: recording.c:1719
cString dirNameSrc
Definition: recording.c:1693
virtual void Action(void)
A derived cThread class must implement the code it wants to execute as a separate thread in this func...
Definition: recording.c:1735
bool error
Definition: recording.c:1695
bool Error(void)
Definition: recording.c:1702
Definition: epg.h:71
bool Parse(char *s)
Definition: epg.c:490
const cComponents * Components(void) const
Definition: epg.h:106
void SetStartTime(time_t StartTime)
Definition: epg.c:216
const char * Title(void) const
Definition: epg.h:103
void SetEventID(tEventID EventID)
Definition: epg.c:156
void SetVersion(uchar Version)
Definition: epg.c:172
void SetDuration(int Duration)
Definition: epg.c:227
const char * ShortText(void) const
Definition: epg.h:104
void SetTitle(const char *Title)
Definition: epg.c:184
void SetTableID(uchar TableID)
Definition: epg.c:167
bool isPesRecording
Definition: recording.h:499
cUnbufferedFile * NextFile(void)
Definition: recording.c:3048
uint16_t Number(void)
Definition: recording.h:504
bool record
Definition: recording.h:497
void Close(void)
Definition: recording.c:2996
uint16_t fileNumber
Definition: recording.h:495
cUnbufferedFile * Open(void)
Definition: recording.c:2972
cFileName(const char *FileName, bool Record, bool Blocking=false, bool IsPesRecording=false)
Definition: recording.c:2897
char * fileName
Definition: recording.h:496
char * pFileNumber
Definition: recording.h:496
bool GetLastPatPmtVersions(int &PatVersion, int &PmtVersion)
Definition: recording.c:2921
bool blocking
Definition: recording.h:498
cUnbufferedFile * SetOffset(int Number, off_t Offset=0)
Definition: recording.c:3006
cUnbufferedFile * file
Definition: recording.h:494
bool Synced(void)
Returns true if the frame detector has synced on the data stream.
Definition: remux.h:544
bool IndependentFrame(void)
Returns true if a new frame was detected and this is an independent frame (i.e.
Definition: remux.h:549
double FramesPerSecond(void)
Returns the number of frames per second, or 0 if this information is not available.
Definition: remux.h:553
int Analyze(const uchar *Data, int Length)
Analyzes the TS packets pointed to by Data.
Definition: remux.c:1690
void SetPid(int Pid, int Type)
Sets the Pid and stream Type to detect frames for.
Definition: remux.c:1671
bool NewFrame(void)
Returns true if the data given to the last call to Analyze() started a new frame.
Definition: remux.h:546
cIndexFileGenerator(const char *RecordingName, bool Update=false)
Definition: recording.c:2342
virtual void Action(void)
A derived cThread class must implement the code it wants to execute as a separate thread in this func...
Definition: recording.c:2355
int GetNextIFrame(int Index, bool Forward, uint16_t *FileNumber=NULL, off_t *FileOffset=NULL, int *Length=NULL)
Definition: recording.c:2755
cResumeFile resumeFile
Definition: recording.h:461
bool IsStillRecording(void)
Definition: recording.c:2835
void ConvertFromPes(tIndexTs *IndexTs, int Count)
Definition: recording.c:2631
bool Write(bool Independent, uint16_t FileNumber, off_t FileOffset)
Definition: recording.c:2712
static int GetLength(const char *FileName, bool IsPesRecording=false)
Calculates the recording length (number of frames) without actually reading the index file.
Definition: recording.c:2852
bool CatchUp(int Index=-1)
Definition: recording.c:2656
void ConvertToPes(tIndexTs *IndexTs, int Count)
Definition: recording.c:2643
bool isPesRecording
Definition: recording.h:460
cString fileName
Definition: recording.h:457
cIndexFile(const char *FileName, bool Record, bool IsPesRecording=false, bool PauseLive=false, bool Update=false)
Definition: recording.c:2534
cIndexFileGenerator * indexFileGenerator
Definition: recording.h:462
static cString IndexFileName(const char *FileName, bool IsPesRecording)
Definition: recording.c:2626
bool Get(int Index, uint16_t *FileNumber, off_t *FileOffset, bool *Independent=NULL, int *Length=NULL)
Definition: recording.c:2729
int GetClosestIFrame(int Index)
Returns the index of the I-frame that is closest to the given Index (or Index itself,...
Definition: recording.c:2793
cMutex mutex
Definition: recording.h:463
void Delete(void)
Definition: recording.c:2840
int Last(void)
Returns the index of the last entry in this file, or -1 if the file is empty.
Definition: recording.h:480
tIndexTs * index
Definition: recording.h:459
static bool Engaged(void)
Returns true if any I/O throttling object is currently active.
Definition: thread.c:918
virtual void Clear(void)
Definition: tools.c:2235
void Del(cListObject *Object, bool DeleteObject=true)
Definition: tools.c:2190
void SetModified(void)
Unconditionally marks this list as modified.
Definition: tools.c:2260
bool Lock(cStateKey &StateKey, bool Write=false, int TimeoutMs=0) const
Tries to get a lock on this list and returns true if successful.
Definition: tools.c:2149
int Count(void) const
Definition: tools.h:594
void Add(cListObject *Object, cListObject *After=NULL)
Definition: tools.c:2158
cListObject * Next(void) const
Definition: tools.h:514
Definition: tools.h:598
const T * Next(const T *Object) const
< Returns the element immediately before Object in this list, or NULL if Object is the first element ...
Definition: tools.h:617
const T * Last(void) const
Returns the last element in this list, or NULL if the list is empty.
Definition: tools.h:612
const T * First(void) const
Returns the first element in this list, or NULL if the list is empty.
Definition: tools.h:610
const T * Prev(const T *Object) const
Definition: tools.h:614
bool Lock(int WaitSeconds=0)
Definition: tools.c:2001
cMark(int Position=0, const char *Comment=NULL, double FramesPerSecond=DEFAULTFRAMESPERSECOND)
Definition: recording.c:2097
cString comment
Definition: recording.h:361
int position
Definition: recording.h:360
bool Parse(const char *s)
Definition: recording.c:2113
bool Save(FILE *f)
Definition: recording.c:2127
cString ToText(void)
Definition: recording.c:2108
const char * Comment(void) const
Definition: recording.h:366
double framesPerSecond
Definition: recording.h:359
int Position(void) const
Definition: recording.h:365
virtual ~cMark()
Definition: recording.c:2104
int GetNumSequences(void) const
Returns the actual number of sequences to be cut from the recording.
Definition: recording.c:2293
double framesPerSecond
Definition: recording.h:378
void Add(int Position)
If this cMarks object is used by multiple threads, the caller must Lock() it before calling Add() and...
Definition: recording.c:2226
const cMark * GetNextBegin(const cMark *EndMark=NULL) const
Returns the next "begin" mark after EndMark, skipping any marks at the same position as EndMark.
Definition: recording.c:2259
const cMark * GetNext(int Position) const
Definition: recording.c:2250
bool Update(void)
Definition: recording.c:2162
bool Load(const char *RecordingFileName, double FramesPerSecond=DEFAULTFRAMESPERSECOND, bool IsPesRecording=false)
Definition: recording.c:2150
time_t lastFileTime
Definition: recording.h:381
const cMark * GetNextEnd(const cMark *BeginMark) const
Returns the next "end" mark after BeginMark, skipping any marks at the same position as BeginMark.
Definition: recording.c:2275
const cMark * Get(int Position) const
Definition: recording.c:2232
cString recordingFileName
Definition: recording.h:376
bool isPesRecording
Definition: recording.h:379
time_t nextUpdate
Definition: recording.h:380
cString fileName
Definition: recording.h:377
static bool DeleteMarksFile(const cRecording *Recording)
Definition: recording.c:2139
void Align(void)
Definition: recording.c:2202
void Sort(void)
Definition: recording.c:2214
static cString MarksFileName(const cRecording *Recording)
Returns the marks file name for the given Recording (regardless whether such a file actually exists).
Definition: recording.c:2134
bool Save(void)
Definition: recording.c:2193
const cMark * GetPrev(int Position) const
Definition: recording.c:2241
time_t lastChange
Definition: recording.h:382
Definition: thread.h:67
bool GetVersions(int &PatVersion, int &PmtVersion) const
Returns true if a valid PAT/PMT has been parsed and stores the current version numbers in the given v...
Definition: remux.c:974
int Vtype(void) const
Returns the video stream type as defined by the current PMT, or 0 if no video stream type has been de...
Definition: remux.h:415
void ParsePat(const uchar *Data, int Length)
Parses the PAT data from the single TS packet in Data.
Definition: remux.c:663
int Apid(int i) const
Definition: remux.h:423
void ParsePmt(const uchar *Data, int Length)
Parses the PMT data from the single TS packet in Data.
Definition: remux.c:695
bool Completed(void)
Returns true if the PMT has been completely parsed.
Definition: remux.h:418
bool IsPmtPid(int Pid) const
Returns true if Pid the one of the PMT pids as defined by the current PAT.
Definition: remux.h:406
int Atype(int i) const
Definition: remux.h:426
int Vpid(void) const
Returns the video pid as defined by the current PMT, or 0 if no video pid has been detected,...
Definition: remux.h:409
struct dirent * Next(void)
Definition: tools.c:1546
bool Ok(void)
Definition: tools.h:422
char * Read(FILE *f)
Definition: tools.c:1465
static cRecordControl * GetRecordControl(const char *FileName)
Definition: menu.c:5580
void SetFramesPerSecond(double FramesPerSecond)
Definition: recording.c:447
cEvent * ownEvent
Definition: recording.h:74
const cEvent * event
Definition: recording.h:73
cRecordingInfo(const cChannel *Channel=NULL, const cEvent *Event=NULL)
Definition: recording.c:351
bool Write(void) const
Definition: recording.c:549
bool Write(FILE *f, const char *Prefix="") const
Definition: recording.c:518
bool Read(void)
Definition: recording.c:531
char * aux
Definition: recording.h:75
const char * Title(void) const
Definition: recording.h:88
tChannelID channelID
Definition: recording.h:71
const char * Description(void) const
Definition: recording.h:90
void SetFileName(const char *FileName)
Definition: recording.c:452
const char * ShortText(void) const
Definition: recording.h:89
bool Read(FILE *f)
Definition: recording.c:459
char * channelName
Definition: recording.h:72
const char * Aux(void) const
Definition: recording.h:92
void SetAux(const char *Aux)
Definition: recording.c:441
void SetData(const char *Title, const char *ShortText, const char *Description)
Definition: recording.c:431
const cComponents * Components(void) const
Definition: recording.h:91
double framesPerSecond
Definition: recording.h:76
double FramesPerSecond(void) const
Definition: recording.h:93
char * fileName
Definition: recording.h:79
static const char * command
Definition: recording.h:432
static void InvokeCommand(const char *State, const char *RecordingFileName, const char *SourceFileName=NULL)
Definition: recording.c:2314
int isOnVideoDirectoryFileSystem
Definition: recording.h:118
virtual int Compare(const cListObject &ListObject) const
Must return 0 if this object is equal to ListObject, a positive value if it is "greater",...
Definition: recording.c:1027
time_t deleted
Definition: recording.h:130
cRecordingInfo * info
Definition: recording.h:120
bool ChangePriorityLifetime(int NewPriority, int NewLifetime)
Changes the priority and lifetime of this recording to the given values.
Definition: recording.c:1211
bool HasMarks(void) const
Returns true if this recording has any editing marks.
Definition: recording.c:1173
bool WriteInfo(const char *OtherFileName=NULL)
Writes in info file of this recording.
Definition: recording.c:1191
int resume
Definition: recording.h:107
int IsInUse(void) const
Checks whether this recording is currently in use and therefore shall not be tampered with.
Definition: recording.c:1326
bool ChangeName(const char *NewName)
Changes the name of this recording to the given value.
Definition: recording.c:1236
bool Undelete(void)
Changes the file name so that it will be visible in the "Recordings" menu again and not processed by ...
Definition: recording.c:1300
void ResetResume(void) const
Definition: recording.c:1337
bool IsNew(void) const
Definition: recording.h:174
double framesPerSecond
Definition: recording.h:119
bool Delete(void)
Changes the file name so that it will no longer be visible in the "Recordings" menu Returns false in ...
Definition: recording.c:1263
const char * Name(void) const
Returns the full name of the recording (without the video directory).
Definition: recording.h:151
cString Folder(void) const
Returns the name of the folder this recording is stored in (without the video directory).
Definition: recording.c:1044
bool isPesRecording
Definition: recording.h:117
void ClearSortName(void)
Definition: recording.c:1006
char * sortBufferName
Definition: recording.h:109
int NumFrames(void) const
Returns the number of frames in this recording.
Definition: recording.c:1342
bool IsEdited(void) const
Definition: recording.c:1159
int Id(void) const
Definition: recording.h:135
int GetResume(void) const
Returns the index of the frame where replay of this recording shall be resumed, or -1 in case of an e...
Definition: recording.c:1018
bool IsInPath(const char *Path) const
Returns true if this recording is stored anywhere under the given Path.
Definition: recording.c:1036
virtual ~cRecording()
Definition: recording.c:943
int fileSizeMB
Definition: recording.h:113
void SetId(int Id)
Definition: recording.c:1013
void SetStartTime(time_t Start)
Sets the start time of this recording to the given value.
Definition: recording.c:1204
char * SortName(void) const
Definition: recording.c:982
time_t Start(void) const
Definition: recording.h:136
int Lifetime(void) const
Definition: recording.h:138
const char * FileName(void) const
Returns the full path name to the recording directory, including the video directory and the actual '...
Definition: recording.c:1058
const char * PrefixFileName(char Prefix)
Definition: recording.c:1137
bool DeleteMarks(void)
Deletes the editing marks from this recording (if any).
Definition: recording.c:1178
int priority
Definition: recording.h:128
bool IsOnVideoDirectoryFileSystem(void) const
Definition: recording.c:1166
int HierarchyLevels(void) const
Definition: recording.c:1148
int lifetime
Definition: recording.h:129
int FileSizeMB(void) const
Returns the total file size of this recording (in MB), or -1 if the file size is unknown.
Definition: recording.c:1361
cString BaseName(void) const
Returns the base name of this recording (without the video directory and folder).
Definition: recording.c:1051
char * fileName
Definition: recording.h:111
char * titleBuffer
Definition: recording.h:108
void SetDeleted(void)
Definition: recording.h:140
int Priority(void) const
Definition: recording.h:137
void ReadInfo(void)
Definition: recording.c:1183
const char * Title(char Delimiter=' ', bool NewIndicator=false, int Level=-1) const
Definition: recording.c:1076
int instanceId
Definition: recording.h:116
bool Remove(void)
Actually removes the file from the disk Returns false in case of error.
Definition: recording.c:1289
char * name
Definition: recording.h:112
cRecording(const cRecording &)
char * sortBufferTime
Definition: recording.h:110
int channel
Definition: recording.h:115
time_t start
Definition: recording.h:127
int numFrames
Definition: recording.h:114
double FramesPerSecond(void) const
Definition: recording.h:162
bool IsPesRecording(void) const
Definition: recording.h:176
static char * StripEpisodeName(char *s, bool Strip)
Definition: recording.c:953
int LengthInSeconds(void) const
Returns the length (in seconds) of this recording, or -1 in case of error.
Definition: recording.c:1353
void Cleanup(cRecordings *Recordings)
Definition: recording.c:1948
const char * FileNameDst(void) const
Definition: recording.c:1870
int Usage(const char *FileName=NULL) const
Definition: recording.c:1891
bool Active(cRecordings *Recordings)
Definition: recording.c:1903
const char * FileNameSrc(void) const
Definition: recording.c:1869
bool Error(void) const
Definition: recording.c:1867
cRecordingsHandlerEntry(int Usage, const char *FileNameSrc, const char *FileNameDst)
Definition: recording.c:1875
void DelAll(void)
Deletes/terminates all operations.
Definition: recording.c:2065
cRecordingsHandler(void)
Definition: recording.c:1977
cRecordingsHandlerEntry * Get(const char *FileName)
Definition: recording.c:2014
bool Add(int Usage, const char *FileNameSrc, const char *FileNameDst=NULL)
Adds the given FileNameSrc to the recordings handler for (later) processing.
Definition: recording.c:2027
bool Finished(bool &Error)
Returns true if all operations in the list have been finished.
Definition: recording.c:2080
virtual void Action(void)
A derived cThread class must implement the code it wants to execute as a separate thread in this func...
Definition: recording.c:1989
int GetUsage(const char *FileName)
Returns the usage type for the given FileName.
Definition: recording.c:2072
cList< cRecordingsHandlerEntry > operations
Definition: recording.h:319
void Del(const char *FileName)
Deletes the given FileName from the list of operations.
Definition: recording.c:2058
virtual ~cRecordingsHandler()
Definition: recording.c:1984
void ResetResume(const char *ResumeFileName=NULL)
Definition: recording.c:1675
void UpdateByName(const char *FileName)
Definition: recording.c:1597
static const char * UpdateFileName(void)
Definition: recording.c:1505
virtual ~cRecordings()
Definition: recording.c:1498
double MBperMinute(void) const
Returns the average data rate (in MB/min) of all recordings, or -1 if this value is unknown.
Definition: recording.c:1614
cRecordings(bool Deleted=false)
Definition: recording.c:1493
int GetNumRecordingsInPath(const char *Path) const
Returns the total number of recordings in the given Path, including all sub-folders of Path.
Definition: recording.c:1645
const cRecording * GetById(int Id) const
Definition: recording.c:1540
static time_t lastUpdate
Definition: recording.h:236
static cRecordings deletedRecordings
Definition: recording.h:233
void AddByName(const char *FileName, bool TriggerUpdate=true)
Definition: recording.c:1566
static cRecordings recordings
Definition: recording.h:232
int TotalFileSizeMB(void) const
Definition: recording.c:1603
static void Update(bool Wait=false)
Triggers an update of the list of recordings, which will run as a separate thread if Wait is false.
Definition: recording.c:1528
static void TouchUpdate(void)
Touches the '.update' file in the video directory, so that other instances of VDR that access the sam...
Definition: recording.c:1512
void Add(cRecording *Recording)
Definition: recording.c:1560
static cVideoDirectoryScannerThread * videoDirectoryScannerThread
Definition: recording.h:237
void DelByName(const char *FileName)
Definition: recording.c:1575
bool MoveRecordings(const char *OldPath, const char *NewPath)
Moves all recordings in OldPath to NewPath.
Definition: recording.c:1655
static bool NeedsUpdate(void)
Definition: recording.c:1520
void ClearSortNames(void)
Definition: recording.c:1683
static int lastRecordingId
Definition: recording.h:234
const cRecording * GetByName(const char *FileName) const
Definition: recording.c:1549
static char * updateFileName
Definition: recording.h:235
int PathIsInUse(const char *Path) const
Checks whether any recording in the given Path is currently in use and therefore the whole Path shall...
Definition: recording.c:1635
static bool HasKeys(void)
Definition: remote.c:175
virtual void Action(void)
A derived cThread class must implement the code it wants to execute as a separate thread in this func...
Definition: recording.c:95
static const char * NowReplaying(void)
Definition: menu.c:5789
bool isPesRecording
Definition: recording.h:59
bool Save(int Index)
Definition: recording.c:307
char * fileName
Definition: recording.h:58
int Read(void)
Definition: recording.c:262
void Delete(void)
Definition: recording.c:337
cResumeFile(const char *FileName, bool IsPesRecording)
Definition: recording.c:244
void Del(int Count)
Deletes at most Count bytes from the ring buffer.
Definition: ringbuffer.c:371
int Put(const uchar *Data, int Count)
Puts at most Count bytes of Data into the ring buffer.
Definition: ringbuffer.c:306
virtual int Available(void)
Definition: ringbuffer.c:211
virtual void Clear(void)
Immediately clears the ring buffer.
Definition: ringbuffer.c:217
uchar * Get(int &Count)
Gets data from the ring buffer.
Definition: ringbuffer.c:346
int Read(int FileHandle, int Max=0)
Reads at most Max bytes from FileHandle and stores them in the ring buffer.
Definition: ringbuffer.c:230
bool Open(void)
Definition: tools.c:1746
bool Close(void)
Definition: tools.c:1756
int ResumeID
Definition: config.h:357
int AlwaysSortFoldersFirst
Definition: config.h:311
int RecSortingDirection
Definition: config.h:313
int RecordingDirs
Definition: config.h:309
int UseSubtitle
Definition: config.h:306
int DefaultSortModeRec
Definition: config.h:312
int QueueMessage(eMessageType Type, const char *s, int Seconds=0, int Timeout=0)
Like Message(), but this function may be called from a background thread.
Definition: skins.c:296
void Remove(bool IncState=true)
Removes this key from the lock it was previously used with.
Definition: thread.c:859
Definition: tools.h:174
static cString sprintf(const char *fmt,...) __attribute__((format(printf
Definition: tools.c:1133
Definition: thread.h:79
void bool Start(void)
Sets the description of this thread, which will be used when logging starting or stopping of the thre...
Definition: thread.c:304
bool Running(void)
Returns false if a derived cThread object shall leave its Action() function.
Definition: thread.h:101
void Cancel(int WaitSeconds=0)
Cancels the thread by first setting 'running' to false, so that the Action() loop can finish in an or...
Definition: thread.c:354
bool Active(void)
Checks whether the thread is still alive.
Definition: thread.c:329
Definition: timers.h:27
bool IsSingleEvent(void) const
Definition: timers.c:361
void SetFile(const char *File)
Definition: timers.c:407
const char * Aux(void) const
Definition: timers.h:68
const char * File(void) const
Definition: timers.h:66
time_t StartTime(void) const
Definition: timers.c:523
int Priority(void) const
Definition: timers.h:64
int Lifetime(void) const
Definition: timers.h:65
const cChannel * Channel(void) const
Definition: timers.h:59
cUnbufferedFile is used for large files that are mainly written or read in a streaming manner,...
Definition: tools.h:461
static cUnbufferedFile * Create(const char *FileName, int Flags, mode_t Mode=DEFFILEMODE)
Definition: tools.c:1972
int Close(void)
Definition: tools.c:1820
ssize_t Read(void *Data, size_t Size)
Definition: tools.c:1863
off_t Seek(off_t Offset, int Whence)
Definition: tools.c:1855
cRecordings * deletedRecordings
Definition: recording.c:1377
void ScanVideoDir(const char *DirName, int LinkLevel=0, int DirLevel=0)
Definition: recording.c:1415
cVideoDirectoryScannerThread(cRecordings *Recordings, cRecordings *DeletedRecordings)
Definition: recording.c:1388
virtual void Action(void)
A derived cThread class must implement the code it wants to execute as a separate thread in this func...
Definition: recording.c:1402
static cString PrefixVideoFileName(const char *FileName, char Prefix)
Definition: videodir.c:164
static void RemoveEmptyVideoDirectories(const char *IgnoreFiles[]=NULL)
Definition: videodir.c:184
static bool IsOnVideoDirectoryFileSystem(const char *FileName)
Definition: videodir.c:189
static const char * Name(void)
Definition: videodir.c:60
static cUnbufferedFile * OpenVideoFile(const char *FileName, int Flags)
Definition: videodir.c:120
static bool VideoFileSpaceAvailable(int SizeMB)
Definition: videodir.c:142
static bool MoveVideoFile(const char *FromName, const char *ToName)
Definition: videodir.c:132
static bool RenameVideoFile(const char *OldName, const char *NewName)
Definition: videodir.c:127
static bool RemoveVideoFile(const char *FileName)
Definition: videodir.c:137
cSetup Setup
Definition: config.c:372
#define MAXLIFETIME
Definition: config.h:44
#define MAXPRIORITY
Definition: config.h:39
#define TIMERMACRO_EPISODE
Definition: config.h:48
#define TIMERMACRO_TITLE
Definition: config.h:47
#define tr(s)
Definition: i18n.h:85
static int Utf8CharLen(const char *s)
Definition: si.c:400
#define MAXFILESPERRECORDINGTS
Definition: recording.c:2893
#define NAMEFORMATPES
Definition: recording.c:48
int DirectoryNameMax
Definition: recording.c:77
tCharExchange CharExchange[]
Definition: recording.c:570
cString GetRecordingTimerId(const char *Directory)
Definition: recording.c:3160
bool GenerateIndex(const char *FileName, bool Update)
Generates the index of the existing recording with the given FileName.
Definition: recording.c:2861
#define REMOVELATENCY
Definition: recording.c:67
cString IndexToHMSF(int Index, bool WithFrame, double FramesPerSecond)
Definition: recording.c:3055
#define MININDEXAGE
Definition: recording.c:69
char * ExchangeChars(char *s, bool ToFileSystem)
Definition: recording.c:590
#define MINDISKSPACE
Definition: recording.c:62
#define INFOFILESUFFIX
Definition: recording.c:56
void AssertFreeDiskSpace(int Priority, bool Force)
The special Priority value -1 means that we shall get rid of any deleted recordings faster than norma...
Definition: recording.c:154
#define DELETEDLIFETIME
Definition: recording.c:65
#define REMOVECHECKDELTA
Definition: recording.c:64
int DirectoryPathMax
Definition: recording.c:76
void GetRecordingsSortMode(const char *Directory)
Definition: recording.c:3112
#define MARKSFILESUFFIX
Definition: recording.c:57
#define MAX_LINK_LEVEL
Definition: recording.c:72
#define DATAFORMATPES
Definition: recording.c:47
bool NeedsConversion(const char *p)
Definition: recording.c:583
int SecondsToFrames(int Seconds, double FramesPerSecond)
Definition: recording.c:3082
#define MAXREMOVETIME
Definition: recording.c:70
eRecordingsSortMode RecordingsSortMode
Definition: recording.c:3105
bool HasRecordingsSortMode(const char *Directory)
Definition: recording.c:3107
#define RECEXT
Definition: recording.c:36
#define MAXFILESPERRECORDINGPES
Definition: recording.c:2891
#define INDEXCATCHUPWAIT
Definition: recording.c:2507
#define INDEXFILESUFFIX
Definition: recording.c:2503
#define IFG_BUFFER_SIZE
Definition: recording.c:2329
#define INDEXFILETESTINTERVAL
Definition: recording.c:2532
#define MAXWAITFORINDEXFILE
Definition: recording.c:2530
int InstanceId
Definition: recording.c:79
#define DELEXT
Definition: recording.c:37
#define INDEXFILECHECKINTERVAL
Definition: recording.c:2531
bool DirectoryEncoding
Definition: recording.c:78
void IncRecordingsSortMode(const char *Directory)
Definition: recording.c:3131
int HMSFToIndex(const char *HMSF, double FramesPerSecond)
Definition: recording.c:3071
#define LIMIT_SECS_PER_MB_RADIO
Definition: recording.c:74
void SetRecordingsSortMode(const char *Directory, eRecordingsSortMode SortMode)
Definition: recording.c:3123
static cRemoveDeletedRecordingsThread RemoveDeletedRecordingsThread
Definition: recording.c:133
#define DISKCHECKDELTA
Definition: recording.c:66
int ReadFrame(cUnbufferedFile *f, uchar *b, int Length, int Max)
Definition: recording.c:3089
cRecordingsHandler RecordingsHandler
Definition: recording.c:1975
cMutex MutexMarkFramesPerSecond
Definition: recording.c:2095
struct __attribute__((packed))
Definition: recording.c:2509
#define RESUME_NOT_INITIALIZED
Definition: recording.c:567
#define SORTMODEFILE
Definition: recording.c:59
#define RECORDFILESUFFIXLEN
Definition: recording.c:2895
#define MAXINDEXCATCHUP
Definition: recording.c:2506
#define NAMEFORMATTS
Definition: recording.c:50
#define DATAFORMATTS
Definition: recording.c:49
#define RECORDFILESUFFIXPES
Definition: recording.c:2892
void SetRecordingTimerId(const char *Directory, const char *TimerId)
Definition: recording.c:3142
#define TIMERRECFILE
Definition: recording.c:60
#define RECORDFILESUFFIXTS
Definition: recording.c:2894
char * LimitNameLengths(char *s, int PathMax, int NameMax)
Definition: recording.c:661
double MarkFramesPerSecond
Definition: recording.c:2094
const char * InvalidChars
Definition: recording.c:581
void RemoveDeletedRecordings(void)
Definition: recording.c:137
#define RESUMEFILESUFFIX
Definition: recording.c:52
#define SUMMARYFILESUFFIX
Definition: recording.c:54
@ ruSrc
Definition: recording.h:37
@ ruCut
Definition: recording.h:33
@ ruReplay
Definition: recording.h:31
@ ruCopy
Definition: recording.h:35
@ ruCanceled
Definition: recording.h:41
@ ruTimer
Definition: recording.h:30
@ ruDst
Definition: recording.h:38
@ ruNone
Definition: recording.h:29
@ ruMove
Definition: recording.h:34
@ ruPending
Definition: recording.h:40
eRecordingsSortMode
Definition: recording.h:534
@ rsmName
Definition: recording.h:534
@ rsmTime
Definition: recording.h:534
#define DEFAULTFRAMESPERSECOND
Definition: recording.h:354
@ rsdAscending
Definition: recording.h:533
#define LOCK_DELETEDRECORDINGS_WRITE
Definition: recording.h:312
#define FOLDERDELIMCHAR
Definition: recording.h:21
#define RUC_DELETERECORDING
Definition: recording.h:428
#define LOCK_DELETEDRECORDINGS_READ
Definition: recording.h:311
#define LOCK_RECORDINGS_WRITE
Definition: recording.h:310
int TsPid(const uchar *p)
Definition: remux.h:87
#define PATPID
Definition: remux.h:52
#define TS_SIZE
Definition: remux.h:34
#define TS_SYNC_BYTE
Definition: remux.h:33
#define MIN_TS_PACKETS_FOR_FRAME_DETECTOR
Definition: remux.h:509
cSkins Skins
Definition: skins.c:219
@ mtWarning
Definition: skins.h:37
@ mtInfo
Definition: skins.h:37
@ mtError
Definition: skins.h:37
static const tChannelID InvalidID
Definition: channels.h:70
bool Valid(void) const
Definition: channels.h:60
static tChannelID FromString(const char *s)
Definition: channels.c:24
cString ToString(void) const
Definition: channels.c:41
Definition: epg.h:42
char language[MAXLANGCODE2]
Definition: epg.h:45
int SystemExec(const char *Command, bool Detached)
Definition: thread.c:1034
void TouchFile(const char *FileName)
Definition: tools.c:701
bool isempty(const char *s)
Definition: tools.c:333
cString strescape(const char *s, const char *chars)
Definition: tools.c:256
bool MakeDirs(const char *FileName, bool IsDirectory)
Definition: tools.c:483
cString dtoa(double d, const char *Format)
Converts the given double value to a string, making sure it uses a '.
Definition: tools.c:416
time_t LastModifiedTime(const char *FileName)
Definition: tools.c:707
double atod(const char *s)
Converts the given string, which is a floating point number using a '.
Definition: tools.c:395
char * strreplace(char *s, char c1, char c2)
Definition: tools.c:139
ssize_t safe_read(int filedes, void *buffer, size_t size)
Definition: tools.c:53
char * stripspace(char *s)
Definition: tools.c:203
ssize_t safe_write(int filedes, const void *buffer, size_t size)
Definition: tools.c:65
int DirSizeMB(const char *DirName)
returns the total size of the files in the given directory, or -1 in case of an error
Definition: tools.c:623
bool DirectoryOk(const char *DirName, bool LogErrors)
Definition: tools.c:465
char * strn0cpy(char *dest, const char *src, size_t n)
Definition: tools.c:131
char * compactspace(char *s)
Definition: tools.c:215
off_t FileSize(const char *FileName)
returns the size of the given file, or -1 in case of an error (e.g. if the file doesn't exist)
Definition: tools.c:715
bool endswith(const char *s, const char *p)
Definition: tools.c:322
cString itoa(int n)
Definition: tools.c:426
cString AddDirectory(const char *DirName, const char *FileName)
Definition: tools.c:386
void writechar(int filedes, char c)
Definition: tools.c:85
T constrain(T v, T l, T h)
Definition: tools.h:66
char * skipspace(const char *s)
Definition: tools.h:207
#define SECSINDAY
Definition: tools.h:42
#define LOG_ERROR_STR(s)
Definition: tools.h:40
unsigned char uchar
Definition: tools.h:31
#define dsyslog(a...)
Definition: tools.h:37
#define MALLOC(type, size)
Definition: tools.h:47
bool DoubleEqual(double a, double b)
Definition: tools.h:93
void swap(T &a, T &b)
Definition: tools.h:63
T max(T a, T b)
Definition: tools.h:59
#define esyslog(a...)
Definition: tools.h:35
#define LOG_ERROR
Definition: tools.h:39
#define isyslog(a...)
Definition: tools.h:36
#define KILOBYTE(n)
Definition: tools.h:44