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