vdr 2.8.3
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 5.64 2026/09/07 18:48:24 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 "ringbuffer.h"
28#include "skins.h"
29#include "svdrp.h"
30#include "tools.h"
31#include "videodir.h"
32
33#define SUMMARYFALLBACK
34
35#define RECEXT ".rec"
36#define DELEXT ".del"
37/* This was the original code, which works fine in a Linux only environment.
38 Unfortunately, because of Windows and its brain dead file system, we have
39 to use a more complicated approach, in order to allow users who have enabled
40 the --vfat command line option to see their recordings even if they forget to
41 enable --vfat when restarting VDR... Gee, do I hate Windows.
42 (kls 2002-07-27)
43#define DATAFORMAT "%4d-%02d-%02d.%02d:%02d.%02d.%02d" RECEXT
44#define NAMEFORMAT "%s/%s/" DATAFORMAT
45*/
46#define DATAFORMATPES "%4d-%02d-%02d.%02d%*c%02d.%02d.%02d" RECEXT
47#define NAMEFORMATPES "%s/%s/" "%4d-%02d-%02d.%02d.%02d.%02d.%02d" RECEXT
48#define DATAFORMATTS "%4d-%02d-%02d.%02d.%02d.%d-%d" RECEXT
49#define NAMEFORMATTS "%s/%s/" DATAFORMATTS
50
51#define RESUMEFILESUFFIX "/resume%s%s"
52#ifdef SUMMARYFALLBACK
53#define SUMMARYFILESUFFIX "/summary.vdr"
54#endif
55#define INFOFILESUFFIX "/info"
56#define MARKSFILESUFFIX "/marks"
57
58#define SORTMODEFILE ".sort"
59#define TIMERRECFILE ".timer"
60
61#define MINDISKSPACE 1024 // MB
62
63#define REMOVECHECKDELTA 60 // seconds between checks for removing deleted files
64#define DELETEDLIFETIME 300 // seconds after which a deleted recording will be actually removed
65#define DISKCHECKDELTA 100 // seconds between checks for free disk space
66#define REMOVELATENCY 10 // seconds to wait until next check after removing a file
67#define MARKSUPDATEDELTA 10 // seconds between checks for updating editing marks
68#define MAXREMOVETIME 10 // seconds after which to return from removing deleted recordings
69
70#define MAX_LINK_LEVEL 6
71
72#define LIMIT_SECS_PER_MB_RADIO 5 // radio recordings typically have more than this
73
74int DirectoryPathMax = PATH_MAX - 1;
75int DirectoryNameMax = NAME_MAX;
76bool DirectoryEncoding = false;
77int InstanceId = 0;
78
79// --- cRemoveDeletedRecordingsThread ----------------------------------------
80
82protected:
83 virtual void Action(void) override;
84public:
86 };
87
89:cThread("remove deleted recordings", true)
90{
91}
92
94{
95 // Make sure only one instance of VDR does this:
97 if (LockFile.Lock()) {
98 time_t StartTime = time(NULL);
99 bool deleted = false;
100 bool interrupted = false;
102 for (cRecording *r = DeletedRecordings->First(); r; ) {
104 interrupted = true;
105 else if (time(NULL) - StartTime > MAXREMOVETIME)
106 interrupted = true; // don't stay here too long
107 else if (cRemote::HasKeys())
108 interrupted = true; // react immediately on user input
109 if (interrupted)
110 break;
111 if (r->RetentionExpired()) {
112 cRecording *next = DeletedRecordings->Next(r);
113 r->Remove();
114 DeletedRecordings->Del(r);
115 r = next;
116 deleted = true;
117 }
118 else
119 r = DeletedRecordings->Next(r);
120 }
121 if (deleted) {
123 if (!interrupted) {
124 const char *IgnoreFiles[] = { SORTMODEFILE, TIMERRECFILE, NULL };
126 }
127 }
128 }
129}
130
132
133// ---
134
136{
137 static time_t LastRemoveCheck = 0;
138 if (time(NULL) - LastRemoveCheck > REMOVECHECKDELTA) {
141 for (const cRecording *r = DeletedRecordings->First(); r; r = DeletedRecordings->Next(r)) {
142 if (r->RetentionExpired()) {
144 break;
145 }
146 }
147 }
148 LastRemoveCheck = time(NULL);
149 }
150}
151
152void AssertFreeDiskSpace(int Priority, bool Force)
153{
154 static cMutex Mutex;
155 cMutexLock MutexLock(&Mutex);
156 // With every call to this function we try to actually remove
157 // a file, or mark a file for removal ("delete" it), so that
158 // it will get removed during the next call.
159 static time_t LastFreeDiskCheck = 0;
160 int Factor = (Priority == -1) ? 10 : 1;
161 if (Force || time(NULL) - LastFreeDiskCheck > DISKCHECKDELTA / Factor) {
163 // Make sure only one instance of VDR does this:
165 if (!LockFile.Lock())
166 return;
167 // Remove the oldest file that has been "deleted":
168 isyslog("low disk space while recording, trying to remove a deleted recording...");
169 int NumDeletedRecordings = 0;
170 {
172 NumDeletedRecordings = DeletedRecordings->Count();
173 if (NumDeletedRecordings) {
174 cRecording *r = DeletedRecordings->First();
175 cRecording *r0 = NULL;
176 while (r) {
177 if (r->IsOnVideoDirectoryFileSystem()) { // only remove recordings that will actually increase the free video disk space
178 if (!r0 || r->Deleted() < r0->Deleted())
179 r0 = r;
180 }
181 r = DeletedRecordings->Next(r);
182 }
183 if (r0) {
184 if (r0->Remove())
185 LastFreeDiskCheck += REMOVELATENCY / Factor;
186 DeletedRecordings->Del(r0);
187 return;
188 }
189 }
190 }
191 if (NumDeletedRecordings == 0) {
192 // DeletedRecordings was empty, so to be absolutely sure there are no
193 // deleted recordings we need to double check:
196 if (DeletedRecordings->Count())
197 return; // the next call will actually remove it
198 }
199 // No "deleted" files to remove, so let's see if we can delete a recording:
200 if (Priority > 0) {
201 isyslog("...no deleted recording found, trying to delete an old recording...");
203 Recordings->SetExplicitModify();
204 if (Recordings->Count()) {
205 cRecording *r = Recordings->First();
206 cRecording *r0 = NULL;
207 while (r) {
208 if (r->IsOnVideoDirectoryFileSystem()) { // only delete recordings that will actually increase the free video disk space
209 if (!r->IsEdited() && r->Lifetime() < MAXLIFETIME) { // edited recordings and recordings with MAXLIFETIME live forever
210 if ((r->Lifetime() == 0 && Priority > r->Priority()) || // the recording has no guaranteed lifetime and the new recording has higher priority
211 (r->Lifetime() > 0 && (time(NULL) - r->Start()) / SECSINDAY >= r->Lifetime())) { // the recording's guaranteed lifetime has expired
212 if (r0) {
213 if (r->Priority() < r0->Priority() || (r->Priority() == r0->Priority() && r->Start() < r0->Start()))
214 r0 = r; // in any case we delete the one with the lowest priority (or the older one in case of equal priorities)
215 }
216 else
217 r0 = r;
218 }
219 }
220 }
221 r = Recordings->Next(r);
222 }
223 if (r0 && r0->Delete()) {
224 Recordings->Del(r0);
225 Recordings->SetModified();
226 return;
227 }
228 }
229 // Unable to free disk space, but there's nothing we can do about that...
230 isyslog("...no old recording found, giving up");
231 }
232 else
233 isyslog("...no deleted recording found, priority %d too low to trigger deleting an old recording", Priority);
234 Skins.QueueMessage(mtWarning, tr("Low disk space!"), 5, -1);
235 }
236 LastFreeDiskCheck = time(NULL);
237 }
238}
239
240// --- cResumeFile -----------------------------------------------------------
241
242#define RESUME_NOT_INITIALIZED (-2)
243
244cResumeFile::cResumeFile(const char *FileName, bool IsPesRecording)
245{
246 fileName = NULL;
247 fileTime = 0;
249 isPesRecording = IsPesRecording;
250 SetFileName(FileName);
251}
252
254{
255 free(fileName);
256}
257
258void cResumeFile::SetFileName(const char *FileName)
259{
260 const char *Suffix = isPesRecording ? RESUMEFILESUFFIX ".vdr" : RESUMEFILESUFFIX;
261 free(fileName);
262 fileName = MALLOC(char, strlen(FileName) + strlen(Suffix) + 1);
263 if (fileName) {
264 strcpy(fileName, FileName);
265 sprintf(fileName + strlen(fileName), Suffix, Setup.ResumeID ? "." : "", Setup.ResumeID ? *itoa(Setup.ResumeID) : "");
266 }
267 else
268 esyslog("ERROR: can't allocate memory for resume file name");
269 Reset(); // for safety
270}
271
273{
274 if (index == RESUME_NOT_INITIALIZED) // checking index is OK, Read() sets index AND fileTime!
275 Read();
276 return fileTime;
277}
278
280{
282 Read();
283 return index;
284}
285
287{
288 int resume = -1;
289 if (fileName) {
290 struct stat st;
291 if (stat(fileName, &st) == 0) {
292 fileTime = st.st_mtime;
293 if ((st.st_mode & S_IWUSR) == 0) // no write access, assume no resume
294 return -1;
295 }
296 if (isPesRecording) {
297 int f = open(fileName, O_RDONLY);
298 if (f >= 0) {
299 if (safe_read(f, &resume, sizeof(resume)) != sizeof(resume)) {
300 resume = -1;
302 }
303 close(f);
304 }
305 else if (errno != ENOENT)
307 }
308 else {
309 FILE *f = fopen(fileName, "r");
310 if (f) {
311 cReadLine ReadLine;
312 char *s;
313 while ((s = ReadLine.Read(f)) != NULL) {
314 char *t = skipspace(s + 1);
315 switch (*s) {
316 case 'I': resume = atoi(t);
317 break;
318 default: ;
319 }
320 }
321 fclose(f);
322 }
323 else if (errno != ENOENT)
325 }
326 }
327 index = resume;
328 return resume;
329}
330
332{
333 if (fileName) {
334 if (isPesRecording) {
335 int f = open(fileName, O_WRONLY | O_CREAT | O_TRUNC, DEFFILEMODE);
336 if (f >= 0) {
337 if (safe_write(f, &Index, sizeof(Index)) < 0)
339 close(f);
340 }
341 else
342 return false;
343 }
344 else {
345 FILE *f = fopen(fileName, "w");
346 if (f) {
347 fprintf(f, "I %d\n", Index);
348 fclose(f);
349 }
350 else {
352 return false;
353 }
354 }
355 // Not using LOCK_RECORDINGS_WRITE here, because we might already hold a lock in cRecordingsHandler::Action()
356 // and end up here if an editing process is canceled while the edited recording is being replayed. The worst
357 // that can happen if we don't get this lock here is that the resume info in the Recordings list is not updated,
358 // but that doesn't matter because the recording is deleted, anyway.
359 cStateKey StateKey;
360 if (cRecordings *Recordings = cRecordings::GetRecordingsWrite(StateKey, 1)) {
361 Recordings->ResetResume(fileName);
362 StateKey.Remove();
363 }
364 fileTime = time(NULL);
365 index = Index;
366 return true;
367 }
368 return false;
369}
370
375
377{
378 if (fileName) {
379 if (remove(fileName) == 0) {
381 Recordings->ResetResume(fileName);
382 }
383 else if (errno != ENOENT)
385 }
386}
387
388// --- cRecordingInfo --------------------------------------------------------
389
390cRecordingInfo::cRecordingInfo(const cChannel *Channel, const cEvent *Event)
391{
392 modified = 0;
393 channelID = Channel ? Channel->GetChannelID() : tChannelID::InvalidID;
394 channelName = Channel ? strdup(Channel->Name()) : NULL;
395 ownEvent = Event ? NULL : new cEvent(0);
396 event = ownEvent ? ownEvent : Event;
397 aux = NULL;
399 frameWidth = 0;
400 frameHeight = 0;
405 fileName = NULL;
406 errors = -1;
407 if (Channel) {
408 // Since the EPG data's component records can carry only a single
409 // language code, let's see whether the channel's PID data has
410 // more information:
412 if (!Components)
414 for (int i = 0; i < MAXAPIDS; i++) {
415 const char *s = Channel->Alang(i);
416 if (*s) {
417 tComponent *Component = Components->GetComponent(i, 2, 3);
418 if (!Component)
420 else if (strlen(s) > strlen(Component->language))
421 strn0cpy(Component->language, s, sizeof(Component->language));
422 }
423 }
424 // There's no "multiple languages" for Dolby Digital tracks, but
425 // we do the same procedure here, too, in case there is no component
426 // information at all:
427 for (int i = 0; i < MAXDPIDS; i++) {
428 const char *s = Channel->Dlang(i);
429 if (*s) {
430 tComponent *Component = Components->GetComponent(i, 4, 0); // AC3 component according to the DVB standard
431 if (!Component)
432 Component = Components->GetComponent(i, 2, 5); // fallback "Dolby" component according to the "Premiere pseudo standard"
433 if (!Component)
435 else if (strlen(s) > strlen(Component->language))
436 strn0cpy(Component->language, s, sizeof(Component->language));
437 }
438 }
439 // The same applies to subtitles:
440 for (int i = 0; i < MAXSPIDS; i++) {
441 const char *s = Channel->Slang(i);
442 if (*s) {
443 tComponent *Component = Components->GetComponent(i, 3, 3);
444 if (!Component)
446 else if (strlen(s) > strlen(Component->language))
447 strn0cpy(Component->language, s, sizeof(Component->language));
448 }
449 }
450 if (Components != event->Components())
451 ((cEvent *)event)->SetComponents(Components);
452 }
453}
454
456{
457 modified = 0;
459 channelName = NULL;
460 ownEvent = new cEvent(0);
461 event = ownEvent;
462 aux = NULL;
463 errors = -1;
464 tmpErrors = 0;
466 frameWidth = 0;
467 frameHeight = 0;
472 fileName = strdup(cString::sprintf("%s%s", FileName, INFOFILESUFFIX));
473}
474
476{
477 delete ownEvent;
478 free(aux);
479 free(channelName);
480 free(fileName);
481}
482
483void cRecordingInfo::SetData(const char *Title, const char *ShortText, const char *Description)
484{
485 if (Title)
487 if (ShortText)
489 if (Description)
491}
492
494{
495 free(aux);
496 aux = Aux ? strdup(Aux) : NULL;
497}
498
503
508
513
515{
516 ((cEvent *)event)->SetTitle(Title);
517}
518
520{
521 ((cEvent *)event)->SetShortText(ShortText);
522}
523
525{
526 ((cEvent *)event)->SetDescription(Description);
527}
528
530{
531 ((cEvent *)event)->SetParentalRating(ParentalRating);
532}
533
541
542void cRecordingInfo::SetFileName(const char *FileName)
543{
544 bool IsPesRecording = fileName && endswith(fileName, ".vdr");
545 free(fileName);
546 fileName = strdup(cString::sprintf("%s%s", FileName, IsPesRecording ? INFOFILESUFFIX ".vdr" : INFOFILESUFFIX));
547}
548
554
555bool cRecordingInfo::Read(FILE *f, bool Force)
556{
557 if (ownEvent) {
558 struct stat st;
559 if (fstat(fileno(f), &st))
560 return false;
561 if (modified == st.st_mtime && !Force)
562 return true;
563 if (modified) {
564 delete ownEvent;
565 event = ownEvent = new cEvent(0);
566 }
567 modified = st.st_mtime;
568 cReadLine ReadLine;
569 char *s;
570 int line = 0;
571 while ((s = ReadLine.Read(f)) != NULL) {
572 ++line;
573 char *t = skipspace(s + 1);
574 switch (*s) {
575 case 'C': {
576 char *p = strchr(t, ' ');
577 if (p) {
578 free(channelName);
579 channelName = strdup(compactspace(p));
580 *p = 0; // strips optional channel name
581 }
582 if (*t)
584 }
585 break;
586 case 'E': {
587 unsigned int EventID;
588 intmax_t StartTime; // actually time_t, but intmax_t for scanning with "%jd"
589 int Duration;
590 unsigned int TableID = 0;
591 unsigned int Version = 0xFF;
592 int n = sscanf(t, "%u %jd %d %X %X", &EventID, &StartTime, &Duration, &TableID, &Version);
593 if (n >= 3 && n <= 5) {
594 ownEvent->SetEventID(EventID);
595 ownEvent->SetStartTime(StartTime);
596 ownEvent->SetDuration(Duration);
597 ownEvent->SetTableID(uchar(TableID));
598 ownEvent->SetVersion(uchar(Version));
599 ownEvent->SetComponents(NULL);
600 }
601 }
602 break;
603 case 'F': {
604 char *fpsBuf = NULL;
605 char scanTypeCode;
606 char *arBuf = NULL;
607 int n = sscanf(t, "%m[^ ] %hu %hu %c %m[^\n]", &fpsBuf, &frameWidth, &frameHeight, &scanTypeCode, &arBuf);
608 if (n >= 1) {
609 framesPerSecond = atod(fpsBuf);
610 if (n >= 4) {
612 for (int st = stUnknown + 1; st < stMax; st++) {
613 if (ScanTypeChars[st] == scanTypeCode) {
614 scanType = eScanType(st);
615 break;
616 }
617 }
619 if (n == 5) {
620 for (int ar = arUnknown + 1; ar < arMax; ar++) {
621 if (strcmp(arBuf, AspectRatioTexts[ar]) == 0) {
623 break;
624 }
625 }
626 }
627 }
628 }
629 free(fpsBuf);
630 free(arBuf);
631 }
632 break;
633 case 'L': lifetime = atoi(t);
634 break;
635 case 'P': priority = atoi(t);
636 break;
637 case 'O': errors = atoi(t);
638 if (t = strchr(t, ' '))
639 tmpErrors = atoi(t);
640 else
641 tmpErrors = 0;
642 break;
643 case '@': free(aux);
644 aux = strdup(t);
645 break;
646 case '#': break; // comments are ignored
647 default: if (!ownEvent->Parse(s)) {
648 esyslog("ERROR: EPG data problem in line %d", line);
649 return false;
650 }
651 break;
652 }
653 }
654 return true;
655 }
656 return false;
657}
658
659bool cRecordingInfo::Write(FILE *f, const char *Prefix) const
660{
661 if (channelID.Valid())
662 fprintf(f, "%sC %s%s%s\n", Prefix, *channelID.ToString(), channelName ? " " : "", channelName ? channelName : "");
663 event->Dump(f, Prefix, true);
664 if (frameWidth > 0 && frameHeight > 0)
665 fprintf(f, "%sF %s %s %s %c %s\n", Prefix, *dtoa(framesPerSecond, "%.10g"), *itoa(frameWidth), *itoa(frameHeight), ScanTypeChars[scanType], AspectRatioTexts[aspectRatio]);
666 else
667 fprintf(f, "%sF %s\n", Prefix, *dtoa(framesPerSecond, "%.10g"));
668 fprintf(f, "%sP %d\n", Prefix, priority);
669 fprintf(f, "%sL %d\n", Prefix, lifetime);
670 fprintf(f, "%sO %d", Prefix, errors);
671 if (tmpErrors)
672 fprintf(f, " %d", tmpErrors);
673 fprintf(f, "\n");
674 if (aux)
675 fprintf(f, "%s@ %s\n", Prefix, aux);
676 return true;
677}
678
679bool cRecordingInfo::Read(bool Force)
680{
681 bool Result = false;
682 if (fileName) {
683 FILE *f = fopen(fileName, "r");
684 if (f) {
685 if (Read(f, Force))
686 Result = true;
687 else
688 esyslog("ERROR: EPG data problem in file %s", fileName);
689 fclose(f);
690 }
691 else if (errno != ENOENT)
693 }
694 return Result;
695}
696
697bool cRecordingInfo::Write(void) const
698{
699 bool Result = false;
700 if (fileName) {
702 if (f.Open()) {
703 if (Write(f))
704 Result = true;
705 f.Close();
706 }
707 else
709 }
710 return Result;
711}
712
714{
715 cString s;
716 if (frameWidth && frameHeight) {
718 if (framesPerSecond > 0) {
719 if (*s)
720 s.Append("/");
721 s.Append(dtoa(framesPerSecond, "%.2g"));
722 if (scanType != stUnknown)
723 s.Append(ScanTypeChar());
724 }
725 if (aspectRatio != arUnknown) {
726 if (*s)
727 s.Append(" ");
729 }
730 }
731 return s;
732}
733
734// --- cRecording ------------------------------------------------------------
735
736struct tCharExchange { char a; char b; };
738 { FOLDERDELIMCHAR, '/' },
739 { '/', FOLDERDELIMCHAR },
740 { ' ', '_' },
741 // backwards compatibility:
742 { '\'', '\'' },
743 { '\'', '\x01' },
744 { '/', '\x02' },
745 { 0, 0 }
746 };
747
748const char *InvalidChars = "\"\\/:*?|<>#";
749
750bool NeedsConversion(const char *p)
751{
752 return DirectoryEncoding &&
753 (strchr(InvalidChars, *p) // characters that can't be part of a Windows file/directory name
754 || *p == '.' && (!*(p + 1) || *(p + 1) == FOLDERDELIMCHAR)); // Windows can't handle '.' at the end of file/directory names
755}
756
757char *ExchangeChars(char *s, bool ToFileSystem)
758{
759 char *p = s;
760 while (*p) {
761 if (DirectoryEncoding) {
762 // Some file systems can't handle all characters, so we
763 // have to take extra efforts to encode/decode them:
764 if (ToFileSystem) {
765 switch (*p) {
766 // characters that can be mapped to other characters:
767 case ' ': *p = '_'; break;
768 case FOLDERDELIMCHAR: *p = '/'; break;
769 case '/': *p = FOLDERDELIMCHAR; break;
770 // characters that have to be encoded:
771 default:
772 if (NeedsConversion(p)) {
773 int l = p - s;
774 if (char *NewBuffer = (char *)realloc(s, strlen(s) + 10)) {
775 s = NewBuffer;
776 p = s + l;
777 char buf[4];
778 sprintf(buf, "#%02X", (unsigned char)*p);
779 memmove(p + 2, p, strlen(p) + 1);
780 memcpy(p, buf, 3);
781 p += 2;
782 }
783 else
784 esyslog("ERROR: out of memory");
785 }
786 }
787 }
788 else {
789 switch (*p) {
790 // mapped characters:
791 case '_': *p = ' '; break;
792 case FOLDERDELIMCHAR: *p = '/'; break;
793 case '/': *p = FOLDERDELIMCHAR; break;
794 // encoded characters:
795 case '#': {
796 if (strlen(p) > 2 && isxdigit(*(p + 1)) && isxdigit(*(p + 2))) {
797 char buf[3];
798 sprintf(buf, "%c%c", *(p + 1), *(p + 2));
799 uchar c = uchar(strtol(buf, NULL, 16));
800 if (c) {
801 *p = c;
802 memmove(p + 1, p + 3, strlen(p) - 2);
803 }
804 }
805 }
806 break;
807 // backwards compatibility:
808 case '\x01': *p = '\''; break;
809 case '\x02': *p = '/'; break;
810 case '\x03': *p = ':'; break;
811 default: ;
812 }
813 }
814 }
815 else {
816 for (struct tCharExchange *ce = CharExchange; ce->a && ce->b; ce++) {
817 if (*p == (ToFileSystem ? ce->a : ce->b)) {
818 *p = ToFileSystem ? ce->b : ce->a;
819 break;
820 }
821 }
822 }
823 p++;
824 }
825 return s;
826}
827
828char *LimitNameLengths(char *s, int PathMax, int NameMax)
829{
830 // Limits the total length of the directory path in 's' to PathMax, and each
831 // individual directory name to NameMax. The lengths of characters that need
832 // conversion when using 's' as a file name are taken into account accordingly.
833 // If a directory name exceeds NameMax, it will be truncated. If the whole
834 // directory path exceeds PathMax, individual directory names will be shortened
835 // (from right to left) until the limit is met, or until the currently handled
836 // directory name consists of only a single character. All operations are performed
837 // directly on the given 's', which may become shorter (but never longer) than
838 // the original value.
839 // Returns a pointer to 's'.
840 int Length = strlen(s);
841 int PathLength = 0;
842 // Collect the resulting lengths of each character:
843 bool NameTooLong = false;
844 int8_t a[Length];
845 int n = 0;
846 int NameLength = 0;
847 for (char *p = s; *p; p++) {
848 if (*p == FOLDERDELIMCHAR) {
849 a[n] = -1; // FOLDERDELIMCHAR is a single character, neg. sign marks it
850 NameTooLong |= NameLength > NameMax;
851 NameLength = 0;
852 PathLength += 1;
853 }
854 else if (NeedsConversion(p)) {
855 a[n] = 3; // "#xx"
856 NameLength += 3;
857 PathLength += 3;
858 }
859 else {
860 int8_t l = Utf8CharLen(p);
861 a[n] = l;
862 NameLength += l;
863 PathLength += l;
864 while (l-- > 1) {
865 a[++n] = 0;
866 p++;
867 }
868 }
869 n++;
870 }
871 NameTooLong |= NameLength > NameMax;
872 // Limit names to NameMax:
873 if (NameTooLong) {
874 while (n > 0) {
875 // Calculate the length of the current name:
876 int NameLength = 0;
877 int i = n;
878 int b = i;
879 while (i-- > 0 && a[i] >= 0) {
880 NameLength += a[i];
881 b = i;
882 }
883 // Shorten the name if necessary:
884 if (NameLength > NameMax) {
885 int l = 0;
886 i = n;
887 while (i-- > 0 && a[i] >= 0) {
888 l += a[i];
889 if (NameLength - l <= NameMax) {
890 memmove(s + i, s + n, Length - n + 1);
891 memmove(a + i, a + n, Length - n + 1);
892 Length -= n - i;
893 PathLength -= l;
894 break;
895 }
896 }
897 }
898 // Switch to the next name:
899 n = b - 1;
900 }
901 }
902 // Limit path to PathMax:
903 n = Length;
904 while (PathLength > PathMax && n > 0) {
905 // Calculate how much to cut off the current name:
906 int i = n;
907 int b = i;
908 int l = 0;
909 while (--i > 0 && a[i - 1] >= 0) {
910 if (a[i] > 0) {
911 l += a[i];
912 b = i;
913 if (PathLength - l <= PathMax)
914 break;
915 }
916 }
917 // Shorten the name if necessary:
918 if (l > 0) {
919 memmove(s + b, s + n, Length - n + 1);
920 Length -= n - b;
921 PathLength -= l;
922 }
923 // Switch to the next name:
924 n = i - 1;
925 }
926 return s;
927}
928
930{
931 id = 0;
932 resume = NULL;
933 titleBuffer = NULL;
935 fileName = NULL;
936 name = NULL;
937 fileSizeMB = -1; // unknown
938 channel = Timer->Channel()->Number();
940 isPesRecording = false;
941 isOnVideoDirectoryFileSystem = -1; // unknown
942 numFrames = -1;
943 deleted = 0;
944 // set up the actual name:
945 const char *Title = Event ? Event->Title() : NULL;
946 const char *Subtitle = Event ? Event->ShortText() : NULL;
947 if (isempty(Title))
948 Title = Timer->Channel()->Name();
949 if (isempty(Subtitle))
950 Subtitle = " ";
951 const char *macroTITLE = strstr(Timer->File(), TIMERMACRO_TITLE);
952 const char *macroEPISODE = strstr(Timer->File(), TIMERMACRO_EPISODE);
953 if (macroTITLE || macroEPISODE) {
954 name = strdup(Timer->File());
957 // avoid blanks at the end:
958 int l = strlen(name);
959 while (l-- > 2) {
960 if (name[l] == ' ' && name[l - 1] != FOLDERDELIMCHAR)
961 name[l] = 0;
962 else
963 break;
964 }
965 if (Timer->IsSingleEvent())
966 Timer->SetFile(name); // this was an instant recording, so let's set the actual data
967 }
968 else if (Timer->IsSingleEvent() || !Setup.UseSubtitle)
969 name = strdup(Timer->File());
970 else
971 name = strdup(cString::sprintf("%s%c%s", Timer->File(), FOLDERDELIMCHAR, Subtitle));
972 // substitute characters that would cause problems in file names:
973 strreplace(name, '\n', ' ');
974 start = Timer->StartTime();
975 // handle info:
976 info = new cRecordingInfo(Timer->Channel(), Event);
977 info->SetAux(Timer->Aux());
978 info->SetPriority(Timer->Priority());
979 info->SetLifetime(Timer->Lifetime());
980}
981
983{
984 id = 0;
985 resume = NULL;
986 fileSizeMB = -1; // unknown
987 channel = -1;
988 instanceId = -1;
989 isPesRecording = false;
990 isOnVideoDirectoryFileSystem = -1; // unknown
991 numFrames = -1;
992 deleted = 0;
993 titleBuffer = NULL;
995 FileName = fileName = strdup(FileName);
996 if (*(fileName + strlen(fileName) - 1) == '/')
997 *(fileName + strlen(fileName) - 1) = 0;
998 if (strstr(FileName, cVideoDirectory::Name()) == FileName)
999 FileName += strlen(cVideoDirectory::Name()) + 1;
1000 const char *p = strrchr(FileName, '/');
1001
1002 name = NULL;
1004 if (p) {
1005 time_t now = time(NULL);
1006 struct tm tm_r;
1007 struct tm t = *localtime_r(&now, &tm_r); // this initializes the time zone in 't'
1008 t.tm_isdst = -1; // makes sure mktime() will determine the correct DST setting
1009 int priority = MAXPRIORITY;
1010 int lifetime = MAXLIFETIME;
1011 if (7 == sscanf(p + 1, DATAFORMATTS, &t.tm_year, &t.tm_mon, &t.tm_mday, &t.tm_hour, &t.tm_min, &channel, &instanceId)
1012 || 7 == sscanf(p + 1, DATAFORMATPES, &t.tm_year, &t.tm_mon, &t.tm_mday, &t.tm_hour, &t.tm_min, &priority, &lifetime)) {
1013 t.tm_year -= 1900;
1014 t.tm_mon--;
1015 t.tm_sec = 0;
1016 start = mktime(&t);
1017 name = MALLOC(char, p - FileName + 1);
1018 strncpy(name, FileName, p - FileName);
1019 name[p - FileName] = 0;
1020 name = ExchangeChars(name, false);
1022 }
1023 else
1024 return;
1026 GetResume();
1027 // read an optional info file:
1029 FILE *f = fopen(InfoFileName, "r");
1030 if (f) {
1031 if (!info->Read(f))
1032 esyslog("ERROR: EPG data problem in file %s", *InfoFileName);
1033 else if (isPesRecording) {
1034 info->SetPriority(priority);
1035 info->SetLifetime(lifetime);
1036 }
1037 fclose(f);
1038 }
1039 else if (errno != ENOENT)
1040 LOG_ERROR_STR(*InfoFileName);
1041#ifdef SUMMARYFALLBACK
1042 // fall back to the old 'summary.vdr' if there was no 'info.vdr':
1043 if (isempty(info->Title())) {
1044 cString SummaryFileName = cString::sprintf("%s%s", fileName, SUMMARYFILESUFFIX);
1045 FILE *f = fopen(SummaryFileName, "r");
1046 if (f) {
1047 int line = 0;
1048 char *data[3] = { NULL };
1049 cReadLine ReadLine;
1050 char *s;
1051 while ((s = ReadLine.Read(f)) != NULL) {
1052 if (*s || line > 1) {
1053 if (data[line]) {
1054 int len = strlen(s);
1055 len += strlen(data[line]) + 1;
1056 if (char *NewBuffer = (char *)realloc(data[line], len + 1)) {
1057 data[line] = NewBuffer;
1058 strcat(data[line], "\n");
1059 strcat(data[line], s);
1060 }
1061 else
1062 esyslog("ERROR: out of memory");
1063 }
1064 else
1065 data[line] = strdup(s);
1066 }
1067 else
1068 line++;
1069 }
1070 fclose(f);
1071 if (!data[2]) {
1072 data[2] = data[1];
1073 data[1] = NULL;
1074 }
1075 else if (data[1] && data[2]) {
1076 // if line 1 is too long, it can't be the short text,
1077 // so assume the short text is missing and concatenate
1078 // line 1 and line 2 to be the long text:
1079 int len = strlen(data[1]);
1080 if (len > 80) {
1081 if (char *NewBuffer = (char *)realloc(data[1], len + 1 + strlen(data[2]) + 1)) {
1082 data[1] = NewBuffer;
1083 strcat(data[1], "\n");
1084 strcat(data[1], data[2]);
1085 free(data[2]);
1086 data[2] = data[1];
1087 data[1] = NULL;
1088 }
1089 else
1090 esyslog("ERROR: out of memory");
1091 }
1092 }
1093 info->SetTitle(data[0]);
1094 info->SetShortText(data[1]);
1095 info->SetDescription(data[2]);
1096 for (int i = 0; i < 3; i ++)
1097 free(data[i]);
1098 }
1099 else if (errno != ENOENT)
1100 LOG_ERROR_STR(*SummaryFileName);
1101 }
1102#endif
1103 if (isempty(info->Title()))
1105 }
1106}
1107
1109{
1110 free(titleBuffer);
1111 free(sortBufferName);
1112 free(sortBufferTime);
1113 free(fileName);
1114 free(name);
1115 delete resume;
1116 delete info;
1117}
1118
1119char *cRecording::StripEpisodeName(char *s, bool Strip)
1120{
1121 char *t = s, *s1 = NULL, *s2 = NULL;
1122 while (*t) {
1123 if (*t == '/') {
1124 if (s1) {
1125 if (s2)
1126 s1 = s2;
1127 s2 = t;
1128 }
1129 else
1130 s1 = t;
1131 }
1132 t++;
1133 }
1134 if (s1 && s2) {
1135 // To have folders sorted before plain recordings, the '/' s1 points to
1136 // is replaced by the character '1'. All other slashes will be replaced
1137 // by '0' in SortName() (see below), which will result in the desired
1138 // sequence ('0' and '1' are reversed in case of rsdDescending):
1139 *s1 = (Setup.RecSortingDirection == rsdAscending) ? '1' : '0';
1140 if (Strip) {
1141 s1++;
1142 memmove(s1, s2, t - s2 + 1);
1143 }
1144 }
1145 return s;
1146}
1147
1148char *cRecording::SortName(void) const
1149{
1151 if (!*sb) {
1153 char buf[32];
1154 struct tm tm_r;
1155 strftime(buf, sizeof(buf), "%Y%m%d%H%I", localtime_r(&start, &tm_r));
1156 *sb = strdup(buf);
1157 }
1158 else {
1159 char *s = strdup(FileName() + strlen(cVideoDirectory::Name()));
1162 strreplace(s, '/', (Setup.RecSortingDirection == rsdAscending) ? '0' : '1'); // some locales ignore '/' when sorting
1163 int l = strxfrm(NULL, s, 0) + 1;
1164 *sb = MALLOC(char, l);
1165 strxfrm(*sb, s, l);
1166 free(s);
1167 }
1168 }
1169 return *sb;
1170}
1171
1173{
1174 free(sortBufferName);
1175 free(sortBufferTime);
1177}
1178
1180{
1181 id = Id;
1182}
1183
1185{
1186 return resume ? resume->Index() : -1;
1187}
1188
1190{
1191 return resume ? resume->FileTime() : 0;
1192}
1193
1195{
1196 if (Deleted()) {
1198 return time(NULL) - Deleted() > Retention;
1199 }
1200 return false;
1201}
1202
1207
1208int cRecording::Compare(const cListObject &ListObject) const
1209{
1210 cRecording *r = (cRecording *)&ListObject;
1212 return strcmp(SortName(), r->SortName());
1213 else
1214 return strcmp(r->SortName(), SortName());
1215}
1216
1217bool cRecording::IsInPath(const char *Path) const
1218{
1219 if (isempty(Path))
1220 return true;
1221 int l = strlen(Path);
1222 return strncmp(Path, name, l) == 0 && (name[l] == FOLDERDELIMCHAR);
1223}
1224
1226{
1227 if (char *s = strrchr(name, FOLDERDELIMCHAR))
1228 return cString(name, s);
1229 return "";
1230}
1231
1233{
1235}
1236
1237const char *cRecording::FileName(void) const
1238{
1239 if (!fileName) {
1240 struct tm tm_r;
1241 struct tm *t = localtime_r(&start, &tm_r);
1242 const char *fmt = isPesRecording ? NAMEFORMATPES : NAMEFORMATTS;
1243 int ch = isPesRecording ? info->Priority() : channel;
1244 int ri = isPesRecording ? info->Lifetime() : instanceId;
1245 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
1246 if (strcmp(Name, name) != 0)
1247 dsyslog("recording file name '%s' truncated to '%s'", name, Name);
1248 Name = ExchangeChars(Name, true);
1249 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));
1250 free(Name);
1251 }
1252 return fileName;
1253}
1254
1255const char *cRecording::Title(char Delimiter, bool NewIndicator, int Level) const
1256{
1257 const char *New = NewIndicator && IsNew() ? "*" : "";
1258 const char *Err = NewIndicator && (info->Errors() > 0) ? "!" : "";
1259 const char *Cut = NewIndicator && ((IsInUse() & (ruCut | ruSrc)) == (ruCut | ruSrc)) ? "%" : "";
1260 free(titleBuffer);
1261 titleBuffer = NULL;
1262 if (Level < 0 || Level == HierarchyLevels()) {
1263 struct tm tm_r;
1264 struct tm *t = localtime_r(&start, &tm_r);
1265 char *s;
1266 if (Level > 0 && (s = strrchr(name, FOLDERDELIMCHAR)) != NULL)
1267 s++;
1268 else
1269 s = name;
1270 cString Length("");
1271 if (NewIndicator) {
1272 int Minutes = max(0, (LengthInSeconds() + 30) / 60);
1273 Length = cString::sprintf("%c%d:%02d",
1274 Delimiter,
1275 Minutes / 60,
1276 Minutes % 60
1277 );
1278 }
1279 titleBuffer = strdup(cString::sprintf("%02d.%02d.%02d%c%02d:%02d%s%s%s%s%c%s",
1280 t->tm_mday,
1281 t->tm_mon + 1,
1282 t->tm_year % 100,
1283 Delimiter,
1284 t->tm_hour,
1285 t->tm_min,
1286 *Length,
1287 New,
1288 Err,
1289 Cut,
1290 Delimiter,
1291 s));
1292 // let's not display a trailing FOLDERDELIMCHAR:
1293 if (!NewIndicator)
1295 s = &titleBuffer[strlen(titleBuffer) - 1];
1296 if (*s == FOLDERDELIMCHAR)
1297 *s = 0;
1298 }
1299 else if (Level < HierarchyLevels()) {
1300 const char *s = name;
1301 const char *p = s;
1302 while (*++s) {
1303 if (*s == FOLDERDELIMCHAR) {
1304 if (Level--)
1305 p = s + 1;
1306 else
1307 break;
1308 }
1309 }
1310 titleBuffer = MALLOC(char, s - p + 3);
1311 *titleBuffer = Delimiter;
1312 *(titleBuffer + 1) = Delimiter;
1313 strn0cpy(titleBuffer + 2, p, s - p + 1);
1314 }
1315 else
1316 return "";
1317 return titleBuffer;
1318}
1319
1320const char *cRecording::PrefixFileName(char Prefix)
1321{
1323 if (*p) {
1324 free(fileName);
1325 fileName = strdup(p);
1326 return fileName;
1327 }
1328 return NULL;
1329}
1330
1332{
1333 const char *s = name;
1334 int level = 0;
1335 while (*++s) {
1336 if (*s == FOLDERDELIMCHAR)
1337 level++;
1338 }
1339 return level;
1340}
1341
1342bool cRecording::IsEdited(void) const
1343{
1344 const char *s = strgetlast(name, FOLDERDELIMCHAR);
1345 return *s == '%';
1346}
1347
1354
1355bool cRecording::HasMarks(void) const
1356{
1357 return access(cMarks::MarksFileName(this), F_OK) == 0;
1358}
1359
1361{
1362 return cMarks::DeleteMarksFile(this);
1363}
1364
1365void cRecording::ReadInfo(bool Force)
1366{
1367 info->Read(Force);
1368}
1369
1370bool cRecording::WriteInfo(const char *OtherFileName)
1371{
1372 cString InfoFileName = cString::sprintf("%s%s", OtherFileName ? OtherFileName : FileName(), isPesRecording ? INFOFILESUFFIX ".vdr" : INFOFILESUFFIX);
1373 if (!OtherFileName) {
1374 // Let's keep the error counter if this is a re-started recording:
1375 cRecordingInfo ExistingInfo(FileName());
1376 if (ExistingInfo.Read())
1377 info->SetErrors(max(0, ExistingInfo.Errors()), max(0, ExistingInfo.TmpErrors()));
1378 else
1379 info->SetErrors(0);
1380 }
1381 cSafeFile f(InfoFileName);
1382 if (f.Open()) {
1383 info->Write(f);
1384 f.Close();
1385 }
1386 else
1387 LOG_ERROR_STR(*InfoFileName);
1388 return true;
1389}
1390
1392{
1393 start = Start;
1394 free(fileName);
1395 fileName = NULL;
1396}
1397
1398bool cRecording::ChangePriorityLifetime(int NewPriority, int NewLifetime)
1399{
1400 if (NewPriority != Priority() || NewLifetime != Lifetime()) {
1401 dsyslog("changing priority/lifetime of '%s' to %d/%d", Name(), NewPriority, NewLifetime);
1402 info->SetPriority(NewPriority);
1403 info->SetLifetime(NewLifetime);
1404 if (IsPesRecording()) {
1405 cString OldFileName = FileName();
1406 free(fileName);
1407 fileName = NULL;
1408 cString NewFileName = FileName();
1409 if (!cVideoDirectory::RenameVideoFile(OldFileName, NewFileName))
1410 return false;
1411 info->SetFileName(NewFileName);
1412 resume->SetFileName(NewFileName);
1413 }
1414 else {
1415 if (!WriteInfo())
1416 return false;
1417 }
1418 }
1419 return true;
1420}
1421
1422bool cRecording::ChangeName(const char *NewName)
1423{
1424 if (strcmp(NewName, Name())) {
1425 dsyslog("changing name of '%s' to '%s'", Name(), NewName);
1426 cString OldName = Name();
1427 cString OldFileName = FileName();
1428 free(fileName);
1429 fileName = NULL;
1430 free(name);
1431 name = strdup(NewName);
1432 cString NewFileName = FileName();
1433 bool Exists = access(NewFileName, F_OK) == 0;
1434 if (Exists)
1435 esyslog("ERROR: recording '%s' already exists", NewName);
1436 if (Exists || !(MakeDirs(NewFileName, true) && cVideoDirectory::MoveVideoFile(OldFileName, NewFileName))) {
1437 free(name);
1438 name = strdup(OldName);
1439 free(fileName);
1440 fileName = strdup(OldFileName);
1441 return false;
1442 }
1443 info->SetFileName(NewFileName);
1444 resume->SetFileName(NewFileName);
1445 isOnVideoDirectoryFileSystem = -1; // it might have been moved to a different file system
1446 ClearSortName();
1447 }
1448 return true;
1449}
1450
1452{
1453 bool result = true;
1454 char *NewName = strdup(FileName());
1455 char *ext = strrchr(NewName, '.');
1456 if (ext && strcmp(ext, RECEXT) == 0) {
1457 strncpy(ext, DELEXT, strlen(ext));
1458 if (access(NewName, F_OK) == 0) {
1459 // the new name already exists, so let's remove that one first:
1460 isyslog("removing recording '%s'", NewName);
1462 }
1463 isyslog("deleting recording '%s'", FileName());
1464 if (access(FileName(), F_OK) == 0) {
1465 result = cVideoDirectory::RenameVideoFile(FileName(), NewName);
1466 if (result) {
1467 info->SetFileName(NewName);
1468 resume->SetFileName(NewName);
1469 TouchFile(NewName);
1470 }
1472 }
1473 else {
1474 isyslog("recording '%s' vanished", FileName());
1475 result = true; // well, we were going to delete it, anyway
1476 }
1477 if (result) {
1478 strncpy(fileName + (ext - NewName), DELEXT, strlen(ext));
1479 SetDeleted();
1480 }
1481 }
1482 free(NewName);
1483 return result;
1484}
1485
1487{
1488 // let's do a final safety check here:
1489 if (!endswith(FileName(), DELEXT)) {
1490 esyslog("attempt to remove recording %s", FileName());
1491 return false;
1492 }
1493 isyslog("removing recording %s", FileName());
1495}
1496
1498{
1499 bool result = true;
1500 char *NewName = strdup(FileName());
1501 char *ext = strrchr(NewName, '.');
1502 if (ext && strcmp(ext, DELEXT) == 0) {
1503 strncpy(ext, RECEXT, strlen(ext));
1504 if (access(NewName, F_OK) == 0) {
1505 // the new name already exists, so let's not remove that one:
1506 esyslog("ERROR: attempt to restore '%s', while recording '%s' exists", FileName(), NewName);
1507 result = false;
1508 }
1509 else {
1510 isyslog("restoring recording '%s'", FileName());
1511 if (access(FileName(), F_OK) == 0) {
1512 result = cVideoDirectory::RenameVideoFile(FileName(), NewName);
1513 if (result) {
1514 info->SetFileName(NewName);
1515 resume->SetFileName(NewName);
1516 }
1517 deleted = 0;
1518 }
1519 else {
1520 isyslog("deleted recording '%s' vanished", FileName());
1521 result = false;
1522 }
1523 }
1524 if (result)
1525 strncpy(fileName + (ext - NewName), RECEXT, strlen(ext));
1526 }
1527 free(NewName);
1528 return result;
1529}
1530
1531int cRecording::IsInUse(void) const
1532{
1533 int Use = ruNone;
1535 Use |= ruTimer;
1537 Use |= ruReplay;
1539 return Use;
1540}
1541
1542static bool StillRecording(const char *Directory)
1543{
1544 return access(AddDirectory(Directory, TIMERRECFILE), F_OK) == 0;
1545}
1546
1548{
1549 if (resume)
1550 resume->Reset();
1551}
1552
1554{
1555 if (resume)
1556 resume->Delete();
1557}
1558
1560{
1561 if (numFrames < 0) {
1563 if (StillRecording(FileName()))
1564 return nf; // check again later for ongoing recordings
1565 numFrames = nf;
1566 }
1567 return numFrames;
1568}
1569
1571{
1572 int IndexLength = cIndexFile::GetLength(fileName, isPesRecording);
1573 if (IndexLength > 0) {
1574 cMarks Marks;
1576 return Marks.GetFrameAfterEdit(IndexLength - 1, IndexLength - 1);
1577 }
1578 return -1;
1579}
1580
1582{
1583 int nf = NumFrames();
1584 if (nf >= 0)
1585 return int(nf / FramesPerSecond());
1586 return -1;
1587}
1588
1590{
1591 int nf = NumFramesAfterEdit();
1592 if (nf >= 0)
1593 return int(nf / FramesPerSecond());
1594 return -1;
1595}
1596
1598{
1599 if (fileSizeMB < 0) {
1600 int fs = DirSizeMB(FileName());
1601 if (StillRecording(FileName()))
1602 return fs; // check again later for ongoing recordings
1603 fileSizeMB = fs;
1604 }
1605 return fileSizeMB;
1606}
1607
1608// --- cVideoDirectoryScannerThread ------------------------------------------
1609
1611private:
1616 void ScanVideoDir(const char *DirName, int LinkLevel = 0, int DirLevel = 0);
1617protected:
1618 virtual void Action(void) override;
1619public:
1620 cVideoDirectoryScannerThread(cRecordings *Recordings, cRecordings *DeletedRecordings);
1622 };
1623
1625:cThread("video directory scanner", true)
1626{
1627 recordings = Recordings;
1628 deletedRecordings = DeletedRecordings;
1629 count = 0;
1630 initial = true;
1631}
1632
1637
1639{
1640 cStateKey StateKey;
1641 recordings->Lock(StateKey);
1642 count = recordings->Count();
1643 initial = count == 0; // no name checking if the list is initially empty
1644 StateKey.Remove();
1645 deletedRecordings->Lock(StateKey, true);
1647 StateKey.Remove();
1649}
1650
1651void cVideoDirectoryScannerThread::ScanVideoDir(const char *DirName, int LinkLevel, int DirLevel)
1652{
1653 // Find any new recordings:
1654 cReadDir d(DirName);
1655 struct dirent *e;
1656 while (Running() && (e = d.Next()) != NULL) {
1658 cCondWait::SleepMs(100);
1659 cString buffer = AddDirectory(DirName, e->d_name);
1660 struct stat st;
1661 if (lstat(buffer, &st) == 0) {
1662 int Link = 0;
1663 if (S_ISLNK(st.st_mode)) {
1664 if (LinkLevel > MAX_LINK_LEVEL) {
1665 isyslog("max link level exceeded - not scanning %s", *buffer);
1666 continue;
1667 }
1668 Link = 1;
1669 if (stat(buffer, &st) != 0)
1670 continue;
1671 }
1672 if (S_ISDIR(st.st_mode)) {
1673 cRecordings *Recordings = NULL;
1674 if (endswith(buffer, RECEXT))
1675 Recordings = recordings;
1676 else if (endswith(buffer, DELEXT))
1677 Recordings = deletedRecordings;
1678 if (Recordings) {
1679 cStateKey StateKey;
1680 Recordings->Lock(StateKey, true);
1681 if (initial && count != recordings->Count()) {
1682 dsyslog("activated name checking for initial read of video directory");
1683 initial = false;
1684 }
1685 cRecording *Recording = NULL;
1686 if (Recordings == deletedRecordings || initial || !(Recording = Recordings->GetByName(buffer))) {
1687 cRecording *r = new cRecording(buffer);
1688 if (r->Name()) {
1689 r->NumFrames(); // initializes the numFrames member
1690 r->FileSizeMB(); // initializes the fileSizeMB member
1691 r->IsOnVideoDirectoryFileSystem(); // initializes the isOnVideoDirectoryFileSystem member
1692 if (Recordings == deletedRecordings)
1693 r->SetDeleted();
1694 if (initial)
1696 Recordings->Add(r);
1697 count = recordings->Count();
1698 }
1699 else
1700 delete r;
1701 }
1702 else if (Recording)
1703 Recording->ReadInfo();
1704 StateKey.Remove();
1705 }
1706 else
1707 ScanVideoDir(buffer, LinkLevel + Link, DirLevel + 1);
1708 }
1709 }
1710 }
1711 // Handle any vanished recordings:
1712 if (!initial && DirLevel == 0) {
1713 cStateKey StateKey;
1714 recordings->Lock(StateKey, true);
1716 for (cRecording *Recording = recordings->First(); Recording; ) {
1717 cRecording *r = Recording;
1718 Recording = recordings->Next(Recording);
1719 if (access(r->FileName(), F_OK) != 0) {
1720 recordings->Del(r);
1722 }
1723 }
1724 StateKey.Remove();
1725 deletedRecordings->Lock(StateKey, true);
1727 for (cRecording *Recording = deletedRecordings->First(); Recording; ) {
1728 cRecording *r = Recording;
1729 Recording = deletedRecordings->Next(Recording);
1730 if (access(r->FileName(), F_OK) != 0) {
1733 }
1734 }
1735 StateKey.Remove();
1736 }
1737}
1738
1739// --- cRecordings -----------------------------------------------------------
1740
1744char *cRecordings::updateFileName = NULL;
1746time_t cRecordings::lastUpdate = 0;
1747
1749:cList<cRecording>(Deleted ? "4 DelRecs" : "3 Recordings")
1750{
1751}
1752
1754{
1755 // The first one to be destructed deletes it:
1758}
1759
1761{
1762 if (!updateFileName)
1763 updateFileName = strdup(AddDirectory(cVideoDirectory::Name(), ".update"));
1764 return updateFileName;
1765}
1766
1768{
1769 bool needsUpdate = NeedsUpdate();
1770 TouchFile(UpdateFileName(), true);
1771 if (!needsUpdate)
1772 lastUpdate = time(NULL); // make sure we don't trigger ourselves
1773}
1774
1776{
1777 time_t lastModified = LastModifiedTime(UpdateFileName());
1778 if (lastModified > time(NULL))
1779 return false; // somebody's clock isn't running correctly
1780 return lastUpdate < lastModified;
1781}
1782
1783void cRecordings::Update(bool Wait)
1784{
1787 lastUpdate = time(NULL); // doing this first to make sure we don't miss anything
1789 if (Wait) {
1791 cCondWait::SleepMs(100);
1792 }
1793}
1794
1796{
1797 for (const cRecording *Recording = First(); Recording; Recording = Next(Recording)) {
1798 if (Recording->Id() == Id)
1799 return Recording;
1800 }
1801 return NULL;
1802}
1803
1804const cRecording *cRecordings::GetByName(const char *FileName) const
1805{
1806 if (FileName) {
1807 for (const cRecording *Recording = First(); Recording; Recording = Next(Recording)) {
1808 if (strcmp(Recording->FileName(), FileName) == 0)
1809 return Recording;
1810 }
1811 }
1812 return NULL;
1813}
1814
1816{
1817 Recording->SetId(++lastRecordingId);
1818 cList<cRecording>::Add(Recording);
1819}
1820
1821void cRecordings::AddByName(const char *FileName, bool TriggerUpdate)
1822{
1823 if (!GetByName(FileName)) {
1824 Add(new cRecording(FileName));
1825 if (TriggerUpdate)
1826 TouchUpdate();
1827 }
1828 else
1829 UpdateByName(FileName);
1830}
1831
1832void cRecordings::DelByName(const char *FileName)
1833{
1834 if (this != &recordings) {
1835 esyslog("ERROR: cRecordings::DelByName() called with '%s' on a list other than Recordings - ignored", FileName);
1836 return;
1837 }
1838 char *DelRecFileName = strdup(FileName);
1839 if (char *ext = strrchr(DelRecFileName, '.')) {
1840 if (strcmp(ext, RECEXT)) {
1841 esyslog("ERROR: cRecordings::DelByName() called with '%s', using '.rec' instead", DelRecFileName);
1842 strncpy(ext, RECEXT, strlen(ext));
1843 }
1844 }
1845 cRecording *dummy = NULL;
1846 cRecording *Recording = GetByName(DelRecFileName);
1847 if (!Recording) {
1848 esyslog("ERROR: cRecordings::DelByName(): '%s' not found in Recordings - using dummy", DelRecFileName);
1849 Recording = dummy = new cRecording(FileName); // allows us to use a FileName that is not in the Recordings list
1850 }
1852 if (!dummy)
1853 Del(Recording, false);
1854 char *ext = strrchr(Recording->fileName, '.');
1855 if (ext) {
1856 strncpy(ext, DELEXT, strlen(ext));
1857 if (access(Recording->FileName(), F_OK) == 0) {
1858 Recording->SetDeleted();
1859 DeletedRecordings->Add(Recording);
1860 Recording = NULL; // to prevent it from being deleted below
1861 }
1862 }
1863 delete Recording;
1864 free(DelRecFileName);
1865 TouchUpdate();
1866}
1867
1868void cRecordings::UpdateByName(const char *FileName)
1869{
1870 if (cRecording *Recording = GetByName(FileName)) {
1871 Recording->numFrames = -1;
1872 Recording->ReadInfo(true);
1873 }
1874}
1875
1877{
1878 int size = 0;
1879 for (const cRecording *Recording = First(); Recording; Recording = Next(Recording)) {
1880 int FileSizeMB = Recording->FileSizeMB();
1881 if (FileSizeMB > 0 && Recording->IsOnVideoDirectoryFileSystem())
1882 size += FileSizeMB;
1883 }
1884 return size;
1885}
1886
1888{
1889 int size = 0;
1890 int length = 0;
1891 for (const cRecording *Recording = First(); Recording; Recording = Next(Recording)) {
1892 if (Recording->IsOnVideoDirectoryFileSystem()) {
1893 int FileSizeMB = Recording->FileSizeMB();
1894 if (FileSizeMB > 0) {
1895 int LengthInSeconds = Recording->LengthInSeconds();
1896 if (LengthInSeconds > 0) {
1897 if (LengthInSeconds / FileSizeMB < LIMIT_SECS_PER_MB_RADIO) { // don't count radio recordings
1898 size += FileSizeMB;
1899 length += LengthInSeconds;
1900 }
1901 }
1902 }
1903 }
1904 }
1905 return (size && length) ? double(size) * 60 / length : -1;
1906}
1907
1908int cRecordings::PathIsInUse(const char *Path) const
1909{
1910 int Use = ruNone;
1911 for (const cRecording *Recording = First(); Recording; Recording = Next(Recording)) {
1912 if (Recording->IsInPath(Path))
1913 Use |= Recording->IsInUse();
1914 }
1915 return Use;
1916}
1917
1918int cRecordings::GetNumRecordingsInPath(const char *Path) const
1919{
1920 int n = 0;
1921 for (const cRecording *Recording = First(); Recording; Recording = Next(Recording)) {
1922 if (Recording->IsInPath(Path))
1923 n++;
1924 }
1925 return n;
1926}
1927
1928bool cRecordings::MoveRecordings(const char *OldPath, const char *NewPath)
1929{
1930 if (OldPath && NewPath && strcmp(OldPath, NewPath)) {
1931 dsyslog("moving '%s' to '%s'", OldPath, NewPath);
1932 bool Moved = false;
1933 for (cRecording *Recording = First(); Recording; Recording = Next(Recording)) {
1934 if (Recording->IsInPath(OldPath)) {
1935 const char *p = Recording->Name() + strlen(OldPath);
1936 cString NewName = cString::sprintf("%s%s", NewPath, p);
1937 if (!Recording->ChangeName(NewName))
1938 return false;
1939 Moved = true;
1940 }
1941 }
1942 if (Moved)
1943 TouchUpdate();
1944 }
1945 return true;
1946}
1947
1948void cRecordings::ResetResume(const char *ResumeFileName)
1949{
1950 for (cRecording *Recording = First(); Recording; Recording = Next(Recording)) {
1951 if (!ResumeFileName || strncmp(ResumeFileName, Recording->FileName(), strlen(Recording->FileName())) == 0)
1952 Recording->ResetResume();
1953 }
1954}
1955
1957{
1958 for (cRecording *Recording = First(); Recording; Recording = Next(Recording))
1959 Recording->ClearSortName();
1960}
1961
1962// --- cDirCopier ------------------------------------------------------------
1963
1964class cDirCopier : public cThread {
1965private:
1968 bool error;
1970 bool Throttled(void);
1971 virtual void Action(void) override;
1972public:
1973 cDirCopier(const char *DirNameSrc, const char *DirNameDst);
1974 virtual ~cDirCopier() override;
1975 bool Error(void) { return error; }
1976 };
1977
1978cDirCopier::cDirCopier(const char *DirNameSrc, const char *DirNameDst)
1979:cThread("file copier", true)
1980{
1981 dirNameSrc = DirNameSrc;
1982 dirNameDst = DirNameDst;
1983 error = true; // prepare for the worst!
1984 suspensionLogged = false;
1985}
1986
1988{
1989 Cancel(3);
1990}
1991
1993{
1994 if (cIoThrottle::Engaged()) {
1995 if (!suspensionLogged) {
1996 dsyslog("suspending copy thread");
1997 suspensionLogged = true;
1998 }
1999 return true;
2000 }
2001 else if (suspensionLogged) {
2002 dsyslog("resuming copy thread");
2003 suspensionLogged = false;
2004 }
2005 return false;
2006}
2007
2009{
2010 if (DirectoryOk(dirNameDst, true)) {
2012 if (d.Ok()) {
2013 dsyslog("copying directory '%s' to '%s'", *dirNameSrc, *dirNameDst);
2014 dirent *e = NULL;
2015 cString FileNameSrc;
2016 cString FileNameDst;
2017 int From = -1;
2018 int To = -1;
2019 size_t BufferSize = BUFSIZ;
2020 uchar *Buffer = NULL;
2021 while (Running()) {
2022 // Suspend copying if we have severe throughput problems:
2023 if (Throttled()) {
2024 cCondWait::SleepMs(100);
2025 continue;
2026 }
2027 // Copy all files in the source directory to the destination directory:
2028 if (e) {
2029 // We're currently copying a file:
2030 if (!Buffer) {
2031 esyslog("ERROR: no buffer");
2032 break;
2033 }
2034 size_t Read = safe_read(From, Buffer, BufferSize);
2035 if (Read > 0) {
2036 size_t Written = safe_write(To, Buffer, Read);
2037 if (Written != Read) {
2038 esyslog("ERROR: can't write to destination file '%s': %m", *FileNameDst);
2039 break;
2040 }
2041 }
2042 else if (Read == 0) { // EOF on From
2043 e = NULL; // triggers switch to next entry
2044 if (fsync(To) < 0) {
2045 esyslog("ERROR: can't sync destination file '%s': %m", *FileNameDst);
2046 break;
2047 }
2048 if (close(From) < 0) {
2049 esyslog("ERROR: can't close source file '%s': %m", *FileNameSrc);
2050 break;
2051 }
2052 if (close(To) < 0) {
2053 esyslog("ERROR: can't close destination file '%s': %m", *FileNameDst);
2054 break;
2055 }
2056 // Plausibility check:
2057 off_t FileSizeSrc = FileSize(FileNameSrc);
2058 off_t FileSizeDst = FileSize(FileNameDst);
2059 if (FileSizeSrc != FileSizeDst) {
2060 esyslog("ERROR: file size discrepancy: %" PRId64 " != %" PRId64, FileSizeSrc, FileSizeDst);
2061 break;
2062 }
2063 }
2064 else {
2065 esyslog("ERROR: can't read from source file '%s': %m", *FileNameSrc);
2066 break;
2067 }
2068 }
2069 else if ((e = d.Next()) != NULL) {
2070 // We're switching to the next directory entry:
2071 FileNameSrc = AddDirectory(dirNameSrc, e->d_name);
2072 FileNameDst = AddDirectory(dirNameDst, e->d_name);
2073 struct stat st;
2074 if (stat(FileNameSrc, &st) < 0) {
2075 esyslog("ERROR: can't access source file '%s': %m", *FileNameSrc);
2076 break;
2077 }
2078 if (!(S_ISREG(st.st_mode) || S_ISLNK(st.st_mode))) {
2079 esyslog("ERROR: source file '%s' is neither a regular file nor a symbolic link", *FileNameSrc);
2080 break;
2081 }
2082 dsyslog("copying file '%s' to '%s'", *FileNameSrc, *FileNameDst);
2083 if (!Buffer) {
2084 BufferSize = max(size_t(st.st_blksize * 10), size_t(BUFSIZ));
2085 Buffer = MALLOC(uchar, BufferSize);
2086 if (!Buffer) {
2087 esyslog("ERROR: out of memory");
2088 break;
2089 }
2090 }
2091 if (access(FileNameDst, F_OK) == 0) {
2092 esyslog("ERROR: destination file '%s' already exists", *FileNameDst);
2093 break;
2094 }
2095 if ((From = open(FileNameSrc, O_RDONLY)) < 0) {
2096 esyslog("ERROR: can't open source file '%s': %m", *FileNameSrc);
2097 break;
2098 }
2099 if ((To = open(FileNameDst, O_WRONLY | O_CREAT | O_EXCL, DEFFILEMODE)) < 0) {
2100 esyslog("ERROR: can't open destination file '%s': %m", *FileNameDst);
2101 close(From);
2102 break;
2103 }
2104 }
2105 else {
2106 // We're done:
2107 free(Buffer);
2108 dsyslog("done copying directory '%s' to '%s'", *dirNameSrc, *dirNameDst);
2109 error = false;
2110 return;
2111 }
2112 }
2113 free(Buffer);
2114 close(From); // just to be absolutely sure
2115 close(To);
2116 isyslog("copying directory '%s' to '%s' ended prematurely", *dirNameSrc, *dirNameDst);
2117 }
2118 else
2119 esyslog("ERROR: can't open '%s'", *dirNameSrc);
2120 }
2121 else
2122 esyslog("ERROR: can't access '%s'", *dirNameDst);
2123}
2124
2125// --- cRecordingsHandlerEntry -----------------------------------------------
2126
2128private:
2134 bool error;
2135 void ClearPending(void) { usage &= ~ruPending; }
2136public:
2137 cRecordingsHandlerEntry(int Usage, const char *FileNameSrc, const char *FileNameDst);
2139 int Usage(const char *FileName = NULL) const;
2140 bool Error(void) const { return error; }
2141 void SetCanceled(void) { usage |= ruCanceled; }
2142 const char *FileNameSrc(void) const { return fileNameSrc; }
2143 const char *FileNameDst(void) const { return fileNameDst; }
2144 bool Active(cRecordings *Recordings);
2145 void Cleanup(cRecordings *Recordings);
2146 };
2147
2149{
2150 usage = Usage;
2153 cutter = NULL;
2154 copier = NULL;
2155 error = false;
2156}
2157
2163
2164int cRecordingsHandlerEntry::Usage(const char *FileName) const
2165{
2166 int u = usage;
2167 if (FileName && *FileName) {
2168 if (strcmp(FileName, fileNameSrc) == 0)
2169 u |= ruSrc;
2170 else if (strcmp(FileName, fileNameDst) == 0)
2171 u |= ruDst;
2172 }
2173 return u;
2174}
2175
2177{
2178 if ((usage & ruCanceled) != 0)
2179 return false;
2180 // First test whether there is an ongoing operation:
2181 if (cutter) {
2182 if (cutter->Active())
2183 return true;
2184 error = cutter->Error();
2185 delete cutter;
2186 cutter = NULL;
2187 }
2188 else if (copier) {
2189 if (copier->Active())
2190 return true;
2191 error = copier->Error();
2192 delete copier;
2193 copier = NULL;
2194 }
2195 // Now check if there is something to start:
2196 if ((Usage() & ruPending) != 0) {
2197 if ((Usage() & ruCut) != 0) {
2198 if (cRecording *Recording = Recordings->GetByName(FileNameDst())) {
2200 Recordings->Del(Recording);
2201 }
2202 cutter = new cCutter(FileNameSrc());
2203 cutter->Start();
2204 Recordings->AddByName(FileNameDst(), false);
2205 }
2206 else if ((Usage() & (ruMove | ruCopy)) != 0) {
2209 copier->Start();
2210 }
2211 ClearPending();
2212 Recordings->SetModified(); // to trigger a state change
2213 return true;
2214 }
2215 // We're done:
2216 if (!error) {
2217 if ((usage & (ruMove | ruCopy)) != 0)
2219 if ((usage & ruMove) != 0) {
2222 if (cRecording *Recording = Recordings->GetByName(FileNameSrc()))
2223 Recordings->Del(Recording); // just to be sure
2224 }
2225 }
2226 }
2227 Recordings->SetModified(); // to trigger a state change
2228 Recordings->TouchUpdate();
2229 return false;
2230}
2231
2233{
2234 if ((usage & ruCut)) { // this was a cut operation...
2235 if (cutter // ...which had not yet ended...
2236 || error) { // ...or finished with error
2237 if (cutter) {
2238 delete cutter;
2239 cutter = NULL;
2240 }
2241 if (cRecording *Recording = Recordings->GetByName(fileNameDst)) {
2242 cVideoDirectory::RemoveVideoFile(Recording->FileName());
2243 Recordings->Del(Recording);
2244 Recordings->SetModified();
2245 }
2246 }
2247 }
2248 if ((usage & (ruMove | ruCopy)) // this was a move/copy operation...
2249 && ((usage & ruPending) // ...which had not yet started...
2250 || copier // ...or not yet finished...
2251 || error)) { // ...or finished with error
2252 if (copier) {
2253 delete copier;
2254 copier = NULL;
2255 }
2256 if (cRecording *Recording = Recordings->GetByName(fileNameDst)) {
2257 cVideoDirectory::RemoveVideoFile(Recording->FileName());
2258 Recordings->Del(Recording);
2259 }
2260 if ((usage & ruMove) != 0)
2261 Recordings->AddByName(fileNameSrc);
2262 Recordings->SetModified();
2263 }
2264}
2265
2266// --- cRecordingsHandler ----------------------------------------------------
2267
2269
2271:cThread("recordings handler")
2272{
2273 finished = true;
2274 error = false;
2275 state = 0;
2276}
2277
2282
2284{
2285 while (Running()) {
2286 bool Sleep = false;
2287 {
2289 Recordings->SetExplicitModify();
2290 cMutexLock MutexLock(&mutex);
2292 if (!r->Active(Recordings)) {
2293 error |= r->Error();
2294 r->Cleanup(Recordings);
2295 operations.Del(r);
2296 state++;
2297 }
2298 else
2299 Sleep = true;
2300 }
2301 else
2302 break;
2303 }
2304 if (Sleep)
2305 cCondWait::SleepMs(100);
2306 }
2307}
2308
2310{
2311 if (FileName && *FileName) {
2312 for (cRecordingsHandlerEntry *r = operations.First(); r; r = operations.Next(r)) {
2313 if ((r->Usage() & ruCanceled) != 0)
2314 continue;
2315 if (strcmp(FileName, r->FileNameSrc()) == 0 || strcmp(FileName, r->FileNameDst()) == 0)
2316 return r;
2317 }
2318 }
2319 return NULL;
2320}
2321
2322bool cRecordingsHandler::Add(int Usage, const char *FileNameSrc, const char *FileNameDst)
2323{
2324 dsyslog("recordings handler add %d '%s' '%s'", Usage, FileNameSrc, FileNameDst);
2325 cMutexLock MutexLock(&mutex);
2326 if (Usage == ruCut || Usage == ruMove || Usage == ruCopy) {
2327 if (FileNameSrc && *FileNameSrc) {
2328 if (Usage == ruCut || FileNameDst && *FileNameDst) {
2329 cString fnd;
2330 if (Usage == ruCut && !FileNameDst)
2331 FileNameDst = fnd = cCutter::EditedFileName(FileNameSrc);
2332 if (!Get(FileNameSrc) && !Get(FileNameDst)) {
2333 Usage |= ruPending;
2334 operations.Add(new cRecordingsHandlerEntry(Usage, FileNameSrc, FileNameDst));
2335 finished = false;
2336 Start();
2337 state++;
2338 return true;
2339 }
2340 else
2341 esyslog("ERROR: file name already present in recordings handler add %d '%s' '%s'", Usage, FileNameSrc, FileNameDst);
2342 }
2343 else
2344 esyslog("ERROR: missing dst file name in recordings handler add %d '%s' '%s'", Usage, FileNameSrc, FileNameDst);
2345 }
2346 else
2347 esyslog("ERROR: missing src file name in recordings handler add %d '%s' '%s'", Usage, FileNameSrc, FileNameDst);
2348 }
2349 else
2350 esyslog("ERROR: invalid usage in recordings handler add %d '%s' '%s'", Usage, FileNameSrc, FileNameDst);
2351 return false;
2352}
2353
2354void cRecordingsHandler::Del(const char *FileName)
2355{
2356 cMutexLock MutexLock(&mutex);
2357 if (cRecordingsHandlerEntry *r = Get(FileName)) {
2358 r->SetCanceled();
2359 state++;
2360 }
2361}
2362
2364{
2365 cMutexLock MutexLock(&mutex);
2366 for (cRecordingsHandlerEntry *r = operations.First(); r; r = operations.Next(r)) {
2367 r->SetCanceled();
2368 state++;
2369 }
2370}
2371
2372int cRecordingsHandler::GetUsage(const char *FileName)
2373{
2374 cMutexLock MutexLock(&mutex);
2375 if (cRecordingsHandlerEntry *r = Get(FileName))
2376 return r->Usage(FileName);
2377 return ruNone;
2378}
2379
2381{
2382 cMutexLock MutexLock(&mutex);
2383 int RequiredDiskSpaceMB = 0;
2384 for (cRecordingsHandlerEntry *r = operations.First(); r; r = operations.Next(r)) {
2385 if ((r->Usage() & ruCanceled) != 0)
2386 continue;
2387 if ((r->Usage() & ruCut) != 0) {
2388 if (!FileName || EntriesOnSameFileSystem(FileName, r->FileNameDst()))
2389 RequiredDiskSpaceMB += FileSizeMBafterEdit(r->FileNameSrc());
2390 }
2391 else if ((r->Usage() & (ruMove | ruCopy)) != 0) {
2392 if (!FileName || EntriesOnSameFileSystem(FileName, r->FileNameDst()))
2393 RequiredDiskSpaceMB += DirSizeMB(r->FileNameSrc());
2394 }
2395 }
2396 return RequiredDiskSpaceMB;
2397}
2398
2400{
2401 cMutexLock MutexLock(&mutex);
2402 if (state != OldState) {
2403 OldState = state;
2404 return true;
2405 }
2406 return false;
2407}
2408
2410{
2411 cMutexLock MutexLock(&mutex);
2412 if (!finished && operations.Count() == 0) {
2413 finished = true;
2414 Error = error;
2415 error = false;
2416 return true;
2417 }
2418 return false;
2419}
2420
2421// --- cMark -----------------------------------------------------------------
2422
2425
2426cMark::cMark(int Position, const char *Comment, double FramesPerSecond)
2427{
2429 comment = Comment;
2430 framesPerSecond = FramesPerSecond;
2431}
2432
2434{
2435}
2436
2438{
2439 return cString::sprintf("%s%s%s", *IndexToHMSF(position, true, framesPerSecond), Comment() ? " " : "", Comment() ? Comment() : "");
2440}
2441
2442bool cMark::Parse(const char *s)
2443{
2444 comment = NULL;
2447 const char *p = strchr(s, ' ');
2448 if (p) {
2449 p = skipspace(p);
2450 if (*p)
2451 comment = p;
2452 }
2453 return true;
2454}
2455
2456bool cMark::Save(FILE *f)
2457{
2458 return fprintf(f, "%s\n", *ToText()) > 0;
2459}
2460
2461// --- cMarks ----------------------------------------------------------------
2462
2464{
2465 return AddDirectory(Recording->FileName(), Recording->IsPesRecording() ? MARKSFILESUFFIX ".vdr" : MARKSFILESUFFIX);
2466}
2467
2469{
2470 if (remove(cMarks::MarksFileName(Recording)) < 0) {
2471 if (errno != ENOENT) {
2472 LOG_ERROR_STR(Recording->FileName());
2473 return false;
2474 }
2475 }
2476 return true;
2477}
2478
2479bool cMarks::Load(const char *RecordingFileName, double FramesPerSecond, bool IsPesRecording)
2480{
2481 recordingFileName = RecordingFileName;
2482 fileName = AddDirectory(RecordingFileName, IsPesRecording ? MARKSFILESUFFIX ".vdr" : MARKSFILESUFFIX);
2483 framesPerSecond = FramesPerSecond;
2484 isPesRecording = IsPesRecording;
2485 nextUpdate = 0;
2486 lastFileTime = -1; // the first call to Load() must take place!
2487 lastChange = 0;
2488 return Update();
2489}
2490
2492{
2493 time_t t = time(NULL);
2494 if (t > nextUpdate && *fileName) {
2495 time_t LastModified = LastModifiedTime(fileName);
2496 if (LastModified != lastFileTime) // change detected, or first run
2497 lastChange = LastModified > 0 ? LastModified : t;
2498 int d = t - lastChange;
2499 if (d < 60)
2500 d = 1; // check frequently if the file has just been modified
2501 else if (d < 3600)
2502 d = 10; // older files are checked less frequently
2503 else
2504 d /= 360; // phase out checking for very old files
2505 nextUpdate = t + d;
2506 if (LastModified != lastFileTime) { // change detected, or first run
2507 lastFileTime = LastModified;
2508 if (lastFileTime == t)
2509 lastFileTime--; // make sure we don't miss updates in the remaining second
2513 Align();
2514 Sort();
2515 return true;
2516 }
2517 }
2518 }
2519 return false;
2520}
2521
2523{
2524 if (cConfig<cMark>::Save()) {
2526 return true;
2527 }
2528 return false;
2529}
2530
2532{
2533 cIndexFile IndexFile(recordingFileName, false, isPesRecording);
2534 for (cMark *m = First(); m; m = Next(m)) {
2535 int p = IndexFile.GetClosestIFrame(m->Position());
2536 if (m->Position() - p) {
2537 //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" : "");
2538 m->SetPosition(p);
2539 }
2540 }
2541}
2542
2544{
2545 for (cMark *m1 = First(); m1; m1 = Next(m1)) {
2546 for (cMark *m2 = Next(m1); m2; m2 = Next(m2)) {
2547 if (m2->Position() < m1->Position()) {
2548 swap(m1->position, m2->position);
2549 swap(m1->comment, m2->comment);
2550 }
2551 }
2552 }
2553}
2554
2555void cMarks::Add(int Position)
2556{
2557 cConfig<cMark>::Add(new cMark(Position, NULL, framesPerSecond));
2558 Sort();
2559}
2560
2561const cMark *cMarks::Get(int Position) const
2562{
2563 for (const cMark *mi = First(); mi; mi = Next(mi)) {
2564 if (mi->Position() == Position)
2565 return mi;
2566 }
2567 return NULL;
2568}
2569
2570const cMark *cMarks::GetPrev(int Position) const
2571{
2572 for (const cMark *mi = Last(); mi; mi = Prev(mi)) {
2573 if (mi->Position() < Position)
2574 return mi;
2575 }
2576 return NULL;
2577}
2578
2579const cMark *cMarks::GetNext(int Position) const
2580{
2581 for (const cMark *mi = First(); mi; mi = Next(mi)) {
2582 if (mi->Position() > Position)
2583 return mi;
2584 }
2585 return NULL;
2586}
2587
2588const cMark *cMarks::GetNextBegin(const cMark *EndMark) const
2589{
2590 const cMark *BeginMark = EndMark ? Next(EndMark) : First();
2591 if (BeginMark && EndMark && BeginMark->Position() == EndMark->Position()) {
2592 while (const cMark *NextMark = Next(BeginMark)) {
2593 if (BeginMark->Position() == NextMark->Position()) { // skip Begin/End at the same position
2594 if (!(BeginMark = Next(NextMark)))
2595 break;
2596 }
2597 else
2598 break;
2599 }
2600 }
2601 return BeginMark;
2602}
2603
2604const cMark *cMarks::GetNextEnd(const cMark *BeginMark) const
2605{
2606 if (!BeginMark)
2607 return NULL;
2608 const cMark *EndMark = Next(BeginMark);
2609 if (EndMark && BeginMark && BeginMark->Position() == EndMark->Position()) {
2610 while (const cMark *NextMark = Next(EndMark)) {
2611 if (EndMark->Position() == NextMark->Position()) { // skip End/Begin at the same position
2612 if (!(EndMark = Next(NextMark)))
2613 break;
2614 }
2615 else
2616 break;
2617 }
2618 }
2619 return EndMark;
2620}
2621
2623{
2624 int NumSequences = 0;
2625 if (const cMark *BeginMark = GetNextBegin()) {
2626 while (const cMark *EndMark = GetNextEnd(BeginMark)) {
2627 NumSequences++;
2628 BeginMark = GetNextBegin(EndMark);
2629 }
2630 if (BeginMark) {
2631 NumSequences++; // the last sequence had no actual "end" mark
2632 if (NumSequences == 1 && BeginMark->Position() == 0)
2633 NumSequences = 0; // there is only one actual "begin" mark at offset zero, and no actual "end" mark
2634 }
2635 }
2636 return NumSequences;
2637}
2638
2639int cMarks::GetFrameAfterEdit(int Frame, int LastFrame) const
2640{
2641 if (Count() == 0 || LastFrame < 0 || Frame < 0 || Frame > LastFrame)
2642 return -1;
2643 int EditedFrame = 0;
2644 int PrevPos = -1;
2645 bool InEdit = false;
2646 for (const cMark *mi = First(); mi; mi = Next(mi)) {
2647 int p = mi->Position();
2648 if (InEdit) {
2649 EditedFrame += p - PrevPos;
2650 InEdit = false;
2651 if (Frame <= p) {
2652 EditedFrame -= p - Frame;
2653 return EditedFrame;
2654 }
2655 }
2656 else {
2657 if (Frame <= p)
2658 return EditedFrame;
2659 PrevPos = p;
2660 InEdit = true;
2661 }
2662 }
2663 if (InEdit) {
2664 EditedFrame += LastFrame - PrevPos; // the last sequence had no actual "end" mark
2665 if (Frame < LastFrame)
2666 EditedFrame -= LastFrame - Frame;
2667 }
2668 return EditedFrame;
2669}
2670
2671// --- cRecordingUserCommand -------------------------------------------------
2672
2673const char *cRecordingUserCommand::command = NULL;
2674
2675void cRecordingUserCommand::InvokeCommand(const char *State, const char *RecordingFileName, const char *SourceFileName)
2676{
2677 if (command) {
2678 cString cmd;
2679 if (SourceFileName)
2680 cmd = cString::sprintf("%s %s \"%s\" \"%s\"", command, State, *strescape(RecordingFileName, "\\\"$"), *strescape(SourceFileName, "\\\"$"));
2681 else
2682 cmd = cString::sprintf("%s %s \"%s\"", command, State, *strescape(RecordingFileName, "\\\"$"));
2683 isyslog("executing '%s'", *cmd);
2684 SystemExec(cmd);
2685 }
2686}
2687
2688// --- cIndexFileGenerator ---------------------------------------------------
2689
2690#define IFG_BUFFER_SIZE KILOBYTE(100)
2691
2693private:
2696protected:
2697 virtual void Action(void) override;
2698public:
2699 cIndexFileGenerator(const char *RecordingName);
2701 };
2702
2704:cThread("index file generator")
2705,recordingName(RecordingName)
2706{
2707 Start();
2708}
2709
2714
2716{
2717 bool IndexFileComplete = false;
2718 bool IndexFileWritten = false;
2719 bool Rewind = false;
2720 cFileName FileName(recordingName, false);
2721 cUnbufferedFile *ReplayFile = FileName.Open();
2723 cPatPmtParser PatPmtParser;
2724 cFrameDetector FrameDetector;
2725 cIndexFile IndexFile(recordingName, true);
2726 int BufferChunks = KILOBYTE(1); // no need to read a lot at the beginning when parsing PAT/PMT
2727 off_t FileSize = 0;
2728 off_t FrameOffset = -1;
2729 bool pendIndependentFrame = false;
2730 uint16_t pendNumber = 0;
2731 off_t pendFileSize = 0;
2732 bool pendMissing = false;
2733 int Errors = 0;
2734 Skins.QueueMessage(mtInfo, tr("Regenerating index file"));
2736 bool Stuffed = false;
2737 while (Running()) {
2738 // Rewind input file:
2739 if (Rewind) {
2740 ReplayFile = FileName.SetOffset(1);
2741 Buffer.Clear();
2742 Rewind = false;
2743 }
2744 // Process data:
2745 int Length;
2746 uchar *Data = Buffer.Get(Length);
2747 if (Data) {
2748 if (FrameDetector.Synced()) {
2749 // Step 3 - generate the index:
2750 if (TsPid(Data) == PATPID) {
2751 int OldPatVersion, OldPmtVersion;
2752 PatPmtParser.GetVersions(OldPatVersion, OldPmtVersion);
2753 if (PatPmtParser.ParsePatPmt(Data, Length)) {
2754 int NewPatVersion, NewPmtVersion;
2755 if (PatPmtParser.GetVersions(NewPatVersion, NewPmtVersion)) {
2756 if (NewPatVersion != OldPatVersion || NewPmtVersion != OldPmtVersion) {
2757 dsyslog("PAT/PMT version change while generating index");
2758 FrameDetector.SetPid(PatPmtParser.Vpid() ? PatPmtParser.Vpid() : PatPmtParser.Apid(0), PatPmtParser.Vpid() ? PatPmtParser.Vtype() : PatPmtParser.Atype(0));
2759 }
2760 }
2761 }
2762 FrameOffset = FileSize; // the PAT/PMT is at the beginning of an I-frame
2763 }
2764 int Processed = FrameDetector.Analyze(Data, Length);
2765 if (Processed > 0) {
2766 bool PreviousErrors = false;
2767 bool MissingFrames = false;
2768 if (FrameDetector.NewFrame(PreviousErrors, MissingFrames)) {
2769 if (pendNumber > 0)
2770 IndexFile.Write(pendIndependentFrame, pendNumber, pendFileSize, PreviousErrors, pendMissing);
2771 pendIndependentFrame = FrameDetector.IndependentFrame();
2772 pendNumber = FileName.Number();
2773 pendFileSize = FrameOffset >= 0 ? FrameOffset : FileSize;
2774 pendMissing = MissingFrames;
2775 FrameOffset = -1;
2776 IndexFileWritten = true;
2777 Errors = FrameDetector.Errors();
2778 }
2779 FileSize += Processed;
2780 Buffer.Del(Processed);
2781 }
2782 }
2783 else if (PatPmtParser.Completed()) {
2784 // Step 2 - sync FrameDetector:
2785 int Processed = FrameDetector.Analyze(Data, Length, false);
2786 if (Processed > 0) {
2787 if (FrameDetector.Synced()) {
2788 // Synced FrameDetector, so rewind for actual processing:
2789 Rewind = true;
2790 }
2791 Buffer.Del(Processed);
2792 }
2793 }
2794 else {
2795 // Step 1 - parse PAT/PMT:
2796 uchar *p = Data;
2797 while (Length >= TS_SIZE) {
2798 int Pid = TsPid(p);
2799 if (Pid == PATPID)
2800 PatPmtParser.ParsePat(p, TS_SIZE);
2801 else if (PatPmtParser.IsPmtPid(Pid))
2802 PatPmtParser.ParsePmt(p, TS_SIZE);
2803 Length -= TS_SIZE;
2804 p += TS_SIZE;
2805 if (PatPmtParser.Completed()) {
2806 // Found pid, so rewind to sync FrameDetector:
2807 FrameDetector.SetPid(PatPmtParser.Vpid() ? PatPmtParser.Vpid() : PatPmtParser.Apid(0), PatPmtParser.Vpid() ? PatPmtParser.Vtype() : PatPmtParser.Atype(0));
2808 BufferChunks = IFG_BUFFER_SIZE;
2809 Rewind = true;
2810 break;
2811 }
2812 }
2813 Buffer.Del(p - Data);
2814 }
2815 }
2816 // Read data:
2817 else if (ReplayFile) {
2818 int Result = Buffer.Read(ReplayFile, BufferChunks);
2819 if (Result == 0) { // EOF
2820 if (Buffer.Available() > 0 && !Stuffed) {
2821 // So the last call to Buffer.Get() returned NULL, but there is still
2822 // data in the buffer, and we're at the end of the current TS file.
2823 // The remaining data in the buffer is less than what's needed for the
2824 // frame detector to analyze frames, so we need to put some stuffing
2825 // packets into the buffer to flush out the rest of the data (otherwise
2826 // any frames within the remaining data would not be seen here):
2827 uchar StuffingPacket[TS_SIZE] = { TS_SYNC_BYTE, 0xFF };
2828 for (int i = 0; i <= MIN_TS_PACKETS_FOR_FRAME_DETECTOR; i++)
2829 Buffer.Put(StuffingPacket, sizeof(StuffingPacket));
2830 Stuffed = true;
2831 }
2832 else {
2833 ReplayFile = FileName.NextFile();
2834 FileSize = 0;
2835 FrameOffset = -1;
2836 Buffer.Clear();
2837 Stuffed = false;
2838 }
2839 }
2840 }
2841 // Recording has been processed:
2842 else {
2843 bool PreviousErrors = false;
2844 Errors = FrameDetector.Errors(&PreviousErrors); // missing frames in the last GOP are tolerated
2845 if (pendNumber > 0)
2846 IndexFile.Write(pendIndependentFrame, pendNumber, pendFileSize, PreviousErrors, pendMissing);
2847 IndexFileComplete = true;
2848 break;
2849 }
2850 }
2852 if (IndexFileComplete) {
2853 if (IndexFileWritten) {
2854 cRecordingInfo RecordingInfo(recordingName);
2855 if (RecordingInfo.Read()) {
2856 if ((FrameDetector.FramesPerSecond() > 0 && !DoubleEqual(RecordingInfo.FramesPerSecond(), FrameDetector.FramesPerSecond())) ||
2857 FrameDetector.FrameWidth() != RecordingInfo.FrameWidth() ||
2858 FrameDetector.FrameHeight() != RecordingInfo.FrameHeight() ||
2859 FrameDetector.AspectRatio() != RecordingInfo.AspectRatio() ||
2860 Errors != RecordingInfo.Errors()) {
2861 RecordingInfo.SetFramesPerSecond(FrameDetector.FramesPerSecond());
2862 RecordingInfo.SetFrameParams(FrameDetector.FrameWidth(), FrameDetector.FrameHeight(), FrameDetector.ScanType(), FrameDetector.AspectRatio());
2863 RecordingInfo.SetErrors(Errors);
2864 RecordingInfo.Write();
2866 Recordings->UpdateByName(recordingName);
2867 }
2868 }
2869 Skins.QueueMessage(mtInfo, tr("Index file regeneration complete"));
2870 return;
2871 }
2872 else
2873 Skins.QueueMessage(mtError, tr("Index file regeneration failed!"));
2874 }
2875 // Delete the index file if the recording has not been processed entirely:
2876 IndexFile.Delete();
2877}
2878
2879// --- cIndexFile ------------------------------------------------------------
2880
2881#define INDEXFILESUFFIX "/index"
2882
2883// The maximum time to wait before giving up while catching up on an index file:
2884#define MAXINDEXCATCHUP 8 // number of retries
2885#define INDEXCATCHUPWAIT 100 // milliseconds
2886
2887struct __attribute__((packed)) tIndexPes {
2888 uint32_t offset;
2889 uchar type;
2890 uchar number;
2891 uint16_t reserved;
2892 };
2893
2894struct __attribute__((packed)) tIndexTs {
2895 uint64_t offset:40; // up to 1TB per file (not using off_t here - must definitely be exactly 64 bit!)
2896 int reserved:5; // reserved for future use
2897 int errors:1; // 1=this frame contains errors
2898 int missing:1; // 1=there are frames missing before this one
2899 int independent:1; // marks frames that can be displayed by themselves (for trick modes)
2900 uint16_t number:16; // up to 64K files per recording
2901 tIndexTs(off_t Offset, bool Independent, uint16_t Number, bool Errors, bool Missing)
2902 {
2903 offset = Offset;
2904 reserved = 0;
2905 errors = Errors;
2906 missing = Missing;
2907 independent = Independent;
2908 number = Number;
2909 }
2910 };
2911
2912#define MAXWAITFORINDEXFILE 10 // max. time to wait for the regenerated index file (seconds)
2913#define INDEXFILECHECKINTERVAL 500 // ms between checks for existence of the regenerated index file
2914#define INDEXFILETESTINTERVAL 10 // ms between tests for the size of the index file in case of pausing live video
2915
2916cIndexFile::cIndexFile(const char *FileName, bool Record, bool IsPesRecording, bool PauseLive)
2917:resumeFile(FileName, IsPesRecording)
2918{
2919 f = -1;
2920 size = 0;
2921 last = -1;
2923 index = NULL;
2924 isPesRecording = IsPesRecording;
2925 indexFileGenerator = NULL;
2926 if (FileName) {
2928 if (!Record && PauseLive) {
2929 // Wait until the index file contains at least two frames:
2930 time_t tmax = time(NULL) + MAXWAITFORINDEXFILE;
2931 while (time(NULL) < tmax && FileSize(fileName) < off_t(2 * sizeof(tIndexTs)))
2933 }
2934 int delta = 0;
2935 if (!Record && (access(fileName, R_OK) != 0 || FileSize(fileName) == 0 && time(NULL) - LastModifiedTime(fileName) > MAXWAITFORINDEXFILE)) {
2936 // Index file doesn't exist, so try to regenerate it:
2937 if (!isPesRecording) { // sorry, can only do this for TS recordings
2938 resumeFile.Delete(); // just in case
2940 // Wait until the index file exists:
2941 time_t tmax = time(NULL) + MAXWAITFORINDEXFILE;
2942 do {
2943 cCondWait::SleepMs(INDEXFILECHECKINTERVAL); // start with a sleep, to give it a head start
2944 } while (access(fileName, R_OK) != 0 && time(NULL) < tmax);
2945 }
2946 }
2947 if (access(fileName, R_OK) == 0) {
2948 struct stat buf;
2949 if (stat(fileName, &buf) == 0) {
2950 delta = int(buf.st_size % sizeof(tIndexTs));
2951 if (delta) {
2952 delta = sizeof(tIndexTs) - delta;
2953 esyslog("ERROR: invalid file size (%" PRId64 ") in '%s'", buf.st_size, *fileName);
2954 }
2955 last = int((buf.st_size + delta) / sizeof(tIndexTs) - 1);
2956 if (!Record && last >= 0) {
2957 size = last + 1;
2958 index = MALLOC(tIndexTs, size);
2959 if (index) {
2960 f = open(fileName, O_RDONLY);
2961 if (f >= 0) {
2962 if (safe_read(f, index, size_t(buf.st_size)) != buf.st_size) {
2963 esyslog("ERROR: can't read from file '%s'", *fileName);
2964 free(index);
2965 size = 0;
2966 last = -1;
2967 index = NULL;
2968 }
2969 else if (isPesRecording)
2971 if (!index || !StillRecording(FileName)) {
2972 close(f);
2973 f = -1;
2974 }
2975 // otherwise we don't close f here, see CatchUp()!
2976 }
2977 else
2979 }
2980 else {
2981 esyslog("ERROR: can't allocate %zd bytes for index '%s'", size * sizeof(tIndexTs), *fileName);
2982 size = 0;
2983 last = -1;
2984 }
2985 }
2986 }
2987 else
2988 LOG_ERROR;
2989 }
2990 else if (!Record)
2991 isyslog("missing index file %s", *fileName);
2992 if (Record) {
2993 if ((f = open(fileName, O_WRONLY | O_CREAT | O_APPEND, DEFFILEMODE)) >= 0) {
2994 if (delta) {
2995 esyslog("ERROR: padding index file with %d '0' bytes", delta);
2996 while (delta--)
2997 writechar(f, 0);
2998 }
2999 }
3000 else
3002 }
3003 }
3004}
3005
3007{
3008 if (f >= 0)
3009 close(f);
3010 free(index);
3011 delete indexFileGenerator;
3012}
3013
3014cString cIndexFile::IndexFileName(const char *FileName, bool IsPesRecording)
3015{
3016 return cString::sprintf("%s%s", FileName, IsPesRecording ? INDEXFILESUFFIX ".vdr" : INDEXFILESUFFIX);
3017}
3018
3019void cIndexFile::ConvertFromPes(tIndexTs *IndexTs, int Count)
3020{
3021 tIndexPes IndexPes;
3022 while (Count-- > 0) {
3023 memcpy(&IndexPes, IndexTs, sizeof(IndexPes));
3024 IndexTs->offset = IndexPes.offset;
3025 IndexTs->independent = IndexPes.type == 1; // I_FRAME
3026 IndexTs->number = IndexPes.number;
3027 IndexTs++;
3028 }
3029}
3030
3031void cIndexFile::ConvertToPes(tIndexTs *IndexTs, int Count)
3032{
3033 tIndexPes IndexPes;
3034 while (Count-- > 0) {
3035 IndexPes.offset = uint32_t(IndexTs->offset);
3036 IndexPes.type = uchar(IndexTs->independent ? 1 : 2); // I_FRAME : "not I_FRAME" (exact frame type doesn't matter)
3037 IndexPes.number = uchar(IndexTs->number);
3038 IndexPes.reserved = 0;
3039 memcpy((void *)IndexTs, &IndexPes, sizeof(*IndexTs));
3040 IndexTs++;
3041 }
3042}
3043
3044bool cIndexFile::CatchUp(int Index)
3045{
3046 // returns true unless something really goes wrong, so that 'index' becomes NULL
3047 cMutexLock MutexLock(&mutex); // 'f' may be closed by another thread's CatchUp(), even while this one waits below
3048 if (index && f >= 0) {
3049 // Note that CatchUp() is triggered even if Index is 'last' (and thus valid).
3050 // This is done to make absolutely sure we don't miss any data at the very end.
3051 for (int i = 0; f >= 0 && i <= MAXINDEXCATCHUP && (Index < 0 || Index >= last); i++) {
3052 // Checked before reading: the timer file is removed after the last index entry has been written.
3053 bool Ended = !StillRecording(*cString(*fileName, strrchr(*fileName, '/')));
3054 struct stat buf;
3055 if (fstat(f, &buf) == 0) {
3056 int newLast = int(buf.st_size / sizeof(tIndexTs) - 1);
3057 if (newLast > last) {
3058 int NewSize = size;
3059 if (NewSize <= newLast) {
3060 NewSize *= 2;
3061 if (NewSize <= newLast)
3062 NewSize = newLast + 1;
3063 }
3064 if (tIndexTs *NewBuffer = (tIndexTs *)realloc(index, NewSize * sizeof(tIndexTs))) {
3065 size = NewSize;
3066 index = NewBuffer;
3067 int offset = (last + 1) * sizeof(tIndexTs);
3068 int delta = (newLast - last) * sizeof(tIndexTs);
3069 if (lseek(f, offset, SEEK_SET) == offset) {
3070 if (safe_read(f, &index[last + 1], delta) != delta) {
3071 esyslog("ERROR: can't read from index");
3072 free(index);
3073 index = NULL;
3074 close(f);
3075 f = -1;
3076 break;
3077 }
3078 if (isPesRecording)
3079 ConvertFromPes(&index[last + 1], newLast - last);
3080 last = newLast;
3081 }
3082 else
3084 }
3085 else {
3086 esyslog("ERROR: can't realloc() index");
3087 break;
3088 }
3089 }
3090 }
3091 else
3093 if (Index < last)
3094 break;
3095 if (Ended) {
3096 // nothing more will come, so don't wait for it on every read past the end
3097 close(f);
3098 f = -1;
3099 break;
3100 }
3101 cCondVar CondVar;
3103 }
3104 }
3105 return index != NULL;
3106}
3107
3108bool cIndexFile::Write(bool Independent, uint16_t FileNumber, off_t FileOffset, bool Errors, bool Missing)
3109{
3110 if (f >= 0) {
3111 tIndexTs i(FileOffset, Independent, FileNumber, Errors, Missing);
3112 if (isPesRecording)
3113 ConvertToPes(&i, 1);
3114 if (safe_write(f, &i, sizeof(i)) < 0) {
3116 close(f);
3117 f = -1;
3118 return false;
3119 }
3120 last++;
3121 }
3122 return f >= 0;
3123}
3124
3125bool cIndexFile::Get(int Index, uint16_t *FileNumber, off_t *FileOffset, bool *Independent, int *Length, bool *Errors, bool *Missing)
3126{
3127 if (CatchUp(Index)) {
3128 if (Index >= 0 && Index <= last) {
3129 *FileNumber = index[Index].number;
3130 *FileOffset = index[Index].offset;
3131 if (Independent)
3132 *Independent = index[Index].independent;
3133 if (Length) {
3134 if (Index < last) {
3135 uint16_t fn = index[Index + 1].number;
3136 off_t fo = index[Index + 1].offset;
3137 if (fn == *FileNumber)
3138 *Length = int(fo - *FileOffset);
3139 else
3140 *Length = -1; // this means "everything up to EOF" (the buffer's Read function will act accordingly)
3141 }
3142 else
3143 *Length = -1;
3144 }
3145 if (Errors)
3146 *Errors = index[Index].errors;
3147 if (Missing)
3148 *Missing = index[Index].missing;
3149 return true;
3150 }
3151 }
3152 return false;
3153}
3154
3156{
3157 for (int Index = lastErrorIndex + 1; Index <= last; Index++) {
3158 tIndexTs *p = &index[Index];
3159 if (p->errors || p->missing)
3160 errors.Append(Index);
3161 }
3163 return &errors;
3164}
3165
3166int cIndexFile::GetNextIFrame(int Index, bool Forward, uint16_t *FileNumber, off_t *FileOffset, int *Length)
3167{
3168 if (CatchUp()) {
3169 int d = Forward ? 1 : -1;
3170 for (;;) {
3171 Index += d;
3172 if (Index >= 0 && Index <= last) {
3173 if (index[Index].independent) {
3174 uint16_t fn;
3175 if (!FileNumber)
3176 FileNumber = &fn;
3177 off_t fo;
3178 if (!FileOffset)
3179 FileOffset = &fo;
3180 *FileNumber = index[Index].number;
3181 *FileOffset = index[Index].offset;
3182 if (Length) {
3183 if (Index < last) {
3184 uint16_t fn = index[Index + 1].number;
3185 off_t fo = index[Index + 1].offset;
3186 if (fn == *FileNumber)
3187 *Length = int(fo - *FileOffset);
3188 else
3189 *Length = -1; // this means "everything up to EOF" (the buffer's Read function will act accordingly)
3190 }
3191 else
3192 *Length = -1;
3193 }
3194 return Index;
3195 }
3196 }
3197 else
3198 break;
3199 }
3200 }
3201 return -1;
3202}
3203
3205{
3206 if (index && last > 0) {
3207 Index = constrain(Index, 0, last);
3208 if (index[Index].independent)
3209 return Index;
3210 int il = Index - 1;
3211 int ih = Index + 1;
3212 for (;;) {
3213 if (il >= 0) {
3214 if (index[il].independent)
3215 return il;
3216 il--;
3217 }
3218 else if (ih > last)
3219 break;
3220 if (ih <= last) {
3221 if (index[ih].independent)
3222 return ih;
3223 ih++;
3224 }
3225 else if (il < 0)
3226 break;
3227 }
3228 }
3229 return 0;
3230}
3231
3232int cIndexFile::Get(uint16_t FileNumber, off_t FileOffset)
3233{
3234 if (CatchUp()) {
3235 //TODO implement binary search!
3236 int i;
3237 for (i = 0; i <= last; i++) {
3238 if (index[i].number > FileNumber || (index[i].number == FileNumber) && off_t(index[i].offset) >= FileOffset)
3239 break;
3240 }
3241 return i;
3242 }
3243 return -1;
3244}
3245
3247{
3248 cMutexLock MutexLock(&mutex); // CatchUp() closes 'f' once the recording has ended
3249 return f >= 0;
3250}
3251
3253{
3254 if (*fileName) {
3255 dsyslog("deleting index file '%s'", *fileName);
3256 if (f >= 0) {
3257 close(f);
3258 f = -1;
3259 }
3260 unlink(fileName);
3261 }
3262}
3263
3264int cIndexFile::GetLength(const char *FileName, bool IsPesRecording)
3265{
3266 struct stat buf;
3267 cString s = IndexFileName(FileName, IsPesRecording);
3268 if (*s && stat(s, &buf) == 0)
3269 return buf.st_size / (IsPesRecording ? sizeof(tIndexTs) : sizeof(tIndexPes));
3270 return -1;
3271}
3272
3273bool GenerateIndex(const char *FileName)
3274{
3275 if (DirectoryOk(FileName)) {
3276 cRecording Recording(FileName);
3277 if (Recording.Name()) {
3278 if (!Recording.IsPesRecording()) {
3279 cString IndexFileName = AddDirectory(FileName, INDEXFILESUFFIX);
3280 unlink(IndexFileName);
3281 cIndexFileGenerator *IndexFileGenerator = new cIndexFileGenerator(FileName);
3282 while (IndexFileGenerator->Active())
3284 if (access(IndexFileName, R_OK) == 0)
3285 return true;
3286 else
3287 fprintf(stderr, "cannot create '%s'\n", *IndexFileName);
3288 }
3289 else
3290 fprintf(stderr, "'%s' is not a TS recording\n", FileName);
3291 }
3292 else
3293 fprintf(stderr, "'%s' is not a recording\n", FileName);
3294 }
3295 else
3296 fprintf(stderr, "'%s' is not a directory\n", FileName);
3297 return false;
3298}
3299
3300// --- cFileName -------------------------------------------------------------
3301
3302#define MAXFILESPERRECORDINGPES 255
3303#define RECORDFILESUFFIXPES "/%03d.vdr"
3304#define MAXFILESPERRECORDINGTS 65535
3305#define RECORDFILESUFFIXTS "/%05d.ts"
3306#define RECORDFILESUFFIXLEN 20 // some additional bytes for safety...
3307
3308cFileName::cFileName(const char *FileName, bool Record, bool Blocking, bool IsPesRecording)
3309{
3310 file = NULL;
3311 fileNumber = 0;
3312 record = Record;
3313 blocking = Blocking;
3314 isPesRecording = IsPesRecording;
3315 // Prepare the file name:
3316 fileName = MALLOC(char, strlen(FileName) + RECORDFILESUFFIXLEN);
3317 if (!fileName) {
3318 esyslog("ERROR: can't copy file name '%s'", FileName);
3319 return;
3320 }
3321 strcpy(fileName, FileName);
3322 pFileNumber = fileName + strlen(fileName);
3323 SetOffset(1);
3324}
3325
3327{
3328 Close();
3329 free(fileName);
3330}
3331
3332bool cFileName::GetLastPatPmtVersions(int &PatVersion, int &PmtVersion)
3333{
3334 if (fileName && !isPesRecording) {
3335 // Find the last recording file:
3336 int Number = 1;
3337 for (; Number <= MAXFILESPERRECORDINGTS + 1; Number++) { // +1 to correctly set Number in case there actually are that many files
3339 if (access(fileName, F_OK) != 0) { // file doesn't exist
3340 Number--;
3341 break;
3342 }
3343 }
3344 for (; Number > 0; Number--) {
3345 // Search for a PAT packet from the end of the file:
3346 cPatPmtParser PatPmtParser;
3348 int fd = open(fileName, O_RDONLY | O_LARGEFILE, DEFFILEMODE);
3349 if (fd >= 0) {
3350 off_t pos = lseek(fd, -TS_SIZE, SEEK_END);
3351 while (pos >= 0) {
3352 // Read and parse the PAT/PMT:
3353 uchar buf[TS_SIZE];
3354 while (read(fd, buf, sizeof(buf)) == sizeof(buf)) {
3355 if (buf[0] == TS_SYNC_BYTE) {
3356 int Pid = TsPid(buf);
3357 if (Pid == PATPID)
3358 PatPmtParser.ParsePat(buf, sizeof(buf));
3359 else if (PatPmtParser.IsPmtPid(Pid)) {
3360 PatPmtParser.ParsePmt(buf, sizeof(buf));
3361 if (PatPmtParser.GetVersions(PatVersion, PmtVersion)) {
3362 close(fd);
3363 return true;
3364 }
3365 }
3366 else
3367 break; // PAT/PMT is always in one sequence
3368 }
3369 else
3370 return false;
3371 }
3372 pos = lseek(fd, pos - TS_SIZE, SEEK_SET);
3373 }
3374 close(fd);
3375 }
3376 else
3377 break;
3378 }
3379 }
3380 return false;
3381}
3382
3384{
3385 if (!file) {
3386 int BlockingFlag = blocking ? 0 : O_NONBLOCK;
3387 if (record) {
3388 dsyslog("recording to '%s'", fileName);
3389 file = cVideoDirectory::OpenVideoFile(fileName, O_RDWR | O_CREAT | O_LARGEFILE | BlockingFlag);
3390 if (!file)
3392 }
3393 else {
3394 if (access(fileName, R_OK) == 0) {
3395 dsyslog("playing '%s'", fileName);
3396 file = cUnbufferedFile::Create(fileName, O_RDONLY | O_LARGEFILE | BlockingFlag);
3397 if (!file)
3399 }
3400 else if (errno != ENOENT)
3402 }
3403 }
3404 return file;
3405}
3406
3408{
3409 if (file) {
3410 if (file->Close() < 0)
3412 delete file;
3413 file = NULL;
3414 }
3415}
3416
3418{
3419 if (fileNumber != Number)
3420 Close();
3421 int MaxFilesPerRecording = isPesRecording ? MAXFILESPERRECORDINGPES : MAXFILESPERRECORDINGTS;
3422 if (0 < Number && Number <= MaxFilesPerRecording) {
3423 fileNumber = uint16_t(Number);
3425 if (record) {
3426 if (access(fileName, F_OK) == 0) {
3427 // file exists, check if it has non-zero size
3428 struct stat buf;
3429 if (stat(fileName, &buf) == 0) {
3430 if (buf.st_size != 0)
3431 return SetOffset(Number + 1); // file exists and has non zero size, let's try next suffix
3432 else {
3433 // zero size file, remove it
3434 dsyslog("cFileName::SetOffset: removing zero-sized file %s", fileName);
3435 unlink(fileName);
3436 }
3437 }
3438 else
3439 return SetOffset(Number + 1); // error with fstat - should not happen, just to be on the safe side
3440 }
3441 else if (errno != ENOENT) { // something serious has happened
3443 return NULL;
3444 }
3445 // found a non existing file suffix
3446 }
3447 if (Open()) {
3448 if (!record && Offset >= 0 && file->Seek(Offset, SEEK_SET) != Offset) {
3450 return NULL;
3451 }
3452 }
3453 return file;
3454 }
3455 esyslog("ERROR: max number of files (%d) exceeded", MaxFilesPerRecording);
3456 return NULL;
3457}
3458
3460{
3461 return SetOffset(fileNumber + 1);
3462}
3463
3464// --- cDoneRecordings -------------------------------------------------------
3465
3467
3468bool cDoneRecordings::Load(const char *FileName)
3469{
3470 fileName = FileName;
3471 if (*fileName && access(fileName, F_OK) == 0) {
3472 isyslog("loading %s", *fileName);
3473 FILE *f = fopen(fileName, "r");
3474 if (f) {
3475 char *s;
3476 cReadLine ReadLine;
3477 while ((s = ReadLine.Read(f)) != NULL)
3478 Add(s);
3479 fclose(f);
3480 }
3481 else {
3483 return false;
3484 }
3485 }
3486 return true;
3487}
3488
3490{
3491 bool result = true;
3493 if (f.Open()) {
3494 for (int i = 0; i < doneRecordings.Size(); i++) {
3495 if (fputs(doneRecordings[i], f) == EOF || fputc('\n', f) == EOF) {
3496 result = false;
3497 break;
3498 }
3499 }
3500 if (!f.Close())
3501 result = false;
3502 }
3503 else
3504 result = false;
3505 return result;
3506}
3507
3508void cDoneRecordings::Add(const char *Title)
3509{
3510 doneRecordings.Append(strdup(Title));
3511}
3512
3513void cDoneRecordings::Append(const char *Title)
3514{
3515 if (!Contains(Title)) {
3516 Add(Title);
3517 if (FILE *f = fopen(fileName, "a")) {
3518 fputs(Title, f);
3519 fputc('\n', f);
3520 fclose(f);
3521 }
3522 else
3523 esyslog("ERROR: can't open '%s' for appending '%s'", *fileName, Title);
3524 }
3525}
3526
3527static const char *FuzzyChars = " -:/";
3528
3529static const char *SkipFuzzyChars(const char *s)
3530{
3531 while (*s && strchr(FuzzyChars, *s))
3532 s++;
3533 return s;
3534}
3535
3536bool cDoneRecordings::Contains(const char *Title) const
3537{
3538 for (int i = 0; i < doneRecordings.Size(); i++) {
3539 const char *s = doneRecordings[i];
3540 const char *t = Title;
3541 while (*s && *t) {
3542 s = SkipFuzzyChars(s);
3543 t = SkipFuzzyChars(t);
3544 if (!*s || !*t)
3545 break;
3546 if (toupper(uchar(*s)) != toupper(uchar(*t)))
3547 break;
3548 s++;
3549 t++;
3550 }
3551 if (!*s && !*t)
3552 return true;
3553 }
3554 return false;
3555}
3556
3557// --- Index stuff -----------------------------------------------------------
3558
3559cString IndexToHMSF(int Index, bool WithFrame, double FramesPerSecond)
3560{
3561 const char *Sign = "";
3562 if (Index < 0) {
3563 Index = -Index;
3564 Sign = "-";
3565 }
3566 double Seconds;
3567 int f = int(modf((Index + 0.5) / FramesPerSecond, &Seconds) * FramesPerSecond);
3568 int s = int(Seconds);
3569 int m = s / 60 % 60;
3570 int h = s / 3600;
3571 s %= 60;
3572 return cString::sprintf(WithFrame ? "%s%d:%02d:%02d.%02d" : "%s%d:%02d:%02d", Sign, h, m, s, f);
3573}
3574
3575int HMSFToIndex(const char *HMSF, double FramesPerSecond)
3576{
3577 int h, m, s, f = 0;
3578 int n = sscanf(HMSF, "%d:%d:%d.%d", &h, &m, &s, &f);
3579 if (n == 1)
3580 return h; // plain frame number
3581 if (n >= 3)
3582 return int(round((h * 3600 + m * 60 + s) * FramesPerSecond)) + f;
3583 return 0;
3584}
3585
3586int SecondsToFrames(int Seconds, double FramesPerSecond)
3587{
3588 return int(round(Seconds * FramesPerSecond));
3589}
3590
3591// --- ReadFrame -------------------------------------------------------------
3592
3593int ReadFrame(cUnbufferedFile *f, uchar *b, int Length, int Max)
3594{
3595 if (Length == -1)
3596 Length = Max; // this means we read up to EOF (see cIndex)
3597 else if (Length > Max) {
3598 esyslog("ERROR: frame larger than buffer (%d > %d)", Length, Max);
3599 Length = Max;
3600 }
3601 int r = f->Read(b, Length);
3602 if (r < 0)
3603 LOG_ERROR;
3604 return r;
3605}
3606
3607// --- Recordings Sort Mode --------------------------------------------------
3608
3610
3611bool HasRecordingsSortMode(const char *Directory)
3612{
3613 return access(AddDirectory(Directory, SORTMODEFILE), R_OK) == 0;
3614}
3615
3616void GetRecordingsSortMode(const char *Directory)
3617{
3619 if (FILE *f = fopen(AddDirectory(Directory, SORTMODEFILE), "r")) {
3620 char buf[8];
3621 if (fgets(buf, sizeof(buf), f))
3623 fclose(f);
3624 }
3625}
3626
3627void SetRecordingsSortMode(const char *Directory, eRecordingsSortMode SortMode)
3628{
3629 if (FILE *f = fopen(AddDirectory(Directory, SORTMODEFILE), "w")) {
3630 fputs(cString::sprintf("%d\n", SortMode), f);
3631 fclose(f);
3632 }
3633}
3634
3643
3644// --- Recording Timer Indicator ---------------------------------------------
3645
3646void SetRecordingTimerId(const char *Directory, const char *TimerId)
3647{
3648 cString FileName = AddDirectory(Directory, TIMERRECFILE);
3649 if (TimerId) {
3650 dsyslog("writing timer id '%s' to %s", TimerId, *FileName);
3651 if (FILE *f = fopen(FileName, "w")) {
3652 fprintf(f, "%s\n", TimerId);
3653 fclose(f);
3654 }
3655 else
3656 LOG_ERROR_STR(*FileName);
3657 }
3658 else {
3659 dsyslog("removing %s", *FileName);
3660 unlink(FileName);
3661 }
3662}
3663
3664cString GetRecordingTimerId(const char *Directory)
3665{
3666 cString FileName = AddDirectory(Directory, TIMERRECFILE);
3667 const char *Id = NULL;
3668 if (FILE *f = fopen(FileName, "r")) {
3669 char buf[HOST_NAME_MAX + 10]; // +10 for numeric timer id and '@'
3670 if (fgets(buf, sizeof(buf), f)) {
3671 stripspace(buf);
3672 Id = buf;
3673 }
3674 fclose(f);
3675 }
3676 return Id;
3677}
3678
3679void ClrRecordingTimerId(const char *Directory)
3680{
3681 cString TimerId = GetRecordingTimerId(Directory);
3682 if (*TimerId) {
3683 if (const char *p = strchr(TimerId, '@')) {
3684 if (strcmp(p + 1, Setup.SVDRPHostName) == 0) {
3685 dsyslog("found stale recording timer id %s", *TimerId);
3686 SetRecordingTimerId(Directory, NULL);
3687 }
3688 }
3689 }
3690}
3691
3692// --- Disk space calculation for editing ------------------------------------
3693
3694int FileSizeMBafterEdit(const char *FileName)
3695{
3696 int FileSizeMB = DirSizeMB(FileName);
3697 if (FileSizeMB > 0) {
3698 cRecording r(FileName);
3699 int NumFramesOrg = r.NumFrames();
3700 if (NumFramesOrg > 0) {
3701 int NumFramesEdit = r.NumFramesAfterEdit();
3702 if (NumFramesEdit > 0)
3703 return max(1, int(FileSizeMB * (double(NumFramesEdit) / NumFramesOrg)));
3704 }
3705 }
3706 return -1;
3707}
3708
3709bool EnoughFreeDiskSpaceForEdit(const char *FileName)
3710{
3711 int FileSizeMB = FileSizeMBafterEdit(FileName);
3712 if (FileSizeMB > 0) {
3713 int FreeDiskMB;
3715 cString EditedFileName = cCutter::EditedFileName(FileName);
3716 if (access(EditedFileName, F_OK)) {
3717 int ExistingEditedSizeMB = DirSizeMB(EditedFileName);
3718 if (ExistingEditedSizeMB > 0)
3719 FreeDiskMB += ExistingEditedSizeMB;
3720 }
3721 FreeDiskMB -= RecordingsHandler.GetRequiredDiskSpaceMB(FileName);
3722 FreeDiskMB -= MINDISKSPACE;
3723 return FileSizeMB < FreeDiskMB;
3724 }
3725 return false;
3726}
#define MAXDPIDS
Definition channels.h:32
#define MAXAPIDS
Definition channels.h:31
#define MAXSPIDS
Definition channels.h:33
const char * Slang(int i) const
Definition channels.h:168
int Number(void) const
Definition channels.h:187
const char * Name(void) const
Definition channels.c:121
tChannelID GetChannelID(void) const
Definition channels.h:199
const char * Dlang(int i) const
Definition channels.h:167
const char * Alang(int i) const
Definition channels.h:166
tComponent * GetComponent(int Index, uchar Stream, uchar Type)
Definition epg.c:97
int NumComponents(void) const
Definition epg.h:62
void SetComponent(int Index, const char *s)
Definition epg.c:77
bool TimedWait(cMutex &Mutex, int TimeoutMs)
Definition thread.c:135
static void SleepMs(int TimeoutMs)
Creates a cCondWait object and uses it to sleep for TimeoutMs milliseconds, immediately giving up the...
Definition thread.c:73
bool Save(void) const
Definition config.h:179
bool Load(const char *FileName=NULL, bool AllowComments=false, bool MustExist=false)
Definition config.h:132
bool Start(void)
Starts the actual cutting process.
Definition cutter.c:734
cCutter(const char *FileName)
Sets up a new cutter for the given FileName, which must be the full path name of an existing recordin...
Definition cutter.c:709
bool Error(void)
Returns true if an error occurred while cutting the recording.
Definition cutter.c:790
bool Active(void)
Returns true if the cutter is currently active.
Definition cutter.c:777
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:722
virtual ~cDirCopier() override
Definition recording.c:1987
virtual void Action(void) override
A derived cThread class must implement the code it wants to execute as a separate thread in this func...
Definition recording.c:2008
cDirCopier(const char *DirNameSrc, const char *DirNameDst)
Definition recording.c:1978
cString dirNameDst
Definition recording.c:1967
bool suspensionLogged
Definition recording.c:1969
bool Throttled(void)
Definition recording.c:1992
cString dirNameSrc
Definition recording.c:1966
bool Error(void)
Definition recording.c:1975
cStringList doneRecordings
Definition recording.h:588
bool Save(void) const
Definition recording.c:3489
void Add(const char *Title)
Definition recording.c:3508
cString fileName
Definition recording.h:587
void Append(const char *Title)
Definition recording.c:3513
bool Load(const char *FileName)
Definition recording.c:3468
bool Contains(const char *Title) const
Definition recording.c:3536
Definition epg.h:74
const char * ShortText(void) const
Definition epg.h:109
const cComponents * Components(void) const
Definition epg.h:111
cEvent(tEventID EventID)
Definition epg.c:115
bool Parse(char *s)
Definition epg.c:501
const char * Title(void) const
Definition epg.h:108
void SetStartTime(time_t StartTime)
Definition epg.c:225
void SetComponents(cComponents *Components)
Definition epg.c:208
void SetEventID(tEventID EventID)
Definition epg.c:160
void SetVersion(uchar Version)
Definition epg.c:176
void SetDuration(int Duration)
Definition epg.c:236
void SetTitle(const char *Title)
Definition epg.c:193
void SetTableID(uchar TableID)
Definition epg.c:171
bool isPesRecording
Definition recording.h:571
cUnbufferedFile * NextFile(void)
Definition recording.c:3459
uint16_t Number(void)
Definition recording.h:576
bool record
Definition recording.h:569
void Close(void)
Definition recording.c:3407
uint16_t fileNumber
Definition recording.h:567
cUnbufferedFile * Open(void)
Definition recording.c:3383
cFileName(const char *FileName, bool Record, bool Blocking=false, bool IsPesRecording=false)
Definition recording.c:3308
char * fileName
Definition recording.h:568
char * pFileNumber
Definition recording.h:568
bool GetLastPatPmtVersions(int &PatVersion, int &PmtVersion)
Definition recording.c:3332
bool blocking
Definition recording.h:570
cUnbufferedFile * SetOffset(int Number, off_t Offset=0)
Definition recording.c:3417
cUnbufferedFile * file
Definition recording.h:566
bool Synced(void)
Returns true if the frame detector has synced on the data stream.
Definition remux.h:607
bool IndependentFrame(void)
Returns true if a new frame was detected and this is an independent frame (i.e.
Definition remux.h:617
double FramesPerSecond(void)
Returns the number of frames per second, or 0 if this information is not available.
Definition remux.h:621
uint16_t FrameWidth(void)
Returns the frame width, or 0 if this information is not available.
Definition remux.h:624
int Errors(bool *PreviousErrors=NULL, bool *MissingFrames=NULL)
Returns the total number of errors so far.
Definition remux.c:2260
eScanType ScanType(void)
Returns the scan type, or stUnknown if this information is not available.
Definition remux.h:628
bool NewFrame(int *PreviousErrors=NULL, int *MissingFrames=NULL)
Definition remux.c:2271
int Analyze(const uchar *Data, int Length, bool ErrorCheck=true)
Analyzes the TS packets pointed to by Data.
Definition remux.c:2292
uint16_t FrameHeight(void)
Returns the frame height, or 0 if this information is not available.
Definition remux.h:626
void SetPid(int Pid, int Type)
Sets the Pid and stream Type to detect frames for.
Definition remux.c:2234
eAspectRatio AspectRatio(void)
Returns the aspect ratio, or arUnknown if this information is not available.
Definition remux.h:630
cIndexFileGenerator(const char *RecordingName)
Definition recording.c:2703
virtual void Action(void) override
A derived cThread class must implement the code it wants to execute as a separate thread in this func...
Definition recording.c:2715
int GetNextIFrame(int Index, bool Forward, uint16_t *FileNumber=NULL, off_t *FileOffset=NULL, int *Length=NULL)
Definition recording.c:3166
bool Write(bool Independent, uint16_t FileNumber, off_t FileOffset, bool Errors=false, bool Missing=false)
Definition recording.c:3108
cResumeFile resumeFile
Definition recording.h:527
bool IsStillRecording(void)
Definition recording.c:3246
void ConvertFromPes(tIndexTs *IndexTs, int Count)
Definition recording.c:3019
cIndexFile(const char *FileName, bool Record, bool IsPesRecording=false, bool PauseLive=false)
Definition recording.c:2916
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:3264
bool CatchUp(int Index=-1)
Definition recording.c:3044
const cErrors * GetErrors(void)
Returns the frame indexes of errors in the recording (if any).
Definition recording.c:3155
void ConvertToPes(tIndexTs *IndexTs, int Count)
Definition recording.c:3031
bool isPesRecording
Definition recording.h:526
cErrors errors
Definition recording.h:528
int lastErrorIndex
Definition recording.h:524
cString fileName
Definition recording.h:522
cIndexFileGenerator * indexFileGenerator
Definition recording.h:529
static cString IndexFileName(const char *FileName, bool IsPesRecording)
Definition recording.c:3014
int GetClosestIFrame(int Index)
Returns the index of the I-frame that is closest to the given Index (or Index itself,...
Definition recording.c:3204
cMutex mutex
Definition recording.h:530
bool Get(int Index, uint16_t *FileNumber, off_t *FileOffset, bool *Independent=NULL, int *Length=NULL, bool *Errors=NULL, bool *Missing=NULL)
Definition recording.c:3125
void Delete(void)
Definition recording.c:3252
tIndexTs * index
Definition recording.h:525
static bool Engaged(void)
Returns true if any I/O throttling object is currently active.
Definition thread.c:963
virtual void Clear(void)
Definition tools.c:2305
void Del(cListObject *Object, bool DeleteObject=true)
Definition tools.c:2260
void SetExplicitModify(void)
If you have obtained a write lock on this list, and you don't want it to be automatically marked as m...
Definition tools.c:2325
void SetModified(void)
Unconditionally marks this list as modified.
Definition tools.c:2330
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:2219
int Count(void) const
Definition tools.h:646
void Add(cListObject *Object, cListObject *After=NULL)
Definition tools.c:2228
cListObject(const cListObject &ListObject)
Definition tools.h:553
cListObject * Next(void) const
Definition tools.h:566
const cMark * Prev(const cMark *Object) const
Definition tools.h:666
const T * First(void) const
Returns the first element in this list, or NULL if the list is empty.
Definition tools.h:662
cList(const char *NeedsLocking=NULL)
Definition tools.h:652
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:669
const cMark * Last(void) const
Definition tools.h:664
bool Lock(int WaitSeconds=0)
Definition tools.c:2067
cMark(int Position=0, const char *Comment=NULL, double FramesPerSecond=DEFAULTFRAMESPERSECOND)
Definition recording.c:2426
cString comment
Definition recording.h:415
int position
Definition recording.h:414
bool Parse(const char *s)
Definition recording.c:2442
bool Save(FILE *f)
Definition recording.c:2456
cString ToText(void)
Definition recording.c:2437
const char * Comment(void) const
Definition recording.h:420
double framesPerSecond
Definition recording.h:413
int Position(void) const
Definition recording.h:419
virtual ~cMark() override
Definition recording.c:2433
int GetNumSequences(void) const
Returns the actual number of sequences to be cut from the recording.
Definition recording.c:2622
double framesPerSecond
Definition recording.h:432
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:2555
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:2588
const cMark * GetNext(int Position) const
Definition recording.c:2579
bool Update(void)
Definition recording.c:2491
bool Load(const char *RecordingFileName, double FramesPerSecond=DEFAULTFRAMESPERSECOND, bool IsPesRecording=false)
Definition recording.c:2479
time_t lastFileTime
Definition recording.h:435
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:2604
const cMark * Get(int Position) const
Definition recording.c:2561
cString recordingFileName
Definition recording.h:430
bool isPesRecording
Definition recording.h:433
time_t nextUpdate
Definition recording.h:434
cString fileName
Definition recording.h:431
static bool DeleteMarksFile(const cRecording *Recording)
Definition recording.c:2468
void Align(void)
Definition recording.c:2531
int GetFrameAfterEdit(int Frame, int LastFrame) const
Returns the number of the given Frame within the region covered by begin/end sequences.
Definition recording.c:2639
void Sort(void)
Definition recording.c:2543
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:2463
bool Save(void)
Definition recording.c:2522
const cMark * GetPrev(int Position) const
Definition recording.c:2570
time_t lastChange
Definition recording.h:436
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:959
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:413
void ParsePat(const uchar *Data, int Length)
Parses the PAT data from the single TS packet in Data.
Definition remux.c:648
bool ParsePatPmt(const uchar *Data, int Length)
Parses the given Data (which may consist of several TS packets, typically an entire frame) and extrac...
Definition remux.c:940
int Apid(int i) const
Definition remux.h:421
void ParsePmt(const uchar *Data, int Length)
Parses the PMT data from the single TS packet in Data.
Definition remux.c:680
bool Completed(void)
Returns true if the PMT has been completely parsed.
Definition remux.h:416
bool IsPmtPid(int Pid) const
Returns true if Pid the one of the PMT pids as defined by the current PAT.
Definition remux.h:404
int Atype(int i) const
Definition remux.h:424
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:407
struct dirent * Next(void)
Definition tools.c:1657
bool Ok(void)
Definition tools.h:476
char * Read(FILE *f)
Definition tools.c:1574
static cRecordControl * GetRecordControl(const char *FileName)
Definition menu.c:5908
char ScanTypeChar(void) const
Definition recording.h:109
void SetFramesPerSecond(double FramesPerSecond)
Definition recording.c:499
cEvent * ownEvent
Definition recording.h:77
int TmpErrors(void) const
Definition recording.h:123
uint16_t FrameHeight(void) const
Definition recording.h:107
const cEvent * event
Definition recording.h:76
uint16_t frameHeight
Definition recording.h:81
void SetTitle(const char *Title)
Definition recording.c:514
void SetDescription(const char *Description)
Definition recording.c:524
int Errors(void) const
Definition recording.h:122
const char * AspectRatioText(void) const
Definition recording.h:111
int Priority(void) const
Definition recording.h:103
const char * ShortText(void) const
Definition recording.h:98
eAspectRatio aspectRatio
Definition recording.h:83
eScanType ScanType(void) const
Definition recording.h:108
int Lifetime(void) const
Definition recording.h:104
cRecordingInfo(const cChannel *Channel=NULL, const cEvent *Event=NULL)
Definition recording.c:390
bool Write(void) const
Definition recording.c:697
int ParentalRating(void)
Definition recording.h:105
void SetLifetime(int Lifetime)
Definition recording.c:509
bool Write(FILE *f, const char *Prefix="") const
Definition recording.c:659
const char * Title(void) const
Definition recording.h:97
tChannelID channelID
Definition recording.h:74
cString FrameParams(void) const
Definition recording.c:713
const char * Aux(void) const
Definition recording.h:101
eScanType scanType
Definition recording.h:82
void SetFileName(const char *FileName)
Definition recording.c:542
void SetPriority(int Priority)
Definition recording.c:504
void SetParentalRating(int ParentalRating)
Definition recording.c:529
time_t modified
Definition recording.h:73
char * channelName
Definition recording.h:75
uint16_t FrameWidth(void) const
Definition recording.h:106
void SetFrameParams(uint16_t FrameWidth, uint16_t FrameHeight, eScanType ScanType, eAspectRatio AspectRatio)
Definition recording.c:534
void SetShortText(const char *ShortText)
Definition recording.c:519
void SetAux(const char *Aux)
Definition recording.c:493
void SetData(const char *Title, const char *ShortText, const char *Description)
Definition recording.c:483
const char * Description(void) const
Definition recording.h:99
eAspectRatio AspectRatio(void) const
Definition recording.h:110
bool Read(FILE *f, bool Force=false)
Definition recording.c:555
uint16_t frameWidth
Definition recording.h:80
void SetErrors(int Errors, int TmpErrors=0)
Definition recording.c:549
double framesPerSecond
Definition recording.h:79
double FramesPerSecond(void) const
Definition recording.h:102
char * fileName
Definition recording.h:86
const cComponents * Components(void) const
Definition recording.h:100
static const char * command
Definition recording.h:497
static void InvokeCommand(const char *State, const char *RecordingFileName, const char *SourceFileName=NULL)
Definition recording.c:2675
virtual int Compare(const cListObject &ListObject) const override
Must return 0 if this object is equal to ListObject, a positive value if it is "greater",...
Definition recording.c:1208
int isOnVideoDirectoryFileSystem
Definition recording.h:148
virtual ~cRecording() override
Definition recording.c:1108
time_t deleted
Definition recording.h:157
cRecordingInfo * info
Definition recording.h:149
bool ChangePriorityLifetime(int NewPriority, int NewLifetime)
Changes the priority and lifetime of this recording to the given values.
Definition recording.c:1398
bool HasMarks(void) const
Returns true if this recording has any editing marks.
Definition recording.c:1355
bool WriteInfo(const char *OtherFileName=NULL)
Writes the info file of this recording.
Definition recording.c:1370
time_t GetLastReplayTime(void) const
Returns the time this recording was last replayed (which is actually the timestamp of the resume file...
Definition recording.c:1189
int IsInUse(void) const
Checks whether this recording is currently in use and therefore shall not be tampered with.
Definition recording.c:1531
bool ChangeName(const char *NewName)
Changes the name of this recording to the given value.
Definition recording.c:1422
bool Undelete(void)
Changes the file name (both internally and on disk) to make this a "normal" recording.
Definition recording.c:1497
void ResetResume(void) const
Definition recording.c:1547
void ReadInfo(bool Force=false)
Definition recording.c:1365
bool IsNew(void) const
Definition recording.h:213
bool Delete(void)
Changes the file name (both internally and on disk) to make this a "deleted" recording.
Definition recording.c:1451
cString Folder(void) const
Returns the name of the folder this recording is stored in (without the video directory).
Definition recording.c:1225
bool isPesRecording
Definition recording.h:147
void DeleteResume(void) const
Definition recording.c:1553
void ClearSortName(void)
Definition recording.c:1172
char * sortBufferName
Definition recording.h:139
int NumFrames(void) const
Returns the number of frames in this recording.
Definition recording.c:1559
bool IsEdited(void) const
Definition recording.c:1342
int Id(void) const
Definition recording.h:162
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:1184
bool IsInPath(const char *Path) const
Returns true if this recording is stored anywhere under the given Path.
Definition recording.c:1217
int fileSizeMB
Definition recording.h:143
void SetId(int Id)
Definition recording.c:1179
void SetStartTime(time_t Start)
Sets the start time of this recording to the given value.
Definition recording.c:1391
char * SortName(void) const
Definition recording.c:1148
const char * Name(void) const
Returns the full name of the recording (without the video directory).
Definition recording.h:179
cResumeFile * resume
Definition recording.h:137
time_t Start(void) const
Definition recording.h:163
int Lifetime(void) const
Definition recording.h:165
int NumFramesAfterEdit(void) const
Returns the number of frames in the edited version of this recording.
Definition recording.c:1570
const char * FileName(void) const
Returns the full path name to the recording directory, including the video directory and the actual '...
Definition recording.c:1237
const char * PrefixFileName(char Prefix)
Definition recording.c:1320
bool DeleteMarks(void)
Deletes the editing marks from this recording (if any).
Definition recording.c:1360
bool IsOnVideoDirectoryFileSystem(void) const
Definition recording.c:1348
int HierarchyLevels(void) const
Definition recording.c:1331
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:1597
cString BaseName(void) const
Returns the base name of this recording (without the video directory and folder).
Definition recording.c:1232
char * fileName
Definition recording.h:141
char * titleBuffer
Definition recording.h:138
void SetDeleted(void)
Definition recording.c:1203
int Priority(void) const
Definition recording.h:164
const char * Title(char Delimiter=' ', bool NewIndicator=false, int Level=-1) const
Definition recording.c:1255
int instanceId
Definition recording.h:146
bool Remove(void)
Actually removes the file from the disk.
Definition recording.c:1486
char * name
Definition recording.h:142
cRecording(const cRecording &)
char * sortBufferTime
Definition recording.h:140
int LengthInSecondsAfterEdit(void) const
Returns the length (in seconds) of the edited version of this recording, or -1 in case of error.
Definition recording.c:1589
bool RetentionExpired(void) const
Definition recording.c:1194
time_t start
Definition recording.h:156
int numFrames
Definition recording.h:144
double FramesPerSecond(void) const
Definition recording.h:191
bool IsPesRecording(void) const
Definition recording.h:215
time_t Deleted(void) const
Definition recording.h:166
static char * StripEpisodeName(char *s, bool Strip)
Definition recording.c:1119
int LengthInSeconds(void) const
Returns the length (in seconds) of this recording, or -1 in case of error.
Definition recording.c:1581
const char * FileNameSrc(void) const
Definition recording.c:2142
void Cleanup(cRecordings *Recordings)
Definition recording.c:2232
int Usage(const char *FileName=NULL) const
Definition recording.c:2164
bool Active(cRecordings *Recordings)
Definition recording.c:2176
bool Error(void) const
Definition recording.c:2140
const char * FileNameDst(void) const
Definition recording.c:2143
cRecordingsHandlerEntry(int Usage, const char *FileNameSrc, const char *FileNameDst)
Definition recording.c:2148
void DelAll(void)
Deletes/terminates all operations.
Definition recording.c:2363
virtual ~cRecordingsHandler() override
Definition recording.c:2278
bool StateChanged(int &OldState)
Returns true if the state if this recordings handler has changed since the last call with the given O...
Definition recording.c:2399
cRecordingsHandlerEntry * Get(const char *FileName)
Definition recording.c:2309
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:2322
bool Finished(bool &Error)
Returns true if all operations in the list have been finished.
Definition recording.c:2409
int GetUsage(const char *FileName)
Returns the usage type for the given FileName.
Definition recording.c:2372
cList< cRecordingsHandlerEntry > operations
Definition recording.h:362
void Del(const char *FileName)
Deletes the given FileName from the list of operations.
Definition recording.c:2354
virtual void Action(void) override
A derived cThread class must implement the code it wants to execute as a separate thread in this func...
Definition recording.c:2283
int GetRequiredDiskSpaceMB(const char *FileName=NULL)
Returns the total disk space required to process all actions.
Definition recording.c:2380
void ResetResume(const char *ResumeFileName=NULL)
Definition recording.c:1948
void UpdateByName(const char *FileName)
Definition recording.c:1868
static const char * UpdateFileName(void)
Definition recording.c:1760
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:1887
virtual ~cRecordings() override
Definition recording.c:1753
cRecordings(bool Deleted=false)
Definition recording.c:1748
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:1918
const cRecording * GetById(int Id) const
Definition recording.c:1795
static time_t lastUpdate
Definition recording.h:279
static cRecordings deletedRecordings
Definition recording.h:276
void AddByName(const char *FileName, bool TriggerUpdate=true)
Definition recording.c:1821
static cRecordings recordings
Definition recording.h:275
int TotalFileSizeMB(void) const
Definition recording.c:1876
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:1783
static cRecordings * GetRecordingsWrite(cStateKey &StateKey, int TimeoutMs=0)
Gets the list of recordings for write access.
Definition recording.h:288
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:1767
void Add(cRecording *Recording)
Definition recording.c:1815
static cVideoDirectoryScannerThread * videoDirectoryScannerThread
Definition recording.h:280
void DelByName(const char *FileName)
Definition recording.c:1832
bool MoveRecordings(const char *OldPath, const char *NewPath)
Moves all recordings in OldPath to NewPath.
Definition recording.c:1928
static bool NeedsUpdate(void)
Definition recording.c:1775
void ClearSortNames(void)
Definition recording.c:1956
static int lastRecordingId
Definition recording.h:277
const cRecording * GetByName(const char *FileName) const
Definition recording.c:1804
static char * updateFileName
Definition recording.h:278
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:1908
static bool HasKeys(void)
Definition remote.c:181
virtual void Action(void) override
A derived cThread class must implement the code it wants to execute as a separate thread in this func...
Definition recording.c:93
static const char * NowReplaying(void)
Definition menu.c:6126
bool isPesRecording
Definition recording.h:57
bool Save(int Index)
Definition recording.c:331
void Reset(void)
Definition recording.c:371
time_t FileTime(void)
Definition recording.c:272
char * fileName
Definition recording.h:54
int Index(void)
Definition recording.c:279
void SetFileName(const char *FileName)
Definition recording.c:258
time_t fileTime
Definition recording.h:55
int Read(void)
Definition recording.c:286
void Delete(void)
Definition recording.c:376
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
virtual void Clear(void) override
Immediately clears the ring buffer.
Definition ringbuffer.c:217
int Put(const uchar *Data, int Count)
Puts at most Count bytes of Data into the ring buffer.
Definition ringbuffer.c:306
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
virtual int Available(void) override
Definition ringbuffer.c:211
bool Open(void)
Definition tools.c:1812
bool Close(void)
Definition tools.c:1822
int DeleteRetention
Definition config.h:316
int ResumeID
Definition config.h:374
int AlwaysSortFoldersFirst
Definition config.h:326
int RecSortingDirection
Definition config.h:328
int RecordingDirs
Definition config.h:324
int UseSubtitle
Definition config.h:321
int DefaultSortModeRec
Definition config.h:327
char SVDRPHostName[HOST_NAME_MAX]
Definition config.h:310
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:334
void Remove(bool IncState=true)
Removes this key from the lock it was previously used with.
Definition thread.c:904
cString(const char *S=NULL, bool TakePointer=false)
Definition tools.c:1138
static cString sprintf(const char *fmt,...) __attribute__((format(printf
Definition tools.c:1242
cString & Append(const char *String)
Definition tools.c:1195
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:330
bool Running(void)
Returns false if a derived cThread object shall leave its Action() function.
Definition thread.h:110
cThread(const char *Description=NULL, bool LowPriority=false)
Creates a new thread.
Definition thread.c:264
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:380
bool Active(void)
Checks whether the thread is still alive.
Definition thread.c:355
const char * Aux(void) const
Definition timers.h:80
const char * File(void) const
Definition timers.h:78
bool IsSingleEvent(void) const
Definition timers.c:513
void SetFile(const char *File)
Definition timers.c:564
time_t StartTime(void) const
The start time of this timer, which is the time as given by the user (for normal timers) or the start...
Definition timers.c:828
const cChannel * Channel(void) const
Definition timers.h:70
int Priority(void) const
Definition timers.h:75
int Lifetime(void) const
Definition timers.h:76
cUnbufferedFile is used for large files that are mainly written or read in a streaming manner,...
Definition tools.h:513
static cUnbufferedFile * Create(const char *FileName, int Flags, mode_t Mode=DEFFILEMODE)
Definition tools.c:2038
int Close(void)
Definition tools.c:1886
ssize_t Read(void *Data, size_t Size)
Definition tools.c:1929
off_t Seek(off_t Offset, int Whence)
Definition tools.c:1921
int Size(void) const
Definition tools.h:773
virtual void Append(T Data)
Definition tools.h:794
cRecordings * deletedRecordings
Definition recording.c:1613
void ScanVideoDir(const char *DirName, int LinkLevel=0, int DirLevel=0)
Definition recording.c:1651
cVideoDirectoryScannerThread(cRecordings *Recordings, cRecordings *DeletedRecordings)
Definition recording.c:1624
virtual void Action(void) override
A derived cThread class must implement the code it wants to execute as a separate thread in this func...
Definition recording.c:1638
static cString PrefixVideoFileName(const char *FileName, char Prefix)
Definition videodir.c:169
static void RemoveEmptyVideoDirectories(const char *IgnoreFiles[]=NULL)
Definition videodir.c:189
static bool IsOnVideoDirectoryFileSystem(const char *FileName)
Definition videodir.c:194
static const char * Name(void)
Definition videodir.c:60
static cUnbufferedFile * OpenVideoFile(const char *FileName, int Flags)
Definition videodir.c:125
static bool VideoFileSpaceAvailable(int SizeMB)
Definition videodir.c:147
static bool MoveVideoFile(const char *FromName, const char *ToName)
Definition videodir.c:137
static int VideoDiskSpace(int *FreeMB=NULL, int *UsedMB=NULL)
Definition videodir.c:152
static bool RenameVideoFile(const char *OldName, const char *NewName)
Definition videodir.c:132
static bool RemoveVideoFile(const char *FileName)
Definition videodir.c:142
cSetup Setup
Definition config.c:373
#define MAXLIFETIME
Definition config.h:46
#define MAXPRIORITY
Definition config.h:41
#define TIMERMACRO_EPISODE
Definition config.h:51
#define TIMERMACRO_TITLE
Definition config.h:50
static cMutex Mutex
Definition epg.c:1439
#define tr(s)
Definition i18n.h:85
#define INFOFILESUFFIX
Definition pes2ts.c:358
#define MARKSFILESUFFIX
Definition pes2ts.c:83
#define MAXFILESPERRECORDINGPES
Definition pes2ts.c:467
#define INDEXFILESUFFIX
Definition pes2ts.c:158
struct __attribute__((packed))
Definition pes2ts.c:138
#define RECORDFILESUFFIXPES
Definition pes2ts.c:468
#define RESUMEFILESUFFIX
Definition pes2ts.c:249
#define SUMMARYFILESUFFIX
Definition pes2ts.c:294
#define MAXFILESPERRECORDINGTS
Definition recording.c:3304
#define NAMEFORMATPES
Definition recording.c:47
int DirectoryNameMax
Definition recording.c:75
tCharExchange CharExchange[]
Definition recording.c:737
cString GetRecordingTimerId(const char *Directory)
Definition recording.c:3664
#define REMOVELATENCY
Definition recording.c:66
cString IndexToHMSF(int Index, bool WithFrame, double FramesPerSecond)
Definition recording.c:3559
static const char * SkipFuzzyChars(const char *s)
Definition recording.c:3529
#define MINDISKSPACE
Definition recording.c:61
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:152
#define DELETEDLIFETIME
Definition recording.c:64
#define REMOVECHECKDELTA
Definition recording.c:63
int DirectoryPathMax
Definition recording.c:74
void GetRecordingsSortMode(const char *Directory)
Definition recording.c:3616
#define MAX_LINK_LEVEL
Definition recording.c:70
#define DATAFORMATPES
Definition recording.c:46
bool GenerateIndex(const char *FileName)
Generates the index of the existing recording with the given FileName.
Definition recording.c:3273
char * LimitNameLengths(char *s, int PathMax, int NameMax)
Definition recording.c:828
static const char * FuzzyChars
Definition recording.c:3527
bool NeedsConversion(const char *p)
Definition recording.c:750
int SecondsToFrames(int Seconds, double FramesPerSecond)
Definition recording.c:3586
#define MAXREMOVETIME
Definition recording.c:68
eRecordingsSortMode RecordingsSortMode
Definition recording.c:3609
bool HasRecordingsSortMode(const char *Directory)
Definition recording.c:3611
#define RECEXT
Definition recording.c:35
#define INDEXCATCHUPWAIT
Definition recording.c:2885
#define IFG_BUFFER_SIZE
Definition recording.c:2690
#define INDEXFILETESTINTERVAL
Definition recording.c:2914
#define MAXWAITFORINDEXFILE
Definition recording.c:2912
int InstanceId
Definition recording.c:77
#define DELEXT
Definition recording.c:36
bool EnoughFreeDiskSpaceForEdit(const char *FileName)
Definition recording.c:3709
#define INDEXFILECHECKINTERVAL
Definition recording.c:2913
char * ExchangeChars(char *s, bool ToFileSystem)
Definition recording.c:757
bool DirectoryEncoding
Definition recording.c:76
void IncRecordingsSortMode(const char *Directory)
Definition recording.c:3635
int HMSFToIndex(const char *HMSF, double FramesPerSecond)
Definition recording.c:3575
#define LIMIT_SECS_PER_MB_RADIO
Definition recording.c:72
void SetRecordingsSortMode(const char *Directory, eRecordingsSortMode SortMode)
Definition recording.c:3627
cDoneRecordings DoneRecordingsPattern
Definition recording.c:3466
static cRemoveDeletedRecordingsThread RemoveDeletedRecordingsThread
Definition recording.c:131
#define DISKCHECKDELTA
Definition recording.c:65
int FileSizeMBafterEdit(const char *FileName)
Definition recording.c:3694
int ReadFrame(cUnbufferedFile *f, uchar *b, int Length, int Max)
Definition recording.c:3593
cRecordingsHandler RecordingsHandler
Definition recording.c:2268
cMutex MutexMarkFramesPerSecond
Definition recording.c:2424
static bool StillRecording(const char *Directory)
Definition recording.c:1542
#define RESUME_NOT_INITIALIZED
Definition recording.c:242
#define SORTMODEFILE
Definition recording.c:58
#define RECORDFILESUFFIXLEN
Definition recording.c:3306
#define MAXINDEXCATCHUP
Definition recording.c:2884
#define NAMEFORMATTS
Definition recording.c:49
#define DATAFORMATTS
Definition recording.c:48
void SetRecordingTimerId(const char *Directory, const char *TimerId)
Definition recording.c:3646
#define TIMERRECFILE
Definition recording.c:59
void ClrRecordingTimerId(const char *Directory)
Definition recording.c:3679
#define RECORDFILESUFFIXTS
Definition recording.c:3305
double MarkFramesPerSecond
Definition recording.c:2423
const char * InvalidChars
Definition recording.c:748
void RemoveDeletedRecordings(void)
Definition recording.c:135
@ ruSrc
Definition recording.h:38
@ ruCut
Definition recording.h:34
@ ruReplay
Definition recording.h:32
@ ruCopy
Definition recording.h:36
@ ruCanceled
Definition recording.h:42
@ ruTimer
Definition recording.h:31
@ ruDst
Definition recording.h:39
@ ruNone
Definition recording.h:30
@ ruMove
Definition recording.h:35
@ ruPending
Definition recording.h:41
int DirectoryNameMax
Definition recording.c:75
eRecordingsSortMode
Definition recording.h:621
@ rsmName
Definition recording.h:621
@ rsmTime
Definition recording.h:621
#define DEFAULTFRAMESPERSECOND
Definition recording.h:408
int HMSFToIndex(const char *HMSF, double FramesPerSecond=DEFAULTFRAMESPERSECOND)
Definition recording.c:3575
@ rsdAscending
Definition recording.h:620
int DirectoryPathMax
Definition recording.c:74
eRecordingsSortMode RecordingsSortMode
Definition recording.c:3609
#define RUC_COPIEDRECORDING
Definition recording.h:493
#define LOCK_DELETEDRECORDINGS_WRITE
Definition recording.h:355
int InstanceId
Definition recording.c:77
char * ExchangeChars(char *s, bool ToFileSystem)
Definition recording.c:757
#define FOLDERDELIMCHAR
Definition recording.h:22
#define RUC_DELETERECORDING
Definition recording.h:489
#define RUC_MOVEDRECORDING
Definition recording.h:491
int FileSizeMBafterEdit(const char *FileName)
Definition recording.c:3694
cRecordingsHandler RecordingsHandler
Definition recording.c:2268
#define RUC_COPYINGRECORDING
Definition recording.h:492
#define LOCK_DELETEDRECORDINGS_READ
Definition recording.h:354
#define LOCK_RECORDINGS_WRITE
Definition recording.h:353
cString IndexToHMSF(int Index, bool WithFrame=false, double FramesPerSecond=DEFAULTFRAMESPERSECOND)
Definition recording.c:3559
const char * AspectRatioTexts[]
Definition remux.c:2190
const char * ScanTypeChars
Definition remux.c:2189
int TsPid(const uchar *p)
Definition remux.h:82
#define PATPID
Definition remux.h:52
#define TS_SIZE
Definition remux.h:34
eAspectRatio
Definition remux.h:518
@ arMax
Definition remux.h:524
@ arUnknown
Definition remux.h:519
eScanType
Definition remux.h:511
@ stMax
Definition remux.h:515
@ stUnknown
Definition remux.h:512
#define TS_SYNC_BYTE
Definition remux.h:33
#define MIN_TS_PACKETS_FOR_FRAME_DETECTOR
Definition remux.h:507
cSkins Skins
Definition skins.c:257
@ mtWarning
Definition skins.h:37
@ mtInfo
Definition skins.h:37
@ mtError
Definition skins.h:37
static const tChannelID InvalidID
Definition channels.h:68
bool Valid(void) const
Definition channels.h:58
static tChannelID FromString(const char *s)
Definition channels.c:23
cString ToString(void) const
Definition channels.c:40
char language[MAXLANGCODE2]
Definition epg.h:48
int SystemExec(const char *Command, bool Detached)
Definition thread.c:1077
const char * strgetlast(const char *s, char c)
Definition tools.c:218
bool isempty(const char *s)
Definition tools.c:387
char * strreplace(char *s, char c1, char c2)
Definition tools.c:139
cString strescape(const char *s, const char *chars)
Definition tools.c:310
bool MakeDirs(const char *FileName, bool IsDirectory)
Definition tools.c:542
cString dtoa(double d, const char *Format)
Converts the given double value to a string, making sure it uses a '.
Definition tools.c:475
time_t LastModifiedTime(const char *FileName)
Definition tools.c:774
char * compactspace(char *s)
Definition tools.c:271
double atod(const char *s)
Converts the given string, which is a floating point number using a '.
Definition tools.c:454
ssize_t safe_read(int filedes, void *buffer, size_t size)
Definition tools.c:50
char * stripspace(char *s)
Definition tools.c:224
ssize_t safe_write(int filedes, const void *buffer, size_t size)
Definition tools.c:62
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:682
bool DirectoryOk(const char *DirName, bool LogErrors)
Definition tools.c:524
int Utf8CharLen(const char *s)
Returns the number of character bytes at the beginning of the given string that form a UTF-8 symbol.
Definition tools.c:874
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:782
bool EntriesOnSameFileSystem(const char *File1, const char *File2)
Checks whether the given files are on the same file system.
Definition tools.c:492
char * strn0cpy(char *dest, const char *src, size_t n)
Definition tools.c:128
bool endswith(const char *s, const char *p)
Definition tools.c:376
cString itoa(int n)
Definition tools.c:485
void TouchFile(const char *FileName, bool Create)
Definition tools.c:760
cString AddDirectory(const char *DirName, const char *FileName)
Definition tools.c:445
void writechar(int filedes, char c)
Definition tools.c:82
T constrain(T v, T l, T h)
Definition tools.h:70
#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
char * skipspace(const char *s)
Definition tools.h:244
bool DoubleEqual(double a, double b)
Definition tools.h:97
void swap(T &a, T &b)
Definition tools.h:65
T max(T a, T b)
Definition tools.h:64
#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