vdr 2.6.7
recording.c
Go to the documentation of this file.
1/*
2 * recording.c: Recording file handling
3 *
4 * See the main source file 'vdr.c' for copyright information and
5 * how to reach the author.
6 *
7 * $Id: recording.c 5.27 2024/03/04 14:12:37 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 cRecording *Recording = NULL;
1547 if (Recordings == deletedRecordings || initial || !(Recording = Recordings->GetByName(buffer))) {
1548 cRecording *r = new cRecording(buffer);
1549 if (r->Name()) {
1550 r->NumFrames(); // initializes the numFrames member
1551 r->FileSizeMB(); // initializes the fileSizeMB member
1552 r->IsOnVideoDirectoryFileSystem(); // initializes the isOnVideoDirectoryFileSystem member
1553 if (Recordings == deletedRecordings)
1554 r->SetDeleted();
1555 Recordings->Add(r);
1556 count = recordings->Count();
1557 }
1558 else
1559 delete r;
1560 }
1561 else if (Recording)
1562 Recording->ReadInfo();
1563 StateKey.Remove();
1564 }
1565 else
1566 ScanVideoDir(buffer, LinkLevel + Link, DirLevel + 1);
1567 }
1568 }
1569 }
1570 // Handle any vanished recordings:
1571 if (!initial && DirLevel == 0) {
1572 cStateKey StateKey;
1573 recordings->Lock(StateKey, true);
1574 for (cRecording *Recording = recordings->First(); Recording; ) {
1575 cRecording *r = Recording;
1576 Recording = recordings->Next(Recording);
1577 if (access(r->FileName(), F_OK) != 0)
1578 recordings->Del(r);
1579 }
1580 StateKey.Remove();
1581 }
1582}
1583
1584// --- cRecordings -----------------------------------------------------------
1585
1589char *cRecordings::updateFileName = NULL;
1591time_t cRecordings::lastUpdate = 0;
1592
1594:cList<cRecording>(Deleted ? "4 DelRecs" : "3 Recordings")
1595{
1596}
1597
1599{
1600 // The first one to be destructed deletes it:
1603}
1604
1606{
1607 if (!updateFileName)
1608 updateFileName = strdup(AddDirectory(cVideoDirectory::Name(), ".update"));
1609 return updateFileName;
1610}
1611
1613{
1614 bool needsUpdate = NeedsUpdate();
1616 if (!needsUpdate)
1617 lastUpdate = time(NULL); // make sure we don't trigger ourselves
1618}
1619
1621{
1622 time_t lastModified = LastModifiedTime(UpdateFileName());
1623 if (lastModified > time(NULL))
1624 return false; // somebody's clock isn't running correctly
1625 return lastUpdate < lastModified;
1626}
1627
1628void cRecordings::Update(bool Wait)
1629{
1632 lastUpdate = time(NULL); // doing this first to make sure we don't miss anything
1634 if (Wait) {
1636 cCondWait::SleepMs(100);
1637 }
1638}
1639
1641{
1642 for (const cRecording *Recording = First(); Recording; Recording = Next(Recording)) {
1643 if (Recording->Id() == Id)
1644 return Recording;
1645 }
1646 return NULL;
1647}
1648
1649const cRecording *cRecordings::GetByName(const char *FileName) const
1650{
1651 if (FileName) {
1652 for (const cRecording *Recording = First(); Recording; Recording = Next(Recording)) {
1653 if (strcmp(Recording->FileName(), FileName) == 0)
1654 return Recording;
1655 }
1656 }
1657 return NULL;
1658}
1659
1661{
1662 Recording->SetId(++lastRecordingId);
1663 cList<cRecording>::Add(Recording);
1664}
1665
1666void cRecordings::AddByName(const char *FileName, bool TriggerUpdate)
1667{
1668 if (!GetByName(FileName)) {
1669 Add(new cRecording(FileName));
1670 if (TriggerUpdate)
1671 TouchUpdate();
1672 }
1673}
1674
1675void cRecordings::DelByName(const char *FileName)
1676{
1677 cRecording *Recording = GetByName(FileName);
1678 cRecording *dummy = NULL;
1679 if (!Recording)
1680 Recording = dummy = new cRecording(FileName); // allows us to use a FileName that is not in the Recordings list
1682 if (!dummy)
1683 Del(Recording, false);
1684 char *ext = strrchr(Recording->fileName, '.');
1685 if (ext) {
1686 strncpy(ext, DELEXT, strlen(ext));
1687 if (access(Recording->FileName(), F_OK) == 0) {
1688 Recording->SetDeleted();
1689 DeletedRecordings->Add(Recording);
1690 Recording = NULL; // to prevent it from being deleted below
1691 }
1692 }
1693 delete Recording;
1694 TouchUpdate();
1695}
1696
1697void cRecordings::UpdateByName(const char *FileName)
1698{
1699 if (cRecording *Recording = GetByName(FileName))
1700 Recording->ReadInfo();
1701}
1702
1704{
1705 int size = 0;
1706 for (const cRecording *Recording = First(); Recording; Recording = Next(Recording)) {
1707 int FileSizeMB = Recording->FileSizeMB();
1708 if (FileSizeMB > 0 && Recording->IsOnVideoDirectoryFileSystem())
1709 size += FileSizeMB;
1710 }
1711 return size;
1712}
1713
1715{
1716 int size = 0;
1717 int length = 0;
1718 for (const cRecording *Recording = First(); Recording; Recording = Next(Recording)) {
1719 if (Recording->IsOnVideoDirectoryFileSystem()) {
1720 int FileSizeMB = Recording->FileSizeMB();
1721 if (FileSizeMB > 0) {
1722 int LengthInSeconds = Recording->LengthInSeconds();
1723 if (LengthInSeconds > 0) {
1724 if (LengthInSeconds / FileSizeMB < LIMIT_SECS_PER_MB_RADIO) { // don't count radio recordings
1725 size += FileSizeMB;
1726 length += LengthInSeconds;
1727 }
1728 }
1729 }
1730 }
1731 }
1732 return (size && length) ? double(size) * 60 / length : -1;
1733}
1734
1735int cRecordings::PathIsInUse(const char *Path) const
1736{
1737 int Use = ruNone;
1738 for (const cRecording *Recording = First(); Recording; Recording = Next(Recording)) {
1739 if (Recording->IsInPath(Path))
1740 Use |= Recording->IsInUse();
1741 }
1742 return Use;
1743}
1744
1745int cRecordings::GetNumRecordingsInPath(const char *Path) const
1746{
1747 int n = 0;
1748 for (const cRecording *Recording = First(); Recording; Recording = Next(Recording)) {
1749 if (Recording->IsInPath(Path))
1750 n++;
1751 }
1752 return n;
1753}
1754
1755bool cRecordings::MoveRecordings(const char *OldPath, const char *NewPath)
1756{
1757 if (OldPath && NewPath && strcmp(OldPath, NewPath)) {
1758 dsyslog("moving '%s' to '%s'", OldPath, NewPath);
1759 bool Moved = false;
1760 for (cRecording *Recording = First(); Recording; Recording = Next(Recording)) {
1761 if (Recording->IsInPath(OldPath)) {
1762 const char *p = Recording->Name() + strlen(OldPath);
1763 cString NewName = cString::sprintf("%s%s", NewPath, p);
1764 if (!Recording->ChangeName(NewName))
1765 return false;
1766 Moved = true;
1767 }
1768 }
1769 if (Moved)
1770 TouchUpdate();
1771 }
1772 return true;
1773}
1774
1775void cRecordings::ResetResume(const char *ResumeFileName)
1776{
1777 for (cRecording *Recording = First(); Recording; Recording = Next(Recording)) {
1778 if (!ResumeFileName || strncmp(ResumeFileName, Recording->FileName(), strlen(Recording->FileName())) == 0)
1779 Recording->ResetResume();
1780 }
1781}
1782
1784{
1785 for (cRecording *Recording = First(); Recording; Recording = Next(Recording))
1786 Recording->ClearSortName();
1787}
1788
1789// --- cDirCopier ------------------------------------------------------------
1790
1791class cDirCopier : public cThread {
1792private:
1795 bool error;
1797 bool Throttled(void);
1798 virtual void Action(void);
1799public:
1800 cDirCopier(const char *DirNameSrc, const char *DirNameDst);
1801 virtual ~cDirCopier();
1802 bool Error(void) { return error; }
1803 };
1804
1805cDirCopier::cDirCopier(const char *DirNameSrc, const char *DirNameDst)
1806:cThread("file copier", true)
1807{
1808 dirNameSrc = DirNameSrc;
1809 dirNameDst = DirNameDst;
1810 error = true; // prepare for the worst!
1811 suspensionLogged = false;
1812}
1813
1815{
1816 Cancel(3);
1817}
1818
1820{
1821 if (cIoThrottle::Engaged()) {
1822 if (!suspensionLogged) {
1823 dsyslog("suspending copy thread");
1824 suspensionLogged = true;
1825 }
1826 return true;
1827 }
1828 else if (suspensionLogged) {
1829 dsyslog("resuming copy thread");
1830 suspensionLogged = false;
1831 }
1832 return false;
1833}
1834
1836{
1837 if (DirectoryOk(dirNameDst, true)) {
1839 if (d.Ok()) {
1840 dsyslog("copying directory '%s' to '%s'", *dirNameSrc, *dirNameDst);
1841 dirent *e = NULL;
1842 cString FileNameSrc;
1843 cString FileNameDst;
1844 int From = -1;
1845 int To = -1;
1846 size_t BufferSize = BUFSIZ;
1847 uchar *Buffer = NULL;
1848 while (Running()) {
1849 // Suspend copying if we have severe throughput problems:
1850 if (Throttled()) {
1851 cCondWait::SleepMs(100);
1852 continue;
1853 }
1854 // Copy all files in the source directory to the destination directory:
1855 if (e) {
1856 // We're currently copying a file:
1857 if (!Buffer) {
1858 esyslog("ERROR: no buffer");
1859 break;
1860 }
1861 size_t Read = safe_read(From, Buffer, BufferSize);
1862 if (Read > 0) {
1863 size_t Written = safe_write(To, Buffer, Read);
1864 if (Written != Read) {
1865 esyslog("ERROR: can't write to destination file '%s': %m", *FileNameDst);
1866 break;
1867 }
1868 }
1869 else if (Read == 0) { // EOF on From
1870 e = NULL; // triggers switch to next entry
1871 if (fsync(To) < 0) {
1872 esyslog("ERROR: can't sync destination file '%s': %m", *FileNameDst);
1873 break;
1874 }
1875 if (close(From) < 0) {
1876 esyslog("ERROR: can't close source file '%s': %m", *FileNameSrc);
1877 break;
1878 }
1879 if (close(To) < 0) {
1880 esyslog("ERROR: can't close destination file '%s': %m", *FileNameDst);
1881 break;
1882 }
1883 // Plausibility check:
1884 off_t FileSizeSrc = FileSize(FileNameSrc);
1885 off_t FileSizeDst = FileSize(FileNameDst);
1886 if (FileSizeSrc != FileSizeDst) {
1887 esyslog("ERROR: file size discrepancy: %" PRId64 " != %" PRId64, FileSizeSrc, FileSizeDst);
1888 break;
1889 }
1890 }
1891 else {
1892 esyslog("ERROR: can't read from source file '%s': %m", *FileNameSrc);
1893 break;
1894 }
1895 }
1896 else if ((e = d.Next()) != NULL) {
1897 // We're switching to the next directory entry:
1898 FileNameSrc = AddDirectory(dirNameSrc, e->d_name);
1899 FileNameDst = AddDirectory(dirNameDst, e->d_name);
1900 struct stat st;
1901 if (stat(FileNameSrc, &st) < 0) {
1902 esyslog("ERROR: can't access source file '%s': %m", *FileNameSrc);
1903 break;
1904 }
1905 if (!(S_ISREG(st.st_mode) || S_ISLNK(st.st_mode))) {
1906 esyslog("ERROR: source file '%s' is neither a regular file nor a symbolic link", *FileNameSrc);
1907 break;
1908 }
1909 dsyslog("copying file '%s' to '%s'", *FileNameSrc, *FileNameDst);
1910 if (!Buffer) {
1911 BufferSize = max(size_t(st.st_blksize * 10), size_t(BUFSIZ));
1912 Buffer = MALLOC(uchar, BufferSize);
1913 if (!Buffer) {
1914 esyslog("ERROR: out of memory");
1915 break;
1916 }
1917 }
1918 if (access(FileNameDst, F_OK) == 0) {
1919 esyslog("ERROR: destination file '%s' already exists", *FileNameDst);
1920 break;
1921 }
1922 if ((From = open(FileNameSrc, O_RDONLY)) < 0) {
1923 esyslog("ERROR: can't open source file '%s': %m", *FileNameSrc);
1924 break;
1925 }
1926 if ((To = open(FileNameDst, O_WRONLY | O_CREAT | O_EXCL, DEFFILEMODE)) < 0) {
1927 esyslog("ERROR: can't open destination file '%s': %m", *FileNameDst);
1928 close(From);
1929 break;
1930 }
1931 }
1932 else {
1933 // We're done:
1934 free(Buffer);
1935 dsyslog("done copying directory '%s' to '%s'", *dirNameSrc, *dirNameDst);
1936 error = false;
1937 return;
1938 }
1939 }
1940 free(Buffer);
1941 close(From); // just to be absolutely sure
1942 close(To);
1943 isyslog("copying directory '%s' to '%s' ended prematurely", *dirNameSrc, *dirNameDst);
1944 }
1945 else
1946 esyslog("ERROR: can't open '%s'", *dirNameSrc);
1947 }
1948 else
1949 esyslog("ERROR: can't access '%s'", *dirNameDst);
1950}
1951
1952// --- cRecordingsHandlerEntry -----------------------------------------------
1953
1955private:
1961 bool error;
1962 void ClearPending(void) { usage &= ~ruPending; }
1963public:
1964 cRecordingsHandlerEntry(int Usage, const char *FileNameSrc, const char *FileNameDst);
1966 int Usage(const char *FileName = NULL) const;
1967 bool Error(void) const { return error; }
1968 void SetCanceled(void) { usage |= ruCanceled; }
1969 const char *FileNameSrc(void) const { return fileNameSrc; }
1970 const char *FileNameDst(void) const { return fileNameDst; }
1971 bool Active(cRecordings *Recordings);
1972 void Cleanup(cRecordings *Recordings);
1973 };
1974
1975cRecordingsHandlerEntry::cRecordingsHandlerEntry(int Usage, const char *FileNameSrc, const char *FileNameDst)
1976{
1977 usage = Usage;
1980 cutter = NULL;
1981 copier = NULL;
1982 error = false;
1983}
1984
1990
1991int cRecordingsHandlerEntry::Usage(const char *FileName) const
1992{
1993 int u = usage;
1994 if (FileName && *FileName) {
1995 if (strcmp(FileName, fileNameSrc) == 0)
1996 u |= ruSrc;
1997 else if (strcmp(FileName, fileNameDst) == 0)
1998 u |= ruDst;
1999 }
2000 return u;
2001}
2002
2004{
2005 if ((usage & ruCanceled) != 0)
2006 return false;
2007 // First test whether there is an ongoing operation:
2008 if (cutter) {
2009 if (cutter->Active())
2010 return true;
2011 error = cutter->Error();
2012 delete cutter;
2013 cutter = NULL;
2014 }
2015 else if (copier) {
2016 if (copier->Active())
2017 return true;
2018 error = copier->Error();
2019 delete copier;
2020 copier = NULL;
2021 }
2022 // Now check if there is something to start:
2023 if ((Usage() & ruPending) != 0) {
2024 if ((Usage() & ruCut) != 0) {
2025 cutter = new cCutter(FileNameSrc());
2026 cutter->Start();
2027 Recordings->AddByName(FileNameDst(), false);
2028 }
2029 else if ((Usage() & (ruMove | ruCopy)) != 0) {
2032 copier->Start();
2033 }
2034 ClearPending();
2035 Recordings->SetModified(); // to trigger a state change
2036 return true;
2037 }
2038 // We're done:
2039 if (!error && (usage & (ruMove | ruCopy)) != 0)
2041 if (!error && (usage & ruMove) != 0) {
2042 cRecording Recording(FileNameSrc());
2043 if (Recording.Delete()) {
2045 Recordings->DelByName(Recording.FileName());
2046 }
2047 }
2048 Recordings->SetModified(); // to trigger a state change
2049 Recordings->TouchUpdate();
2050 return false;
2051}
2052
2054{
2055 if ((usage & ruCut)) { // this was a cut operation...
2056 if (cutter // ...which had not yet ended...
2057 || error) { // ...or finished with error
2058 if (cutter) {
2059 delete cutter;
2060 cutter = NULL;
2061 }
2063 Recordings->DelByName(fileNameDst);
2064 }
2065 }
2066 if ((usage & (ruMove | ruCopy)) // this was a move/copy operation...
2067 && ((usage & ruPending) // ...which had not yet started...
2068 || copier // ...or not yet finished...
2069 || error)) { // ...or finished with error
2070 if (copier) {
2071 delete copier;
2072 copier = NULL;
2073 }
2075 if ((usage & ruMove) != 0)
2076 Recordings->AddByName(fileNameSrc);
2077 Recordings->DelByName(fileNameDst);
2078 }
2079}
2080
2081// --- cRecordingsHandler ----------------------------------------------------
2082
2084
2086:cThread("recordings handler")
2087{
2088 finished = true;
2089 error = false;
2090}
2091
2096
2098{
2099 while (Running()) {
2100 bool Sleep = false;
2101 {
2103 Recordings->SetExplicitModify();
2104 cMutexLock MutexLock(&mutex);
2106 if (!r->Active(Recordings)) {
2107 error |= r->Error();
2108 r->Cleanup(Recordings);
2109 operations.Del(r);
2110 }
2111 else
2112 Sleep = true;
2113 }
2114 else
2115 break;
2116 }
2117 if (Sleep)
2118 cCondWait::SleepMs(100);
2119 }
2120}
2121
2123{
2124 if (FileName && *FileName) {
2125 for (cRecordingsHandlerEntry *r = operations.First(); r; r = operations.Next(r)) {
2126 if ((r->Usage() & ruCanceled) != 0)
2127 continue;
2128 if (strcmp(FileName, r->FileNameSrc()) == 0 || strcmp(FileName, r->FileNameDst()) == 0)
2129 return r;
2130 }
2131 }
2132 return NULL;
2133}
2134
2135bool cRecordingsHandler::Add(int Usage, const char *FileNameSrc, const char *FileNameDst)
2136{
2137 dsyslog("recordings handler add %d '%s' '%s'", Usage, FileNameSrc, FileNameDst);
2138 cMutexLock MutexLock(&mutex);
2139 if (Usage == ruCut || Usage == ruMove || Usage == ruCopy) {
2140 if (FileNameSrc && *FileNameSrc) {
2141 if (Usage == ruCut || FileNameDst && *FileNameDst) {
2142 cString fnd;
2143 if (Usage == ruCut && !FileNameDst)
2144 FileNameDst = fnd = cCutter::EditedFileName(FileNameSrc);
2145 if (!Get(FileNameSrc) && !Get(FileNameDst)) {
2146 Usage |= ruPending;
2147 operations.Add(new cRecordingsHandlerEntry(Usage, FileNameSrc, FileNameDst));
2148 finished = false;
2149 Start();
2150 return true;
2151 }
2152 else
2153 esyslog("ERROR: file name already present in recordings handler add %d '%s' '%s'", Usage, FileNameSrc, FileNameDst);
2154 }
2155 else
2156 esyslog("ERROR: missing dst file name in recordings handler add %d '%s' '%s'", Usage, FileNameSrc, FileNameDst);
2157 }
2158 else
2159 esyslog("ERROR: missing src file name in recordings handler add %d '%s' '%s'", Usage, FileNameSrc, FileNameDst);
2160 }
2161 else
2162 esyslog("ERROR: invalid usage in recordings handler add %d '%s' '%s'", Usage, FileNameSrc, FileNameDst);
2163 return false;
2164}
2165
2166void cRecordingsHandler::Del(const char *FileName)
2167{
2168 cMutexLock MutexLock(&mutex);
2169 if (cRecordingsHandlerEntry *r = Get(FileName))
2170 r->SetCanceled();
2171}
2172
2174{
2175 cMutexLock MutexLock(&mutex);
2177 r->SetCanceled();
2178}
2179
2180int cRecordingsHandler::GetUsage(const char *FileName)
2181{
2182 cMutexLock MutexLock(&mutex);
2183 if (cRecordingsHandlerEntry *r = Get(FileName))
2184 return r->Usage(FileName);
2185 return ruNone;
2186}
2187
2189{
2190 cMutexLock MutexLock(&mutex);
2191 if (!finished && operations.Count() == 0) {
2192 finished = true;
2193 Error = error;
2194 error = false;
2195 return true;
2196 }
2197 return false;
2198}
2199
2200// --- cMark -----------------------------------------------------------------
2201
2204
2205cMark::cMark(int Position, const char *Comment, double FramesPerSecond)
2206{
2208 comment = Comment;
2209 framesPerSecond = FramesPerSecond;
2210}
2211
2213{
2214}
2215
2217{
2218 return cString::sprintf("%s%s%s", *IndexToHMSF(position, true, framesPerSecond), Comment() ? " " : "", Comment() ? Comment() : "");
2219}
2220
2221bool cMark::Parse(const char *s)
2222{
2223 comment = NULL;
2226 const char *p = strchr(s, ' ');
2227 if (p) {
2228 p = skipspace(p);
2229 if (*p)
2230 comment = strdup(p);
2231 }
2232 return true;
2233}
2234
2235bool cMark::Save(FILE *f)
2236{
2237 return fprintf(f, "%s\n", *ToText()) > 0;
2238}
2239
2240// --- cMarks ----------------------------------------------------------------
2241
2243{
2244 return AddDirectory(Recording->FileName(), Recording->IsPesRecording() ? MARKSFILESUFFIX ".vdr" : MARKSFILESUFFIX);
2245}
2246
2248{
2249 if (remove(cMarks::MarksFileName(Recording)) < 0) {
2250 if (errno != ENOENT) {
2251 LOG_ERROR_STR(Recording->FileName());
2252 return false;
2253 }
2254 }
2255 return true;
2256}
2257
2258bool cMarks::Load(const char *RecordingFileName, double FramesPerSecond, bool IsPesRecording)
2259{
2260 recordingFileName = RecordingFileName;
2261 fileName = AddDirectory(RecordingFileName, IsPesRecording ? MARKSFILESUFFIX ".vdr" : MARKSFILESUFFIX);
2262 framesPerSecond = FramesPerSecond;
2263 isPesRecording = IsPesRecording;
2264 nextUpdate = 0;
2265 lastFileTime = -1; // the first call to Load() must take place!
2266 lastChange = 0;
2267 return Update();
2268}
2269
2271{
2272 time_t t = time(NULL);
2273 if (t > nextUpdate && *fileName) {
2274 time_t LastModified = LastModifiedTime(fileName);
2275 if (LastModified != lastFileTime) // change detected, or first run
2276 lastChange = LastModified > 0 ? LastModified : t;
2277 int d = t - lastChange;
2278 if (d < 60)
2279 d = 1; // check frequently if the file has just been modified
2280 else if (d < 3600)
2281 d = 10; // older files are checked less frequently
2282 else
2283 d /= 360; // phase out checking for very old files
2284 nextUpdate = t + d;
2285 if (LastModified != lastFileTime) { // change detected, or first run
2286 lastFileTime = LastModified;
2287 if (lastFileTime == t)
2288 lastFileTime--; // make sure we don't miss updates in the remaining second
2292 Align();
2293 Sort();
2294 return true;
2295 }
2296 }
2297 }
2298 return false;
2299}
2300
2302{
2303 if (cConfig<cMark>::Save()) {
2305 return true;
2306 }
2307 return false;
2308}
2309
2311{
2312 cIndexFile IndexFile(recordingFileName, false, isPesRecording);
2313 for (cMark *m = First(); m; m = Next(m)) {
2314 int p = IndexFile.GetClosestIFrame(m->Position());
2315 if (m->Position() - p) {
2316 //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" : "");
2317 m->SetPosition(p);
2318 }
2319 }
2320}
2321
2323{
2324 for (cMark *m1 = First(); m1; m1 = Next(m1)) {
2325 for (cMark *m2 = Next(m1); m2; m2 = Next(m2)) {
2326 if (m2->Position() < m1->Position()) {
2327 swap(m1->position, m2->position);
2328 swap(m1->comment, m2->comment);
2329 }
2330 }
2331 }
2332}
2333
2334void cMarks::Add(int Position)
2335{
2336 cConfig<cMark>::Add(new cMark(Position, NULL, framesPerSecond));
2337 Sort();
2338}
2339
2340const cMark *cMarks::Get(int Position) const
2341{
2342 for (const cMark *mi = First(); mi; mi = Next(mi)) {
2343 if (mi->Position() == Position)
2344 return mi;
2345 }
2346 return NULL;
2347}
2348
2349const cMark *cMarks::GetPrev(int Position) const
2350{
2351 for (const cMark *mi = Last(); mi; mi = Prev(mi)) {
2352 if (mi->Position() < Position)
2353 return mi;
2354 }
2355 return NULL;
2356}
2357
2358const cMark *cMarks::GetNext(int Position) const
2359{
2360 for (const cMark *mi = First(); mi; mi = Next(mi)) {
2361 if (mi->Position() > Position)
2362 return mi;
2363 }
2364 return NULL;
2365}
2366
2367const cMark *cMarks::GetNextBegin(const cMark *EndMark) const
2368{
2369 const cMark *BeginMark = EndMark ? Next(EndMark) : First();
2370 if (BeginMark && EndMark && BeginMark->Position() == EndMark->Position()) {
2371 while (const cMark *NextMark = Next(BeginMark)) {
2372 if (BeginMark->Position() == NextMark->Position()) { // skip Begin/End at the same position
2373 if (!(BeginMark = Next(NextMark)))
2374 break;
2375 }
2376 else
2377 break;
2378 }
2379 }
2380 return BeginMark;
2381}
2382
2383const cMark *cMarks::GetNextEnd(const cMark *BeginMark) const
2384{
2385 if (!BeginMark)
2386 return NULL;
2387 const cMark *EndMark = Next(BeginMark);
2388 if (EndMark && BeginMark && BeginMark->Position() == EndMark->Position()) {
2389 while (const cMark *NextMark = Next(EndMark)) {
2390 if (EndMark->Position() == NextMark->Position()) { // skip End/Begin at the same position
2391 if (!(EndMark = Next(NextMark)))
2392 break;
2393 }
2394 else
2395 break;
2396 }
2397 }
2398 return EndMark;
2399}
2400
2402{
2403 int NumSequences = 0;
2404 if (const cMark *BeginMark = GetNextBegin()) {
2405 while (const cMark *EndMark = GetNextEnd(BeginMark)) {
2406 NumSequences++;
2407 BeginMark = GetNextBegin(EndMark);
2408 }
2409 if (BeginMark) {
2410 NumSequences++; // the last sequence had no actual "end" mark
2411 if (NumSequences == 1 && BeginMark->Position() == 0)
2412 NumSequences = 0; // there is only one actual "begin" mark at offset zero, and no actual "end" mark
2413 }
2414 }
2415 return NumSequences;
2416}
2417
2418// --- cRecordingUserCommand -------------------------------------------------
2419
2420const char *cRecordingUserCommand::command = NULL;
2421
2422void cRecordingUserCommand::InvokeCommand(const char *State, const char *RecordingFileName, const char *SourceFileName)
2423{
2424 if (command) {
2425 cString cmd;
2426 if (SourceFileName)
2427 cmd = cString::sprintf("%s %s \"%s\" \"%s\"", command, State, *strescape(RecordingFileName, "\\\"$"), *strescape(SourceFileName, "\\\"$"));
2428 else
2429 cmd = cString::sprintf("%s %s \"%s\"", command, State, *strescape(RecordingFileName, "\\\"$"));
2430 isyslog("executing '%s'", *cmd);
2431 SystemExec(cmd);
2432 }
2433}
2434
2435// --- cIndexFileGenerator ---------------------------------------------------
2436
2437#define IFG_BUFFER_SIZE KILOBYTE(100)
2438
2440private:
2443protected:
2444 virtual void Action(void);
2445public:
2446 cIndexFileGenerator(const char *RecordingName, bool Update = false);
2448 };
2449
2450cIndexFileGenerator::cIndexFileGenerator(const char *RecordingName, bool Update)
2451:cThread("index file generator")
2452,recordingName(RecordingName)
2453{
2454 update = Update;
2455 Start();
2456}
2457
2462
2464{
2465 bool IndexFileComplete = false;
2466 bool IndexFileWritten = false;
2467 bool Rewind = false;
2468 cFileName FileName(recordingName, false);
2469 cUnbufferedFile *ReplayFile = FileName.Open();
2471 cPatPmtParser PatPmtParser;
2472 cFrameDetector FrameDetector;
2473 cIndexFile IndexFile(recordingName, true, false, false, true);
2474 int BufferChunks = KILOBYTE(1); // no need to read a lot at the beginning when parsing PAT/PMT
2475 off_t FileSize = 0;
2476 off_t FrameOffset = -1;
2477 uint16_t FileNumber = 1;
2478 off_t FileOffset = 0;
2479 int Last = -1;
2480 if (update) {
2481 // Look for current index and position to end of it if present:
2482 bool Independent;
2483 int Length;
2484 Last = IndexFile.Last();
2485 if (Last >= 0 && !IndexFile.Get(Last, &FileNumber, &FileOffset, &Independent, &Length))
2486 Last = -1; // reset Last if an error occurred
2487 if (Last >= 0) {
2488 Rewind = true;
2489 isyslog("updating index file");
2490 }
2491 else
2492 isyslog("generating index file");
2493 }
2494 Skins.QueueMessage(mtInfo, tr("Regenerating index file"));
2496 bool Stuffed = false;
2497 while (Running()) {
2498 // Rewind input file:
2499 if (Rewind) {
2500 ReplayFile = FileName.SetOffset(FileNumber, FileOffset);
2501 FileSize = FileOffset;
2502 Buffer.Clear();
2503 Rewind = false;
2504 }
2505 // Process data:
2506 int Length;
2507 uchar *Data = Buffer.Get(Length);
2508 if (Data) {
2509 if (FrameDetector.Synced()) {
2510 // Step 3 - generate the index:
2511 if (TsPid(Data) == PATPID)
2512 FrameOffset = FileSize; // the PAT/PMT is at the beginning of an I-frame
2513 int Processed = FrameDetector.Analyze(Data, Length);
2514 if (Processed > 0) {
2515 if (FrameDetector.NewFrame()) {
2516 if (IndexFileWritten || Last < 0) // check for first frame and do not write if in update mode
2517 IndexFile.Write(FrameDetector.IndependentFrame(), FileName.Number(), FrameOffset >= 0 ? FrameOffset : FileSize);
2518 FrameOffset = -1;
2519 IndexFileWritten = true;
2520 }
2521 FileSize += Processed;
2522 Buffer.Del(Processed);
2523 }
2524 }
2525 else if (PatPmtParser.Completed()) {
2526 // Step 2 - sync FrameDetector:
2527 int Processed = FrameDetector.Analyze(Data, Length);
2528 if (Processed > 0) {
2529 if (FrameDetector.Synced()) {
2530 // Synced FrameDetector, so rewind for actual processing:
2531 Rewind = true;
2532 }
2533 Buffer.Del(Processed);
2534 }
2535 }
2536 else {
2537 // Step 1 - parse PAT/PMT:
2538 uchar *p = Data;
2539 while (Length >= TS_SIZE) {
2540 int Pid = TsPid(p);
2541 if (Pid == PATPID)
2542 PatPmtParser.ParsePat(p, TS_SIZE);
2543 else if (PatPmtParser.IsPmtPid(Pid))
2544 PatPmtParser.ParsePmt(p, TS_SIZE);
2545 Length -= TS_SIZE;
2546 p += TS_SIZE;
2547 if (PatPmtParser.Completed()) {
2548 // Found pid, so rewind to sync FrameDetector:
2549 FrameDetector.SetPid(PatPmtParser.Vpid() ? PatPmtParser.Vpid() : PatPmtParser.Apid(0), PatPmtParser.Vpid() ? PatPmtParser.Vtype() : PatPmtParser.Atype(0));
2550 BufferChunks = IFG_BUFFER_SIZE;
2551 Rewind = true;
2552 break;
2553 }
2554 }
2555 Buffer.Del(p - Data);
2556 }
2557 }
2558 // Read data:
2559 else if (ReplayFile) {
2560 int Result = Buffer.Read(ReplayFile, BufferChunks);
2561 if (Result == 0) { // EOF
2562 if (Buffer.Available() > 0 && !Stuffed) {
2563 // So the last call to Buffer.Get() returned NULL, but there is still
2564 // data in the buffer, and we're at the end of the current TS file.
2565 // The remaining data in the buffer is less than what's needed for the
2566 // frame detector to analyze frames, so we need to put some stuffing
2567 // packets into the buffer to flush out the rest of the data (otherwise
2568 // any frames within the remaining data would not be seen here):
2569 uchar StuffingPacket[TS_SIZE] = { TS_SYNC_BYTE, 0xFF };
2570 for (int i = 0; i <= MIN_TS_PACKETS_FOR_FRAME_DETECTOR; i++)
2571 Buffer.Put(StuffingPacket, sizeof(StuffingPacket));
2572 Stuffed = true;
2573 }
2574 else {
2575 ReplayFile = FileName.NextFile();
2576 FileSize = 0;
2577 FrameOffset = -1;
2578 Buffer.Clear();
2579 Stuffed = false;
2580 }
2581 }
2582 }
2583 // Recording has been processed:
2584 else {
2585 IndexFileComplete = true;
2586 break;
2587 }
2588 }
2590 if (IndexFileComplete) {
2591 if (IndexFileWritten) {
2592 cRecordingInfo RecordingInfo(recordingName);
2593 if (RecordingInfo.Read()) {
2594 if ((FrameDetector.FramesPerSecond() > 0 && !DoubleEqual(RecordingInfo.FramesPerSecond(), FrameDetector.FramesPerSecond())) ||
2595 FrameDetector.FrameWidth() != RecordingInfo.FrameWidth() ||
2596 FrameDetector.FrameHeight() != RecordingInfo.FrameHeight() ||
2597 FrameDetector.AspectRatio() != RecordingInfo.AspectRatio()) {
2598 RecordingInfo.SetFramesPerSecond(FrameDetector.FramesPerSecond());
2599 RecordingInfo.SetFrameParams(FrameDetector.FrameWidth(), FrameDetector.FrameHeight(), FrameDetector.ScanType(), FrameDetector.AspectRatio());
2600 RecordingInfo.Write();
2602 Recordings->UpdateByName(recordingName);
2603 }
2604 }
2605 Skins.QueueMessage(mtInfo, tr("Index file regeneration complete"));
2606 return;
2607 }
2608 else
2609 Skins.QueueMessage(mtError, tr("Index file regeneration failed!"));
2610 }
2611 // Delete the index file if the recording has not been processed entirely:
2612 IndexFile.Delete();
2613}
2614
2615// --- cIndexFile ------------------------------------------------------------
2616
2617#define INDEXFILESUFFIX "/index"
2618
2619// The maximum time to wait before giving up while catching up on an index file:
2620#define MAXINDEXCATCHUP 8 // number of retries
2621#define INDEXCATCHUPWAIT 100 // milliseconds
2622
2623struct __attribute__((packed)) tIndexPes {
2624 uint32_t offset;
2625 uchar type;
2626 uchar number;
2627 uint16_t reserved;
2628 };
2629
2630struct __attribute__((packed)) tIndexTs {
2631 uint64_t offset:40; // up to 1TB per file (not using off_t here - must definitely be exactly 64 bit!)
2632 int reserved:7; // reserved for future use
2633 int independent:1; // marks frames that can be displayed by themselves (for trick modes)
2634 uint16_t number:16; // up to 64K files per recording
2635 tIndexTs(off_t Offset, bool Independent, uint16_t Number)
2636 {
2637 offset = Offset;
2638 reserved = 0;
2639 independent = Independent;
2640 number = Number;
2641 }
2642 };
2643
2644#define MAXWAITFORINDEXFILE 10 // max. time to wait for the regenerated index file (seconds)
2645#define INDEXFILECHECKINTERVAL 500 // ms between checks for existence of the regenerated index file
2646#define INDEXFILETESTINTERVAL 10 // ms between tests for the size of the index file in case of pausing live video
2647
2648cIndexFile::cIndexFile(const char *FileName, bool Record, bool IsPesRecording, bool PauseLive, bool Update)
2649:resumeFile(FileName, IsPesRecording)
2650{
2651 f = -1;
2652 size = 0;
2653 last = -1;
2654 index = NULL;
2655 isPesRecording = IsPesRecording;
2656 indexFileGenerator = NULL;
2657 if (FileName) {
2659 if (!Record && PauseLive) {
2660 // Wait until the index file contains at least two frames:
2661 time_t tmax = time(NULL) + MAXWAITFORINDEXFILE;
2662 while (time(NULL) < tmax && FileSize(fileName) < off_t(2 * sizeof(tIndexTs)))
2664 }
2665 int delta = 0;
2666 if (!Record && (access(fileName, R_OK) != 0 || FileSize(fileName) == 0 && time(NULL) - LastModifiedTime(fileName) > MAXWAITFORINDEXFILE)) {
2667 // Index file doesn't exist, so try to regenerate it:
2668 if (!isPesRecording) { // sorry, can only do this for TS recordings
2669 resumeFile.Delete(); // just in case
2671 // Wait until the index file exists:
2672 time_t tmax = time(NULL) + MAXWAITFORINDEXFILE;
2673 do {
2674 cCondWait::SleepMs(INDEXFILECHECKINTERVAL); // start with a sleep, to give it a head start
2675 } while (access(fileName, R_OK) != 0 && time(NULL) < tmax);
2676 }
2677 }
2678 if (access(fileName, R_OK) == 0) {
2679 struct stat buf;
2680 if (stat(fileName, &buf) == 0) {
2681 delta = int(buf.st_size % sizeof(tIndexTs));
2682 if (delta) {
2683 delta = sizeof(tIndexTs) - delta;
2684 esyslog("ERROR: invalid file size (%" PRId64 ") in '%s'", buf.st_size, *fileName);
2685 }
2686 last = int((buf.st_size + delta) / sizeof(tIndexTs) - 1);
2687 if ((!Record || Update) && last >= 0) {
2688 size = last + 1;
2689 index = MALLOC(tIndexTs, size);
2690 if (index) {
2691 f = open(fileName, O_RDONLY);
2692 if (f >= 0) {
2693 if (safe_read(f, index, size_t(buf.st_size)) != buf.st_size) {
2694 esyslog("ERROR: can't read from file '%s'", *fileName);
2695 free(index);
2696 size = 0;
2697 last = -1;
2698 index = NULL;
2699 }
2700 else if (isPesRecording)
2702 if (!index || !StillRecording(FileName)) {
2703 close(f);
2704 f = -1;
2705 }
2706 // otherwise we don't close f here, see CatchUp()!
2707 }
2708 else
2710 }
2711 else {
2712 esyslog("ERROR: can't allocate %zd bytes for index '%s'", size * sizeof(tIndexTs), *fileName);
2713 size = 0;
2714 last = -1;
2715 }
2716 }
2717 }
2718 else
2719 LOG_ERROR;
2720 }
2721 else if (!Record)
2722 isyslog("missing index file %s", *fileName);
2723 if (Record) {
2724 if ((f = open(fileName, O_WRONLY | O_CREAT | O_APPEND, DEFFILEMODE)) >= 0) {
2725 if (delta) {
2726 esyslog("ERROR: padding index file with %d '0' bytes", delta);
2727 while (delta--)
2728 writechar(f, 0);
2729 }
2730 }
2731 else
2733 }
2734 }
2735}
2736
2738{
2739 if (f >= 0)
2740 close(f);
2741 free(index);
2742 delete indexFileGenerator;
2743}
2744
2745cString cIndexFile::IndexFileName(const char *FileName, bool IsPesRecording)
2746{
2747 return cString::sprintf("%s%s", FileName, IsPesRecording ? INDEXFILESUFFIX ".vdr" : INDEXFILESUFFIX);
2748}
2749
2750void cIndexFile::ConvertFromPes(tIndexTs *IndexTs, int Count)
2751{
2752 tIndexPes IndexPes;
2753 while (Count-- > 0) {
2754 memcpy(&IndexPes, IndexTs, sizeof(IndexPes));
2755 IndexTs->offset = IndexPes.offset;
2756 IndexTs->independent = IndexPes.type == 1; // I_FRAME
2757 IndexTs->number = IndexPes.number;
2758 IndexTs++;
2759 }
2760}
2761
2762void cIndexFile::ConvertToPes(tIndexTs *IndexTs, int Count)
2763{
2764 tIndexPes IndexPes;
2765 while (Count-- > 0) {
2766 IndexPes.offset = uint32_t(IndexTs->offset);
2767 IndexPes.type = uchar(IndexTs->independent ? 1 : 2); // I_FRAME : "not I_FRAME" (exact frame type doesn't matter)
2768 IndexPes.number = uchar(IndexTs->number);
2769 IndexPes.reserved = 0;
2770 memcpy((void *)IndexTs, &IndexPes, sizeof(*IndexTs));
2771 IndexTs++;
2772 }
2773}
2774
2775bool cIndexFile::CatchUp(int Index)
2776{
2777 // returns true unless something really goes wrong, so that 'index' becomes NULL
2778 if (index && f >= 0) {
2779 cMutexLock MutexLock(&mutex);
2780 // Note that CatchUp() is triggered even if Index is 'last' (and thus valid).
2781 // This is done to make absolutely sure we don't miss any data at the very end.
2782 for (int i = 0; i <= MAXINDEXCATCHUP && (Index < 0 || Index >= last); i++) {
2783 struct stat buf;
2784 if (fstat(f, &buf) == 0) {
2785 int newLast = int(buf.st_size / sizeof(tIndexTs) - 1);
2786 if (newLast > last) {
2787 int NewSize = size;
2788 if (NewSize <= newLast) {
2789 NewSize *= 2;
2790 if (NewSize <= newLast)
2791 NewSize = newLast + 1;
2792 }
2793 if (tIndexTs *NewBuffer = (tIndexTs *)realloc(index, NewSize * sizeof(tIndexTs))) {
2794 size = NewSize;
2795 index = NewBuffer;
2796 int offset = (last + 1) * sizeof(tIndexTs);
2797 int delta = (newLast - last) * sizeof(tIndexTs);
2798 if (lseek(f, offset, SEEK_SET) == offset) {
2799 if (safe_read(f, &index[last + 1], delta) != delta) {
2800 esyslog("ERROR: can't read from index");
2801 free(index);
2802 index = NULL;
2803 close(f);
2804 f = -1;
2805 break;
2806 }
2807 if (isPesRecording)
2808 ConvertFromPes(&index[last + 1], newLast - last);
2809 last = newLast;
2810 }
2811 else
2813 }
2814 else {
2815 esyslog("ERROR: can't realloc() index");
2816 break;
2817 }
2818 }
2819 }
2820 else
2822 if (Index < last)
2823 break;
2824 cCondVar CondVar;
2826 }
2827 }
2828 return index != NULL;
2829}
2830
2831bool cIndexFile::Write(bool Independent, uint16_t FileNumber, off_t FileOffset)
2832{
2833 if (f >= 0) {
2834 tIndexTs i(FileOffset, Independent, FileNumber);
2835 if (isPesRecording)
2836 ConvertToPes(&i, 1);
2837 if (safe_write(f, &i, sizeof(i)) < 0) {
2839 close(f);
2840 f = -1;
2841 return false;
2842 }
2843 last++;
2844 }
2845 return f >= 0;
2846}
2847
2848bool cIndexFile::Get(int Index, uint16_t *FileNumber, off_t *FileOffset, bool *Independent, int *Length)
2849{
2850 if (CatchUp(Index)) {
2851 if (Index >= 0 && Index <= last) {
2852 *FileNumber = index[Index].number;
2853 *FileOffset = index[Index].offset;
2854 if (Independent)
2855 *Independent = index[Index].independent;
2856 if (Length) {
2857 if (Index < last) {
2858 uint16_t fn = index[Index + 1].number;
2859 off_t fo = index[Index + 1].offset;
2860 if (fn == *FileNumber)
2861 *Length = int(fo - *FileOffset);
2862 else
2863 *Length = -1; // this means "everything up to EOF" (the buffer's Read function will act accordingly)
2864 }
2865 else
2866 *Length = -1;
2867 }
2868 return true;
2869 }
2870 }
2871 return false;
2872}
2873
2874int cIndexFile::GetNextIFrame(int Index, bool Forward, uint16_t *FileNumber, off_t *FileOffset, int *Length)
2875{
2876 if (CatchUp()) {
2877 int d = Forward ? 1 : -1;
2878 for (;;) {
2879 Index += d;
2880 if (Index >= 0 && Index <= last) {
2881 if (index[Index].independent) {
2882 uint16_t fn;
2883 if (!FileNumber)
2884 FileNumber = &fn;
2885 off_t fo;
2886 if (!FileOffset)
2887 FileOffset = &fo;
2888 *FileNumber = index[Index].number;
2889 *FileOffset = index[Index].offset;
2890 if (Length) {
2891 if (Index < last) {
2892 uint16_t fn = index[Index + 1].number;
2893 off_t fo = index[Index + 1].offset;
2894 if (fn == *FileNumber)
2895 *Length = int(fo - *FileOffset);
2896 else
2897 *Length = -1; // this means "everything up to EOF" (the buffer's Read function will act accordingly)
2898 }
2899 else
2900 *Length = -1;
2901 }
2902 return Index;
2903 }
2904 }
2905 else
2906 break;
2907 }
2908 }
2909 return -1;
2910}
2911
2913{
2914 if (index && last > 0) {
2915 Index = constrain(Index, 0, last);
2916 if (index[Index].independent)
2917 return Index;
2918 int il = Index - 1;
2919 int ih = Index + 1;
2920 for (;;) {
2921 if (il >= 0) {
2922 if (index[il].independent)
2923 return il;
2924 il--;
2925 }
2926 else if (ih > last)
2927 break;
2928 if (ih <= last) {
2929 if (index[ih].independent)
2930 return ih;
2931 ih++;
2932 }
2933 else if (il < 0)
2934 break;
2935 }
2936 }
2937 return 0;
2938}
2939
2940int cIndexFile::Get(uint16_t FileNumber, off_t FileOffset)
2941{
2942 if (CatchUp()) {
2943 //TODO implement binary search!
2944 int i;
2945 for (i = 0; i <= last; i++) {
2946 if (index[i].number > FileNumber || (index[i].number == FileNumber) && off_t(index[i].offset) >= FileOffset)
2947 break;
2948 }
2949 return i;
2950 }
2951 return -1;
2952}
2953
2955{
2956 return f >= 0;
2957}
2958
2960{
2961 if (*fileName) {
2962 dsyslog("deleting index file '%s'", *fileName);
2963 if (f >= 0) {
2964 close(f);
2965 f = -1;
2966 }
2967 unlink(fileName);
2968 }
2969}
2970
2971int cIndexFile::GetLength(const char *FileName, bool IsPesRecording)
2972{
2973 struct stat buf;
2974 cString s = IndexFileName(FileName, IsPesRecording);
2975 if (*s && stat(s, &buf) == 0)
2976 return buf.st_size / (IsPesRecording ? sizeof(tIndexTs) : sizeof(tIndexPes));
2977 return -1;
2978}
2979
2980bool GenerateIndex(const char *FileName, bool Update)
2981{
2982 if (DirectoryOk(FileName)) {
2983 cRecording Recording(FileName);
2984 if (Recording.Name()) {
2985 if (!Recording.IsPesRecording()) {
2986 cString IndexFileName = AddDirectory(FileName, INDEXFILESUFFIX);
2987 if (!Update)
2988 unlink(IndexFileName);
2989 cIndexFileGenerator *IndexFileGenerator = new cIndexFileGenerator(FileName, Update);
2990 while (IndexFileGenerator->Active())
2992 if (access(IndexFileName, R_OK) == 0)
2993 return true;
2994 else
2995 fprintf(stderr, "cannot create '%s'\n", *IndexFileName);
2996 }
2997 else
2998 fprintf(stderr, "'%s' is not a TS recording\n", FileName);
2999 }
3000 else
3001 fprintf(stderr, "'%s' is not a recording\n", FileName);
3002 }
3003 else
3004 fprintf(stderr, "'%s' is not a directory\n", FileName);
3005 return false;
3006}
3007
3008// --- cFileName -------------------------------------------------------------
3009
3010#define MAXFILESPERRECORDINGPES 255
3011#define RECORDFILESUFFIXPES "/%03d.vdr"
3012#define MAXFILESPERRECORDINGTS 65535
3013#define RECORDFILESUFFIXTS "/%05d.ts"
3014#define RECORDFILESUFFIXLEN 20 // some additional bytes for safety...
3015
3016cFileName::cFileName(const char *FileName, bool Record, bool Blocking, bool IsPesRecording)
3017{
3018 file = NULL;
3019 fileNumber = 0;
3020 record = Record;
3022 isPesRecording = IsPesRecording;
3023 // Prepare the file name:
3024 fileName = MALLOC(char, strlen(FileName) + RECORDFILESUFFIXLEN);
3025 if (!fileName) {
3026 esyslog("ERROR: can't copy file name '%s'", FileName);
3027 return;
3028 }
3029 strcpy(fileName, FileName);
3031 SetOffset(1);
3032}
3033
3035{
3036 Close();
3037 free(fileName);
3038}
3039
3040bool cFileName::GetLastPatPmtVersions(int &PatVersion, int &PmtVersion)
3041{
3042 if (fileName && !isPesRecording) {
3043 // Find the last recording file:
3044 int Number = 1;
3045 for (; Number <= MAXFILESPERRECORDINGTS + 1; Number++) { // +1 to correctly set Number in case there actually are that many files
3047 if (access(fileName, F_OK) != 0) { // file doesn't exist
3048 Number--;
3049 break;
3050 }
3051 }
3052 for (; Number > 0; Number--) {
3053 // Search for a PAT packet from the end of the file:
3054 cPatPmtParser PatPmtParser;
3057 if (fd >= 0) {
3058 off_t pos = lseek(fd, -TS_SIZE, SEEK_END);
3059 while (pos >= 0) {
3060 // Read and parse the PAT/PMT:
3061 uchar buf[TS_SIZE];
3062 while (read(fd, buf, sizeof(buf)) == sizeof(buf)) {
3063 if (buf[0] == TS_SYNC_BYTE) {
3064 int Pid = TsPid(buf);
3065 if (Pid == PATPID)
3066 PatPmtParser.ParsePat(buf, sizeof(buf));
3067 else if (PatPmtParser.IsPmtPid(Pid)) {
3068 PatPmtParser.ParsePmt(buf, sizeof(buf));
3069 if (PatPmtParser.GetVersions(PatVersion, PmtVersion)) {
3070 close(fd);
3071 return true;
3072 }
3073 }
3074 else
3075 break; // PAT/PMT is always in one sequence
3076 }
3077 else
3078 return false;
3079 }
3080 pos = lseek(fd, pos - TS_SIZE, SEEK_SET);
3081 }
3082 close(fd);
3083 }
3084 else
3085 break;
3086 }
3087 }
3088 return false;
3089}
3090
3092{
3093 if (!file) {
3094 int BlockingFlag = blocking ? 0 : O_NONBLOCK;
3095 if (record) {
3096 dsyslog("recording to '%s'", fileName);
3098 if (!file)
3100 }
3101 else {
3102 if (access(fileName, R_OK) == 0) {
3103 dsyslog("playing '%s'", fileName);
3105 if (!file)
3107 }
3108 else if (errno != ENOENT)
3110 }
3111 }
3112 return file;
3113}
3114
3116{
3117 if (file) {
3118 if (file->Close() < 0)
3120 delete file;
3121 file = NULL;
3122 }
3123}
3124
3125cUnbufferedFile *cFileName::SetOffset(int Number, off_t Offset)
3126{
3127 if (fileNumber != Number)
3128 Close();
3130 if (0 < Number && Number <= MaxFilesPerRecording) {
3133 if (record) {
3134 if (access(fileName, F_OK) == 0) {
3135 // file exists, check if it has non-zero size
3136 struct stat buf;
3137 if (stat(fileName, &buf) == 0) {
3138 if (buf.st_size != 0)
3139 return SetOffset(Number + 1); // file exists and has non zero size, let's try next suffix
3140 else {
3141 // zero size file, remove it
3142 dsyslog("cFileName::SetOffset: removing zero-sized file %s", fileName);
3144 }
3145 }
3146 else
3147 return SetOffset(Number + 1); // error with fstat - should not happen, just to be on the safe side
3148 }
3149 else if (errno != ENOENT) { // something serious has happened
3151 return NULL;
3152 }
3153 // found a non existing file suffix
3154 }
3155 if (Open()) {
3156 if (!record && Offset >= 0 && file->Seek(Offset, SEEK_SET) != Offset) {
3158 return NULL;
3159 }
3160 }
3161 return file;
3162 }
3163 esyslog("ERROR: max number of files (%d) exceeded", MaxFilesPerRecording);
3164 return NULL;
3165}
3166
3168{
3169 return SetOffset(fileNumber + 1);
3170}
3171
3172// --- cDoneRecordings -------------------------------------------------------
3173
3175
3176bool cDoneRecordings::Load(const char *FileName)
3177{
3178 fileName = FileName;
3179 if (*fileName && access(fileName, F_OK) == 0) {
3180 isyslog("loading %s", *fileName);
3181 FILE *f = fopen(fileName, "r");
3182 if (f) {
3183 char *s;
3184 cReadLine ReadLine;
3185 while ((s = ReadLine.Read(f)) != NULL)
3186 Add(s);
3187 fclose(f);
3188 }
3189 else {
3191 return false;
3192 }
3193 }
3194 return true;
3195}
3196
3198{
3199 bool result = true;
3201 if (f.Open()) {
3202 for (int i = 0; i < doneRecordings.Size(); i++) {
3203 if (fputs(doneRecordings[i], f) == EOF || fputc('\n', f) == EOF) {
3204 result = false;
3205 break;
3206 }
3207 }
3208 if (!f.Close())
3209 result = false;
3210 }
3211 else
3212 result = false;
3213 return result;
3214}
3215
3216void cDoneRecordings::Add(const char *Title)
3217{
3218 doneRecordings.Append(strdup(Title));
3219}
3220
3221void cDoneRecordings::Append(const char *Title)
3222{
3223 if (!Contains(Title)) {
3224 Add(Title);
3225 if (FILE *f = fopen(fileName, "a")) {
3226 fputs(Title, f);
3227 fputc('\n', f);
3228 fclose(f);
3229 }
3230 else
3231 esyslog("ERROR: can't open '%s' for appending '%s'", *fileName, Title);
3232 }
3233}
3234
3235static const char *FuzzyChars = " -:/";
3236
3237static const char *SkipFuzzyChars(const char *s)
3238{
3239 while (*s && strchr(FuzzyChars, *s))
3240 s++;
3241 return s;
3242}
3243
3244bool cDoneRecordings::Contains(const char *Title) const
3245{
3246 for (int i = 0; i < doneRecordings.Size(); i++) {
3247 const char *s = doneRecordings[i];
3248 const char *t = Title;
3249 while (*s && *t) {
3250 s = SkipFuzzyChars(s);
3251 t = SkipFuzzyChars(t);
3252 if (!*s || !*t)
3253 break;
3254 if (toupper(uchar(*s)) != toupper(uchar(*t)))
3255 break;
3256 s++;
3257 t++;
3258 }
3259 if (!*s && !*t)
3260 return true;
3261 }
3262 return false;
3263}
3264
3265// --- Index stuff -----------------------------------------------------------
3266
3267cString IndexToHMSF(int Index, bool WithFrame, double FramesPerSecond)
3268{
3269 const char *Sign = "";
3270 if (Index < 0) {
3271 Index = -Index;
3272 Sign = "-";
3273 }
3274 double Seconds;
3275 int f = int(modf((Index + 0.5) / FramesPerSecond, &Seconds) * FramesPerSecond);
3276 int s = int(Seconds);
3277 int m = s / 60 % 60;
3278 int h = s / 3600;
3279 s %= 60;
3280 return cString::sprintf(WithFrame ? "%s%d:%02d:%02d.%02d" : "%s%d:%02d:%02d", Sign, h, m, s, f);
3281}
3282
3283int HMSFToIndex(const char *HMSF, double FramesPerSecond)
3284{
3285 int h, m, s, f = 0;
3286 int n = sscanf(HMSF, "%d:%d:%d.%d", &h, &m, &s, &f);
3287 if (n == 1)
3288 return h; // plain frame number
3289 if (n >= 3)
3290 return int(round((h * 3600 + m * 60 + s) * FramesPerSecond)) + f;
3291 return 0;
3292}
3293
3294int SecondsToFrames(int Seconds, double FramesPerSecond)
3295{
3296 return int(round(Seconds * FramesPerSecond));
3297}
3298
3299// --- ReadFrame -------------------------------------------------------------
3300
3301int ReadFrame(cUnbufferedFile *f, uchar *b, int Length, int Max)
3302{
3303 if (Length == -1)
3304 Length = Max; // this means we read up to EOF (see cIndex)
3305 else if (Length > Max) {
3306 esyslog("ERROR: frame larger than buffer (%d > %d)", Length, Max);
3307 Length = Max;
3308 }
3309 int r = f->Read(b, Length);
3310 if (r < 0)
3311 LOG_ERROR;
3312 return r;
3313}
3314
3315// --- Recordings Sort Mode --------------------------------------------------
3316
3318
3319bool HasRecordingsSortMode(const char *Directory)
3320{
3321 return access(AddDirectory(Directory, SORTMODEFILE), R_OK) == 0;
3322}
3323
3324void GetRecordingsSortMode(const char *Directory)
3325{
3327 if (FILE *f = fopen(AddDirectory(Directory, SORTMODEFILE), "r")) {
3328 char buf[8];
3329 if (fgets(buf, sizeof(buf), f))
3331 fclose(f);
3332 }
3333}
3334
3335void SetRecordingsSortMode(const char *Directory, eRecordingsSortMode SortMode)
3336{
3337 if (FILE *f = fopen(AddDirectory(Directory, SORTMODEFILE), "w")) {
3338 fputs(cString::sprintf("%d\n", SortMode), f);
3339 fclose(f);
3340 }
3341}
3342
3351
3352// --- Recording Timer Indicator ---------------------------------------------
3353
3354void SetRecordingTimerId(const char *Directory, const char *TimerId)
3355{
3356 cString FileName = AddDirectory(Directory, TIMERRECFILE);
3357 if (TimerId) {
3358 dsyslog("writing timer id '%s' to %s", TimerId, *FileName);
3359 if (FILE *f = fopen(FileName, "w")) {
3360 fprintf(f, "%s\n", TimerId);
3361 fclose(f);
3362 }
3363 else
3364 LOG_ERROR_STR(*FileName);
3365 }
3366 else {
3367 dsyslog("removing %s", *FileName);
3368 unlink(FileName);
3369 }
3370}
3371
3372cString GetRecordingTimerId(const char *Directory)
3373{
3374 cString FileName = AddDirectory(Directory, TIMERRECFILE);
3375 const char *Id = NULL;
3376 if (FILE *f = fopen(FileName, "r")) {
3377 char buf[HOST_NAME_MAX + 10]; // +10 for numeric timer id and '@'
3378 if (fgets(buf, sizeof(buf), f)) {
3379 stripspace(buf);
3380 Id = buf;
3381 }
3382 fclose(f);
3383 }
3384 return Id;
3385}
#define MAXDPIDS
Definition channels.h:32
#define MAXAPIDS
Definition channels.h:31
#define MAXSPIDS
Definition channels.h:33
const char * Slang(int i) const
Definition channels.h:165
int Number(void) const
Definition channels.h:179
const char * Name(void) const
Definition channels.c:121
tChannelID GetChannelID(void) const
Definition channels.h:191
const char * Dlang(int i) const
Definition channels.h:164
const char * Alang(int i) const
Definition channels.h:163
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:1805
cString dirNameDst
Definition recording.c:1794
bool suspensionLogged
Definition recording.c:1796
virtual ~cDirCopier()
Definition recording.c:1814
bool Throttled(void)
Definition recording.c:1819
cString dirNameSrc
Definition recording.c:1793
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:1835
bool Error(void)
Definition recording.c:1802
cStringList doneRecordings
Definition recording.h:530
bool Save(void) const
Definition recording.c:3197
void Add(const char *Title)
Definition recording.c:3216
cString fileName
Definition recording.h:529
void Append(const char *Title)
Definition recording.c:3221
bool Load(const char *FileName)
Definition recording.c:3176
bool Contains(const char *Title) const
Definition recording.c:3244
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:3167
uint16_t Number(void)
Definition recording.h:519
bool record
Definition recording.h:512
void Close(void)
Definition recording.c:3115
uint16_t fileNumber
Definition recording.h:510
cUnbufferedFile * Open(void)
Definition recording.c:3091
cFileName(const char *FileName, bool Record, bool Blocking=false, bool IsPesRecording=false)
Definition recording.c:3016
char * fileName
Definition recording.h:511
char * pFileNumber
Definition recording.h:511
bool GetLastPatPmtVersions(int &PatVersion, int &PmtVersion)
Definition recording.c:3040
bool blocking
Definition recording.h:513
cUnbufferedFile * SetOffset(int Number, off_t Offset=0)
Definition recording.c:3125
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:2450
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:2463
int GetNextIFrame(int Index, bool Forward, uint16_t *FileNumber=NULL, off_t *FileOffset=NULL, int *Length=NULL)
Definition recording.c:2874
cResumeFile resumeFile
Definition recording.h:476
bool IsStillRecording(void)
Definition recording.c:2954
void ConvertFromPes(tIndexTs *IndexTs, int Count)
Definition recording.c:2750
bool Write(bool Independent, uint16_t FileNumber, off_t FileOffset)
Definition recording.c:2831
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:2971
bool CatchUp(int Index=-1)
Definition recording.c:2775
void ConvertToPes(tIndexTs *IndexTs, int Count)
Definition recording.c:2762
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:2648
cIndexFileGenerator * indexFileGenerator
Definition recording.h:477
static cString IndexFileName(const char *FileName, bool IsPesRecording)
Definition recording.c:2745
bool Get(int Index, uint16_t *FileNumber, off_t *FileOffset, bool *Independent=NULL, int *Length=NULL)
Definition recording.c:2848
int GetClosestIFrame(int Index)
Returns the index of the I-frame that is closest to the given Index (or Index itself,...
Definition recording.c:2912
cMutex mutex
Definition recording.h:478
void Delete(void)
Definition recording.c:2959
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:2291
void Del(cListObject *Object, bool DeleteObject=true)
Definition tools.c:2246
void SetModified(void)
Unconditionally marks this list as modified.
Definition tools.c:2316
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:2205
int Count(void) const
Definition tools.h:640
void Add(cListObject *Object, cListObject *After=NULL)
Definition tools.c:2214
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:2053
cMark(int Position=0, const char *Comment=NULL, double FramesPerSecond=DEFAULTFRAMESPERSECOND)
Definition recording.c:2205
cString comment
Definition recording.h:372
int position
Definition recording.h:371
bool Parse(const char *s)
Definition recording.c:2221
bool Save(FILE *f)
Definition recording.c:2235
cString ToText(void)
Definition recording.c:2216
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:2212
int GetNumSequences(void) const
Returns the actual number of sequences to be cut from the recording.
Definition recording.c:2401
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:2334
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:2367
const cMark * GetNext(int Position) const
Definition recording.c:2358
bool Update(void)
Definition recording.c:2270
bool Load(const char *RecordingFileName, double FramesPerSecond=DEFAULTFRAMESPERSECOND, bool IsPesRecording=false)
Definition recording.c:2258
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:2383
const cMark * Get(int Position) const
Definition recording.c:2340
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:2247
void Align(void)
Definition recording.c:2310
void Sort(void)
Definition recording.c:2322
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:2242
bool Save(void)
Definition recording.c:2301
const cMark * GetPrev(int Position) const
Definition recording.c:2349
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:1588
bool Ok(void)
Definition tools.h:459
char * Read(FILE *f)
Definition tools.c:1507
static cRecordControl * GetRecordControl(const char *FileName)
Definition menu.c:5669
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:2422
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:1969
void Cleanup(cRecordings *Recordings)
Definition recording.c:2053
int Usage(const char *FileName=NULL) const
Definition recording.c:1991
bool Active(cRecordings *Recordings)
Definition recording.c:2003
bool Error(void) const
Definition recording.c:1967
const char * FileNameDst(void) const
Definition recording.c:1970
cRecordingsHandlerEntry(int Usage, const char *FileNameSrc, const char *FileNameDst)
Definition recording.c:1975
void DelAll(void)
Deletes/terminates all operations.
Definition recording.c:2173
cRecordingsHandlerEntry * Get(const char *FileName)
Definition recording.c:2122
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:2135
bool Finished(bool &Error)
Returns true if all operations in the list have been finished.
Definition recording.c:2188
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:2097
int GetUsage(const char *FileName)
Returns the usage type for the given FileName.
Definition recording.c:2180
cList< cRecordingsHandlerEntry > operations
Definition recording.h:330
void Del(const char *FileName)
Deletes the given FileName from the list of operations.
Definition recording.c:2166
virtual ~cRecordingsHandler()
Definition recording.c:2092
void ResetResume(const char *ResumeFileName=NULL)
Definition recording.c:1775
void UpdateByName(const char *FileName)
Definition recording.c:1697
static const char * UpdateFileName(void)
Definition recording.c:1605
virtual ~cRecordings()
Definition recording.c:1598
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:1714
cRecordings(bool Deleted=false)
Definition recording.c:1593
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:1745
const cRecording * GetById(int Id) const
Definition recording.c:1640
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:1666
static cRecordings recordings
Definition recording.h:243
int TotalFileSizeMB(void) const
Definition recording.c:1703
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:1628
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:1612
void Add(cRecording *Recording)
Definition recording.c:1660
static cVideoDirectoryScannerThread * videoDirectoryScannerThread
Definition recording.h:248
void DelByName(const char *FileName)
Definition recording.c:1675
bool MoveRecordings(const char *OldPath, const char *NewPath)
Moves all recordings in OldPath to NewPath.
Definition recording.c:1755
static bool NeedsUpdate(void)
Definition recording.c:1620
void ClearSortNames(void)
Definition recording.c:1783
static int lastRecordingId
Definition recording.h:245
const cRecording * GetByName(const char *FileName) const
Definition recording.c:1649
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:1735
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:5878
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:1798
bool Close(void)
Definition tools.c:1808
int ResumeID
Definition config.h:365
int AlwaysSortFoldersFirst
Definition config.h:320
int RecSortingDirection
Definition config.h:322
int RecordingDirs
Definition config.h:318
int UseSubtitle
Definition config.h:315
int DefaultSortModeRec
Definition config.h:321
char SVDRPHostName[HOST_NAME_MAX]
Definition config.h:305
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:1175
cString & Append(const char *String)
Definition tools.c:1128
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:79
const char * File(void) const
Definition timers.h:77
bool IsSingleEvent(void) const
Definition timers.c:509
void SetFile(const char *File)
Definition timers.c:560
time_t StartTime(void) const
the start time as given by the user
Definition timers.c:737
const cChannel * Channel(void) const
Definition timers.h:69
int Priority(void) const
Definition timers.h:74
int Lifetime(void) const
Definition timers.h:75
cUnbufferedFile is used for large files that are mainly written or read in a streaming manner,...
Definition tools.h:507
static cUnbufferedFile * Create(const char *FileName, int Flags, mode_t Mode=DEFFILEMODE)
Definition tools.c:2024
int Close(void)
Definition tools.c:1872
ssize_t Read(void *Data, size_t Size)
Definition tools.c:1915
off_t Seek(off_t Offset, int Whence)
Definition tools.c:1907
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:3012
#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:3372
bool GenerateIndex(const char *FileName, bool Update)
Generates the index of the existing recording with the given FileName.
Definition recording.c:2980
#define REMOVELATENCY
Definition recording.c:66
cString IndexToHMSF(int Index, bool WithFrame, double FramesPerSecond)
Definition recording.c:3267
static const char * SkipFuzzyChars(const char *s)
Definition recording.c:3237
#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:3324
#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:3235
bool NeedsConversion(const char *p)
Definition recording.c:668
int SecondsToFrames(int Seconds, double FramesPerSecond)
Definition recording.c:3294
#define MAXREMOVETIME
Definition recording.c:68
eRecordingsSortMode RecordingsSortMode
Definition recording.c:3317
bool HasRecordingsSortMode(const char *Directory)
Definition recording.c:3319
#define RECEXT
Definition recording.c:35
#define MAXFILESPERRECORDINGPES
Definition recording.c:3010
#define INDEXCATCHUPWAIT
Definition recording.c:2621
#define INDEXFILESUFFIX
Definition recording.c:2617
#define IFG_BUFFER_SIZE
Definition recording.c:2437
#define INDEXFILETESTINTERVAL
Definition recording.c:2646
#define MAXWAITFORINDEXFILE
Definition recording.c:2644
int InstanceId
Definition recording.c:77
#define DELEXT
Definition recording.c:36
#define INDEXFILECHECKINTERVAL
Definition recording.c:2645
char * ExchangeChars(char *s, bool ToFileSystem)
Definition recording.c:675
bool DirectoryEncoding
Definition recording.c:76
void IncRecordingsSortMode(const char *Directory)
Definition recording.c:3343
int HMSFToIndex(const char *HMSF, double FramesPerSecond)
Definition recording.c:3283
#define LIMIT_SECS_PER_MB_RADIO
Definition recording.c:72
void SetRecordingsSortMode(const char *Directory, eRecordingsSortMode SortMode)
Definition recording.c:3335
cDoneRecordings DoneRecordingsPattern
Definition recording.c:3174
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:3301
cRecordingsHandler RecordingsHandler
Definition recording.c:2083
cMutex MutexMarkFramesPerSecond
Definition recording.c:2203
static bool StillRecording(const char *Directory)
Definition recording.c:1429
struct __attribute__((packed))
Definition recording.c:2623
#define RESUME_NOT_INITIALIZED
Definition recording.c:652
#define SORTMODEFILE
Definition recording.c:58
#define RECORDFILESUFFIXLEN
Definition recording.c:3014
#define MAXINDEXCATCHUP
Definition recording.c:2620
#define NAMEFORMATTS
Definition recording.c:49
#define DATAFORMATTS
Definition recording.c:48
#define RECORDFILESUFFIXPES
Definition recording.c:3011
void SetRecordingTimerId(const char *Directory, const char *TimerId)
Definition recording.c:3354
#define TIMERRECFILE
Definition recording.c:59
#define RECORDFILESUFFIXTS
Definition recording.c:3013
double MarkFramesPerSecond
Definition recording.c:2202
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:3283
@ rsdAscending
Definition recording.h:562
int DirectoryPathMax
Definition recording.c:74
eRecordingsSortMode RecordingsSortMode
Definition recording.c:3317
#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:2083
#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:3267
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