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