forked from MarkusEh/vdr-plugin-live
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrecman.cpp
More file actions
1719 lines (1586 loc) · 72.7 KB
/
recman.cpp
File metadata and controls
1719 lines (1586 loc) · 72.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <iostream>
#include <dirent.h>
#include "recman.h"
#include "tools.h"
#include "services.h"
#include "epg_events.h"
// STL headers need to be before VDR tools.h (included by <vdr/videodir.h>)
#include <fstream>
#include <stack>
#include <algorithm>
#include <limits>
#include <vdr/videodir.h>
#include <vdr/config.h>
#include <vdr/menu.h>
#include <vdr/svdrp.h>
#define TIMERRECFILE "/.timer"
namespace vdrlive {
/**
* Implementation of class RecordingsManager:
*/
void RecordingsManager::setSortOrder(eSortOrder sortOrder, bool backwards, cSv filter) {
EnsureValidData();
m_sortOrder = sortOrder;
std::vector<RecordingsItemRec*> &all_recordings_sorted = all_recordings[(int)(sortOrder)];
if (all_recordings_sorted.empty() ) {
all_recordings_sorted.assign(all_recordings_iterator(), all_recordings_iterator(iterator_end() ));
std::sort(all_recordings_sorted.begin(), all_recordings_sorted.end(), RecordingsItemPtrCompare::getComp(sortOrder));
if (all_recordings_sorted.begin() == all_recordings_sorted.end())
dsyslog("live: RecordingsManager::setSortOrder, sortOrder = %d, backwards = %s, empty container", (int)sortOrder, backwards?"true":"false");
else
dsyslog("live: RecordingsManager::setSortOrder, sortOrder = %d, backwards = %s, first = %s",
(int)sortOrder, backwards?"true":"false", (*all_recordings_sorted.begin())->NameStr().c_str() );
}
m_backwards = backwards;
if (filter.empty() ) {
m_filter_regex_ptr = nullptr;
} else {
m_filter_regex = getRegex(filter, g_locale, std::regex_constants::icase |
std::regex_constants::nosubs |
std::regex_constants::collate);
m_filter_regex_ptr = &m_filter_regex;
}
}
/*
cStateKey RecordingsManager::m_recordingsStateKey, together with
time_t RecordingsManager::m_last_recordings_update = 0
are used to check for any relevant changes (in VDRs recordings or
in scraper data)
RecordingsTreePtr RecordingsManager::GetRecordingsTree()
is checking for such changes. If there are none, it returns a cached
recording tree (m_recTree)
Otherwise, the rec tree is re-created from currnet data.
*/
RecordingsTreePtr RecordingsManager::GetRecordingsTree()
{
EnsureValidData();
return m_recTree;
}
DuplicatesRecordingsTreePtr RecordingsManager::GetDuplicatesRecordingsTree()
{
EnsureValidData();
return m_duplicatesRecTree;
}
const cRecording *RecordingsManager::GetByHash(cSv hash, const cRecordings* Recordings)
{
if (hash.length() != 42) return nullptr;
if (hash.compare(0, 10, "recording_") != 0) return nullptr;
XXH128_hash_t xxh = parse_hex_128(hash.substr(10));
for (const cRecording* rec = Recordings->First(); rec; rec = Recordings->Next(rec)) {
if (XXH128_isEqual(XXH3_128bits(rec->FileName(), strlen(rec->FileName())), xxh)) return rec;
}
return nullptr;
}
RecordingsItemRec* const RecordingsManager::GetByIdHash(cSv hash)
{
if (hash.length() != 42) return 0;
if (hash.compare(0, 10, "recording_") != 0) return 0;
XXH128_hash_t xxh = parse_hex_128(hash.substr(10));
for (RecordingsItemRec * recItem : all_recordings_iterator() ) {
if (XXH128_isEqual(recItem->IdHash(), xxh)) return recItem;
}
return nullptr;
}
bool RecordingsManager::UpdateRecording(cSv hash, cSv directory, cSv name, bool copy, cSv title, cSv shorttext, cSv description)
{
// std::string new_filename = FileSystemExchangeChars(directory.empty() ? name : cSv(cToSvReplace(directory, "/", "~") << "~" << name), true);
std::string new_filename = FileSystemExchangeChars(directory.empty() ? name : cSv(cToSvConcat(directory, "~", name)), true);
// Check for injections that try to escape from the video dir.
if (new_filename.compare(0, 3, "../") == 0 || new_filename.find("/..") != std::string::npos) {
esyslog("live: renaming failed: new name invalid \"%.*s\"", (int)new_filename.length(), new_filename.data());
return false;
}
LOCK_RECORDINGS_WRITE;
cRecording *recording = const_cast<cRecording *>(RecordingsManager::GetByHash(hash, Recordings));
if (!recording) return false;
std::string oldname = recording->FileName();
size_t found = oldname.find_last_of("/");
if (found == std::string::npos) return false;
std::string newname = concat(cVideoDirectory::Name(), "/", new_filename, cSv(oldname).substr(found));
if (oldname != newname) {
if (recording->IsInUse() ) return false;
if (!MoveDirectory(oldname, newname, copy)) {
esyslog("live: renaming failed from '%.*s' to '%s'", (int)oldname.length(), oldname.data(), newname.c_str());
return false;
}
if (!copy)
Recordings->DelByName(oldname.c_str());
Recordings->AddByName(newname.c_str());
recording = Recordings->GetByName(newname.c_str()); // old pointer to recording invalid after DelByName/AddByName
if (copy)
cRecordingUserCommand::InvokeCommand(RUC_COPIEDRECORDING, newname.c_str(), oldname.c_str());
else {
if (strcmp(strgetbefore(oldname.c_str(), '/', 2), strgetbefore(newname.c_str(), '/', 2)))
cRecordingUserCommand::InvokeCommand(RUC_MOVEDRECORDING, newname.c_str(), oldname.c_str());
else
cRecordingUserCommand::InvokeCommand(RUC_RENAMEDRECORDING, newname.c_str(), oldname.c_str());
}
}
#if VDRVERSNUM >= 20502
// 2021-04-06: Version 2.5.2
// Made the functions cRecordingInfo::SetData() and cRecordingInfo::SetAux() public
// da ist auch cRecordingInfo *Info(void) const { return info; }
// in 2.5.1: noch const cRecordingInfo *Info(void) const { return info; }
// update texts
// need null terminated strings for VDR API
std::string desc(description);
desc.erase(std::remove(desc.begin(), desc.end(), '\r'), desc.end()); // remove \r from HTML
cRecordingInfo* info = recording->Info();
if (title != cSv(info->Title()) || shorttext != cSv(info->ShortText()) || desc != cSv(info->Description()))
{
info->SetData(cToSvConcat(title).c_str(), cToSvConcat(shorttext).c_str(), desc.c_str());
recording->WriteInfo();
}
#endif
Recordings->TouchUpdate();
return true;
}
void RecordingsManager::DeleteResume(cRecording const * recording)
{
if (!recording)
return;
cResumeFile ResumeFile(recording->FileName(), recording->IsPesRecording());
ResumeFile.Delete();
}
void RecordingsManager::DeleteMarks(cRecording const * recording)
{
if (!recording)
return;
cMarks marks;
marks.Load(recording->FileName());
if (marks.Count()) {
cMark *mark = marks.First();
while (mark) {
cMark *nextmark = marks.Next(mark);
marks.Del(mark);
mark = nextmark;
}
marks.Save();
}
}
int RecordingsManager::DeleteRecording(cSv recording_hash, std::string *name)
{
LOCK_TIMERS_WRITE; // must be before LOCK_RECORDINGS_WRITE
Timers->SetExplicitModify();
LOCK_RECORDINGS_WRITE;
cRecording *recording = const_cast<cRecording *>(RecordingsManager::GetByHash(recording_hash, Recordings));
if (!recording) return 1;
if (name) *name = cSv(recording->Name());
// check if recording is active
std::string fileName(recording->FileName());
if (cRecordControl *rc = cRecordControls::GetRecordControl(fileName.c_str())) {
// local timer is active
if (cTimer *Timer = rc->Timer()) {
isyslog("live: deactivating local timer %s before deleting recording %s", *Timer->ToDescr(), name->c_str());
Timer->OnOff();
Timers->SetModified();
}
}
else {
// remote timer
cString TimerId = GetRecordingTimerId(fileName.c_str());
if (*TimerId) {
int Id;
char *RemoteBuf = NULL;
cString Remote;
if (2 == sscanf(TimerId, "%d@%m[^ \n]", &Id, &RemoteBuf) && Id != 0) {
Remote = RemoteBuf;
free(RemoteBuf);
if (cTimer *Timer = Timers->GetById(Id, Remote)) {
cTimer OldTimer = *Timer;
Timers->SetSyncStateKey(StateKeySVDRPRemoteTimersPoll);
cString ErrorMessage1;
if (HandleRemoteTimerModifications(NULL, Timer, &ErrorMessage1)) { // delete active timer on remote VDR
isyslog("live: deactivating remote timer %s before deleting recording %s", *Timer->ToDescr(), name->c_str());
Timer->OnOff();
Timers->SetModified();
cString ErrorMessage2;
if (!HandleRemoteTimerModifications(Timer, NULL, &ErrorMessage2)) { // add deactivated timer on remote VDR
esyslog("live: adding inactive remote timer %s failed: %s", *Timer->ToDescr(), *ErrorMessage2);
return 2;
}
}
else {
esyslog("live: deleting active remote timer %s failed: %s", *Timer->ToDescr(), *ErrorMessage1);
return 2;
}
}
}
}
}
bool result = recording->Delete();
Recordings->DelByName(fileName.c_str());
return result?0:3;
}
int RecordingsManager::GetArchiveType(cRecording const * recording)
{
// 1: on DVD
// 2: on HDD
// 0: "normal" VDR recording
return 0;
}
std::string const RecordingsManager::GetArchiveId(cRecording const * recording, int archiveType)
{
std::string filename = recording->FileName();
if (archiveType==1) {
std::string dvdFile = filename + "/dvd.vdr";
std::ifstream dvd(dvdFile);
if (dvd) {
std::string archiveDisc;
std::string videoDisc;
dvd >> archiveDisc;
if ("0000" == archiveDisc) {
dvd >> videoDisc;
return videoDisc;
}
return archiveDisc;
}
} else if(archiveType==2) {
std::string hddFile = filename + "/hdd.vdr";
std::ifstream hdd(hddFile);
if (hdd) {
std::string archiveDisc;
hdd >> archiveDisc;
return archiveDisc;
}
}
return "";
}
std::string const RecordingsManager::GetArchiveDescr(cRecording const * recording)
{
int archiveType;
std::string archived;
archiveType = GetArchiveType(recording);
if (archiveType==1) {
archived += " [";
archived += tr("On archive DVD No.");
archived += ": ";
archived += GetArchiveId(recording, archiveType);
archived += "]";
} else if (archiveType==2) {
archived += " [";
archived += tr("On archive HDD No.");
archived += ": ";
archived += GetArchiveId(recording, archiveType);
archived += "]";
}
return archived;
}
bool RecordingsManager::StillRecording(cSv RecordingFileName) {
struct stat buffer;
return stat(cToSvConcat(RecordingFileName, TIMERRECFILE).c_str(), &buffer) == 0;
}
bool RecordingsManager::StillRecording(const cRecording *recording) {
int use = recording->IsInUse();
return ((use & ruTimer ) == ruTimer) |
((use & ruDst ) == ruDst) |
((use & ruPending ) == ruPending) |
((use & ruCanceled) == ruCanceled);
}
/**
* Is this recording currently played?
* Return codes:
* 0: this recording is currently played
* 1: this recording does not exist
* 2: no recording is played
* 3: another recording is played
*/
int RecordingsManager::CheckReplay(cSv recording_hash, std::string *fileName) {
LOCK_RECORDINGS_READ;
const cRecording *recording = GetByHash(recording_hash, Recordings);
if (!recording) return 1;
if (fileName) *fileName = cSv(recording->FileName());
const char *current = cReplayControl::NowReplaying();
if (!current) return 2;
if (0 != strcmp(current, recording->FileName())) return 3;
return 0;
}
bool RecordingsManager::StateChanged ()
{
bool result = false;
// will return true only, if the Recordings List has been changed since last read
if (cRecordings::GetRecordingsRead(m_recordingsStateKey)) {
result = true;
m_recordingsStateKey.Remove();
}
return result;
}
void update_all_recordings();
void update_all_recordings_scraper();
void RecordingsManager::EnsureValidData()
// ensure m_recTree is up to date
{
if (m_last_recordings_update + 1 > time(NULL) ) return; // don't update too often
// StateChanged must be executed every time, so not part of
// the short cut evaluation in the if statement below.
bool stateChanged = StateChanged();
// check: changes on scraper data?
bool scraperChanged = false;
cGetScraperUpdateTimes scraperUpdateTimes;
if (scraperUpdateTimes.call(LiveSetup().GetPluginTvscraper()) )
scraperChanged = scraperUpdateTimes.m_recordingsUpdateTime > m_last_recordings_update;
if (stateChanged || all_recordings[(int)(RecordingsManager::eSortOrder::id)].empty() ) update_all_recordings();
if (scraperChanged) update_all_recordings_scraper();
if (stateChanged || scraperChanged || (!m_recTree) ) {
m_last_recordings_update = time(NULL);
std::chrono::time_point<std::chrono::high_resolution_clock> begin = std::chrono::high_resolution_clock::now();
m_recTree = std::shared_ptr<RecordingsTree>(new RecordingsTree());
m_duplicatesRecTree = std::shared_ptr<DuplicatesRecordingsTree>(new DuplicatesRecordingsTree(m_recTree));
std::chrono::duration<double> timeNeeded = std::chrono::high_resolution_clock::now() - begin;
dsyslog("live: DH: ------ RecordingsTree::RecordingsTree() --------, required time: %9.5f", timeNeeded.count() );
}
}
/**
* Implementation of class RecordingsItemPtrCompare
*/
int RecordingsItemPtrCompare::FindBestMatch(RecordingsItemRec *&BestMatch, const std::vector<RecordingsItemRec*>::const_iterator & First, const std::vector<RecordingsItemRec*>::const_iterator & Last, const RecordingsItemRec * EPG_Entry) {
// d: length of movie in minutes, without commercial breaks
// Assumption: the maximum length of commercial breaks is cb% * d
// Assumption: cb = 34%
const long cb = 34;
// lengthLowerBound: minimum of d, if EPG_Entry->Duration() has commercial breaks
long lengthLowerBound = EPG_Entry->Duration() * 100 / ( 100 + cb) ;
// lengthUpperBound: if EPG_Entry->Duration() is d (no commercial breaks), max length of recording with commercial breaks
// Add VDR recording margins to this value
long lengthUpperBound = EPG_Entry->Duration() * (100 + cb) / 100;
lengthUpperBound += (::Setup.MarginStart + ::Setup.MarginStop) * 60;
if(EPG_Entry->Duration() >= 90*60 && lengthLowerBound < 70*60) lengthLowerBound = 70*60;
int numRecordings = 0;
int min_deviation = std::numeric_limits<int>::max();
std::vector<RecordingsItemRec*>::const_iterator bestMatchIter;
for ( std::vector<RecordingsItemRec*>::const_iterator iter = First; iter != Last; ++iter)
if ( (*iter)->Duration() >= lengthLowerBound && (*iter)->Duration() <= lengthUpperBound ) {
int deviation = abs( (*iter)->Duration() - EPG_Entry->Duration() );
if (deviation < min_deviation || numRecordings == 0) {
min_deviation = deviation;
bestMatchIter = iter;
}
++numRecordings;
}
if (numRecordings > 0) BestMatch = *bestMatchIter;
return numRecordings;
}
bool RecordingsItemPtrCompare::ByAscendingDate(const RecordingsItemRec * first, const RecordingsItemRec * second)
{
return (first->StartTime() < second->StartTime());
}
bool RecordingsItemPtrCompare::ByDuplicatesName(const RecordingsItemRec * first, const RecordingsItemRec * second) // return first < second
{
return first->orderDuplicates(second, false);
}
bool RecordingsItemPtrCompare::ByDuplicates(const RecordingsItemRec * first, const RecordingsItemRec * second) // return first < second
{
return first->orderDuplicates(second, true);
}
bool RecordingsItemPtrCompare::ByDuplicatesLanguage(const RecordingsItemRec * first, const RecordingsItemRec * second)
{
return first->orderDuplicates(second, true, true);
}
const char *firstNonPunct(const char *s) {
// returns first non-punct char in s
while (ispunct(*s)) ++s;
return s;
}
int compareWithLocale(cStr first, cStr second) {
const char *ls = firstNonPunct(first.c_str());
const char *rs = firstNonPunct(second.c_str());
return strcoll(ls, rs);
// see https://en.cppreference.com/w/cpp/string/byte/strcoll
// see https://en.cppreference.com/w/cpp/locale/collate/compare
// Compares the character sequence [low1, high1) to the character sequence [low2, high2)
// we use the c-version, as it is usually much faster
}
bool RecordingsItemPtrCompare::ByAscendingNameDescSort(const RecordingsItemRec * first, const RecordingsItemRec * second) // return first < second
// used for sort
{
int i = compareWithLocale(first->NameStr(), second->NameStr() );
if(i != 0) return i < 0;
return first->CompareStD(second) < 0;
}
bool RecordingsItemPtrCompare::ByAscendingNameSort(const RecordingsItemDirPtr & first, const RecordingsItemDirPtr & second) // return first < second
{
return compareWithLocale(first->NameStr(), second->NameStr()) < 0;
}
bool RecordingsItemPtrCompare::ByDescendingRecordingErrors(const RecordingsItemRec * first, const RecordingsItemRec * second) {
return first->RecordingErrors() > second->RecordingErrors();
}
bool RecordingsItemPtrCompare::ByDescendingDurationDeviation(const RecordingsItemRec * first, const RecordingsItemRec * second) {
return first->DurationDeviation() > second->DurationDeviation();
}
bool RecordingsItemPtrCompare::ByEpisode(const RecordingsItemRec * first, const RecordingsItemRec * second) {
return first->scraperEpisodeNumber() < second->scraperEpisodeNumber();
}
bool RecordingsItemPtrCompare::BySeason(const RecordingsItemDirPtr & first, const RecordingsItemDirPtr & second) {
return first->scraperSeasonNumber() < second->scraperSeasonNumber();
}
bool RecordingsItemPtrCompare::ByReleaseDate(const RecordingsItemRec * first, const RecordingsItemRec * second) {
return first->scraperReleaseDate() < second->scraperReleaseDate();
}
tCompRec RecordingsItemPtrCompare::getComp(RecordingsManager::eSortOrder sortOrder) {
switch (sortOrder) {
case RecordingsManager::eSortOrder::name: return &RecordingsItemPtrCompare::ByAscendingNameDescSort;
case RecordingsManager::eSortOrder::date: return &RecordingsItemPtrCompare::ByAscendingDate;
case RecordingsManager::eSortOrder::errors: return &RecordingsItemPtrCompare::ByDescendingRecordingErrors;
case RecordingsManager::eSortOrder::durationDeviation: return &RecordingsItemPtrCompare::ByDescendingDurationDeviation;
case RecordingsManager::eSortOrder::duplicatesLanguage: return &RecordingsItemPtrCompare::ByDuplicatesLanguage;
default:
esyslog("live: ERROR, RecordingsItemPtrCompare::getComp, sortOrder %d unknown", (int)sortOrder);
return &RecordingsItemPtrCompare::ByAscendingNameDescSort;
}
}
bool searchNameDesc(RecordingsItemRec *&RecItem, const std::vector<RecordingsItemRec*> *RecItems, const cEvent *event, cScraperVideo *scraperVideo) {
if (RecItems->empty() ) return false; // there are no recordings
// find all recordings with equal name
RecordingsItemRec dummy_o(event, scraperVideo);
RecordingsItemRec* dummy = &dummy_o;
dummy->finalize();
const auto equalName = std::equal_range(RecItems->begin(), RecItems->end(), dummy, RecordingsItemPtrCompare::ByDuplicatesName);
if (equalName.first == equalName.second) return false; // there is no recording with this name
// find all recordings with matching short text / description / language
auto equalDuplicates = std::equal_range(equalName.first, equalName.second, dummy, RecordingsItemPtrCompare::ByDuplicatesLanguage);
if (equalDuplicates.first == equalDuplicates.second) { // nothing found. Try again, and include other languages
equalDuplicates = std::equal_range(equalName.first, equalName.second, dummy, RecordingsItemPtrCompare::ByDuplicates);
}
if (equalDuplicates.first != equalDuplicates.second) { // exact match found
if (RecordingsItemPtrCompare::FindBestMatch(RecItem, equalDuplicates.first, equalDuplicates.second, dummy) > 0) return true;
RecItem = *equalDuplicates.first;
return true;
}
// no exact match found, get recording with most matching characters in short text / description
int numEqualCharsLow = 0;
int numEqualCharsUp = 0;
if (equalDuplicates.first != equalName.first) {
--equalDuplicates.first;
(*equalDuplicates.first)->CompareStD(dummy, &numEqualCharsLow);
}
if (equalDuplicates.second != equalName.second)
(*equalDuplicates.second)->CompareStD(dummy, &numEqualCharsUp);
if (numEqualCharsLow > numEqualCharsUp ) {
if (numEqualCharsLow > 5) { RecItem = *equalDuplicates.first; return true; }
} else {
if (numEqualCharsUp > 5) { RecItem = *equalDuplicates.second; return true; }
}
// no sufficient match in short text / description
// get best match from length of event match
int num_match_rec = RecordingsItemPtrCompare::FindBestMatch(RecItem, equalName.first, equalName.second, dummy);
if (num_match_rec > 5) return false; // series (too many matching lengths)
if (num_match_rec > 0) return true;
// no matching length
RecItem = *equalDuplicates.first;
return !scraperVideo;
}
/**
* Implementation of class RecordingsItemDir:
*/
RecordingsItemDir::RecordingsItemDir(cSv name, int level):
m_name(name),
m_level(level) { }
RecordingsItemDir::~RecordingsItemDir() { }
int RecordingsItemDir::numberOfRecordings() const {
int result = m_entries.size();
for (const auto &item: m_subdirs) result += item->numberOfRecordings();
return result;
}
void RecordingsItemDir::finishRecordingsTree() {
for (auto &item: m_subdirs) item->finishRecordingsTree();
if (m_cmp_rec) std::sort(m_entries.begin(), m_entries.end(), m_cmp_rec);
if (m_cmp_dir) std::sort(m_subdirs.begin(), m_subdirs.end(), m_cmp_dir);
else std::sort(m_subdirs.begin(), m_subdirs.end(), RecordingsItemPtrCompare::ByAscendingNameSort);
m_entries.shrink_to_fit();
m_subdirs.shrink_to_fit();
}
RecordingsItemDirPtr RecordingsItemDir::addDirIfNotExists(cSv dirName) {
std::vector<RecordingsItemDirPtr>::iterator iter = std::lower_bound(m_subdirs.begin(), m_subdirs.end(), dirName);
if (iter != m_subdirs.end() && !(dirName < *iter) ) return *iter;
RecordingsItemDirPtr dirPtr= std::make_shared<RecordingsItemDir>(dirName, Level() + 1);
m_subdirs.insert(iter, dirPtr);
return dirPtr;
}
RecordingsItemDirPtr RecordingsItemDir::addDirCollectionIfNotExists(int collectionId, const RecordingsItemRec *rPtr) {
std::vector<RecordingsItemDirPtr>::iterator iter = std::lower_bound(m_subdirs.begin(), m_subdirs.end(), collectionId);
if (iter != m_subdirs.end() && !(collectionId < *iter) ) return *iter;
RecordingsItemDirPtr dirPtr2 = std::make_shared<RecordingsItemDirCollection>(Level() + 1, rPtr);
m_subdirs.insert(iter, dirPtr2);
return dirPtr2;
}
RecordingsItemDirPtr RecordingsItemDir::addDirSeasonIfNotExists(int seasonNumber, const RecordingsItemRec *rPtr) {
std::vector<RecordingsItemDirPtr>::iterator iter = std::lower_bound(m_subdirs.begin(), m_subdirs.end(), seasonNumber);
if (iter != m_subdirs.end() && !(seasonNumber < *iter) ) return *iter;
RecordingsItemDirPtr dirPtr2 = std::make_shared<RecordingsItemDirSeason>(Level() + 1, rPtr);
m_subdirs.insert(iter, dirPtr2);
return dirPtr2;
}
const_rec_iterator<RecordingsItemDirPtr> RecordingsItemDir::get_dir_iterator() const {
return const_rec_iterator<RecordingsItemDirPtr>(m_subdirs, false, RecordingsManager::m_filter_regex_ptr);
}
const_rec_iterator<RecordingsItemRec*> RecordingsItemDir::get_rec_iterator() const {
if (m_cmp_rec) {
return const_rec_iterator<RecordingsItemRec*>(m_entries, false, RecordingsManager::m_filter_regex_ptr);
} else {
if (m_sortOrder != RecordingsManager::m_sortOrder) {
m_sortOrder = RecordingsManager::m_sortOrder;
std::sort(m_entries.begin(), m_entries.end(), RecordingsItemPtrCompare::getComp(RecordingsManager::m_sortOrder));
}
return const_rec_iterator<RecordingsItemRec*>(m_entries, RecordingsManager::m_backwards, RecordingsManager::m_filter_regex_ptr);
}
}
bool RecordingsItemDir::checkNew() const{
for (const auto rec:get_rec_iterator() ) if (rec->IsNew()) return true;
for (const auto &subdir:m_subdirs) if (subdir->checkNew() ) return true;
return false;
}
void RecordingsItemDir::addDirList(std::vector<std::string> &dirs, cSv basePath) const
{
std::string basePath0(basePath);
if (basePath.empty() ) dirs.push_back("");
else basePath0.append(1, FOLDERDELIMCHAR);
size_t basePath0_len = basePath0.length();
for (const auto &subdir: m_subdirs) {
basePath0.erase(basePath0_len);
basePath0.append(subdir->m_name);
dirs.push_back(basePath0);
subdir->addDirList(dirs, basePath0);
}
}
void RecordingsItemDir::setTvShow(const RecordingsItemRec *rPtr) {
if (m_cmp_dir) return;
m_cmp_dir = RecordingsItemPtrCompare::BySeason;
m_imageLevels = cImageLevels(eImageLevel::tvShowCollection, eImageLevel::anySeasonCollection);
m_rec_item = rPtr;
m_s_season_number = m_rec_item->scraperSeasonNumber();
}
const cTvMedia &RecordingsItemDir::scraperImage() const {
if (m_s_image_requested) return m_s_image;
if (m_rec_item) {
if (!m_rec_item->StillRecording() && time(NULL) > m_rec_item->m_stopRecording + 10*60) { // retry up to 10 mins after recording has finished
m_s_image_requested = true;
}
if (m_rec_item->m_scraperVideo)
m_s_image = m_rec_item->m_scraperVideo->getImage(m_imageLevels, cOrientations(eOrientation::landscape, eOrientation::portrait, eOrientation::banner), false);
} else
m_s_image_requested = true;
return m_s_image;
}
bool RecordingsItemDir::matches_regex(std::regex *regex_filter) const {
if (!regex_filter) return true;
for (const auto rec:get_rec_iterator() ) if (rec->matches_regex(regex_filter)) return true;
for (const auto &subdir:m_subdirs) if (subdir->matches_regex(regex_filter)) return true;
return false;
}
/**
* Implementation of class RecordingsItemDirFileSystem
*/
RecordingsItemDirFileSystem::RecordingsItemDirFileSystem(cSv name, cSv name_contains, int level):
RecordingsItemDir(name, level),
m_name_contains(name_contains)
{ }
int RecordingsItemDirFileSystem::numberOfRecordings() const {
// ignore regex filter for counting here
std::regex *filter_regex_ptr = RecordingsManager::m_filter_regex_ptr;
RecordingsManager::m_filter_regex_ptr = nullptr;
int result = get_rec_iterator().size();
RecordingsManager::m_filter_regex_ptr = filter_regex_ptr;
// subdirs
for (const auto &item: m_subdirs) result += item->numberOfRecordings();
return result;
}
bool RecordingsItemDirFileSystem::Contains(const RecordingsItemRec *rec) const {
return rec->Folder() == m_name_contains; // filesystem folders
}
const_rec_iterator<RecordingsItemRec*> RecordingsItemDirFileSystem::get_rec_iterator() const {
return const_rec_iterator<RecordingsItemRec*>(this);
}
RecordingsItemDirPtr RecordingsItemDirFileSystem::addDirIfNotExists(cSv dirName) {
std::vector<RecordingsItemDirPtr>::iterator iter = std::lower_bound(m_subdirs.begin(), m_subdirs.end(), dirName);
if (iter != m_subdirs.end() && !(dirName < *iter) ) return *iter;
RecordingsItemDirPtr dirPtr;
if (m_name_contains.empty())
dirPtr = std::make_shared<RecordingsItemDirFileSystem>(dirName, dirName, Level() + 1);
else
dirPtr = std::make_shared<RecordingsItemDirFileSystem>(dirName, cToSvConcat(m_name_contains, FOLDERDELIMCHAR, dirName), Level() + 1);
m_subdirs.insert(iter, dirPtr);
return dirPtr;
}
const_rec_iterator<RecordingsItemRec*> RecordingsItemDirFlat::get_rec_iterator() const {
return const_rec_iterator<RecordingsItemRec*>((RecordingsItemDirFileSystem*)nullptr, 100);
}
/**
* Implementation of class RecordingsItemDirCollection:
*/
RecordingsItemDirCollection::RecordingsItemDirCollection(int level, const RecordingsItemRec *rPtr):
RecordingsItemDir("", level)
{
m_cmp_rec = RecordingsItemPtrCompare::ByReleaseDate;
m_imageLevels = cImageLevels(eImageLevel::tvShowCollection, eImageLevel::seasonMovie);
m_rec_item = rPtr;
m_s_collection_id = m_rec_item->m_s_collection_id;
m_rec_item->m_scraperVideo->getOverview(nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, &m_name);
}
const_rec_iterator<RecordingsItemRec*> RecordingsItemDirCollection::get_rec_iterator() const {
return const_rec_iterator<RecordingsItemRec*>(m_entries, false, RecordingsManager::m_filter_regex_ptr);
}
/**
* Implementation of class RecordingsItemDirSeason:
*/
RecordingsItemDirSeason::RecordingsItemDirSeason(int level, const RecordingsItemRec *rPtr):
RecordingsItemDir(cToSvInt(rPtr->m_s_season_number), level)
{
m_cmp_rec = RecordingsItemPtrCompare::ByEpisode;
// m_imageLevels = cImageLevels(eImageLevel::seasonMovie, eImageLevel::tvShowCollection, eImageLevel::anySeasonCollection);
m_imageLevels = cImageLevels(eImageLevel::seasonMovie);
m_rec_item = rPtr;
m_s_season_number = m_rec_item->m_s_season_number;
}
const_rec_iterator<RecordingsItemRec*> RecordingsItemDirSeason::get_rec_iterator() const {
return const_rec_iterator<RecordingsItemRec*>(m_entries, false, RecordingsManager::m_filter_regex_ptr);
}
int GetNumberOfTsFiles(cSv fileName) {
// find our number of ts files
size_t folder_length = fileName.length();
cToSvConcat file_path(fileName, "/00001.ts");
struct stat buffer;
uint32_t num_ts_files;
std::chrono::time_point<std::chrono::high_resolution_clock> timeStart = std::chrono::high_resolution_clock::now();
for (num_ts_files = 1; num_ts_files < 100000u; ++num_ts_files) {
file_path.erase(folder_length+1);
file_path.appendInt<5>(num_ts_files).append(".ts");
// stat is 10% faster than access on my system. On others, there is a larger difference
// see https://stackoverflow.com/questions/12774207/fastest-way-to-check-if-a-file-exists-using-standard-c-c11-14-17-c
if (stat(file_path.c_str(), &buffer) != 0) break;
}
std::chrono::duration<double> timeNeeded = std::chrono::high_resolution_clock::now() - timeStart;
if (timeNeeded.count() > 0.1)
dsyslog("live, time GetNumberOfTsFiles: %f, recording %.*s, num ts files %d", timeNeeded.count(), (int)fileName.length(), fileName.data(), num_ts_files - 1);
return num_ts_files - 1;
}
/**
* Implementation of class RecordingsItemRec:
*/
// check recording != nullpointer before calling!
RecordingsItemRec::RecordingsItemRec(const cRecording* recording, cMeasureTime *timeIdentify, cMeasureTime *timeOverview, cMeasureTime *timeItemRec):
m_id(recording->Id()),
m_hash(recording->FileName()?XXH3_128bits(recording->FileName(), strlen(recording->FileName()) ):XXH3_128bits("no file", 7)),
m_name_vdr(cSv(recording->Name())),
m_file_name(cSv(recording->FileName()))
{
m_IsNew = recording->IsNew();
m_startTime = recording->Start();
if (!RecordingsManager::StillRecording(recording) && !RecordingsManager::StillRecording(m_file_name)) {
m_stopRecording = 0;
m_fileSizeMB = DirSizeMB(m_file_name.c_str());
m_duration = recording->LengthInSeconds();
m_number_ts_files = GetNumberOfTsFiles(m_file_name);
#if VDRVERSNUM >= 20505
if (recording->Info()) m_recordingErrors = recording->Info()->Errors();
#endif
}
#if VDRVERSNUM < 20505
m_recordingErrors = 0;
#endif
const cRecordingInfo *info = recording->Info();
if (info) {
m_shortText = cSv(info->ShortText());
m_description = cSv(info->Description());
m_channelName = cSv(info->ChannelName());
if (info->GetEvent()) m_parentalRating = info->GetEvent()->ParentalRating();
#if VDRVERSNUM >= 20605
m_framesPerSecond = info->FramesPerSecond();
m_frameWidth = info->FrameWidth();
m_frameHeight = info->FrameHeight();
m_scanType = info->ScanType();
m_aspectRatio = info->AspectRatio();
#endif
}
// scraper data
if (timeItemRec) timeItemRec->start();
m_timeIdentify = timeIdentify;
m_timeOverview = timeOverview;
getScraperData(recording);
if (timeItemRec) timeItemRec->stop();
m_video_SD_HD = get_SD_HD(info); // we might use scraper data for this
}
bool RecordingsItemRec::has_changed(const cRecording* recording) {
if (!XXH128_isEqual(m_hash, recording->FileName()?XXH3_128bits(recording->FileName(), strlen(recording->FileName()) ):XXH3_128bits("no file", 7))) return true;
if (!is_equal_utf8_sanitized_string(m_name_vdr, recording->Name() )) return true;
m_IsNew = recording->IsNew();
if (m_startTime != recording->Start()) return true;
const cRecordingInfo *info = recording->Info();
if (info) {
if (!is_equal_utf8_sanitized_string(m_shortText, info->ShortText())) return true;
if (!is_equal_utf8_sanitized_string(m_description, info->Description())) return true;
if (!is_equal_utf8_sanitized_string(m_channelName, info->ChannelName())) return true;
if (info->GetEvent() && m_parentalRating != info->GetEvent()->ParentalRating()) return true;
#if VDRVERSNUM >= 20605
if (m_framesPerSecond != info->FramesPerSecond()) return true;
if (m_frameWidth != info->FrameWidth()) return true;
if (m_frameHeight != info->FrameHeight()) return true;
if (m_scanType != info->ScanType()) return true;
if (m_aspectRatio != info->AspectRatio()) return true;
#endif
} else {
if (!m_shortText.empty() || !m_description.empty() || !m_channelName.empty()) return true;
}
m_seen = true;
return false;
}
RecordingsItemRec::RecordingsItemRec(const cEvent *event, cScraperVideo *scraperVideo):
m_id(-1),
m_hash(XXH3_128bits("dummy recording", 15)),
m_name_vdr(cSv(event->Title()))
{
m_shortText = cSv(event->ShortText());
m_description = std::string(cSv(event->Description()));
m_parentalRating = event->ParentalRating();
m_startTime = event->StartTime();
m_duration = event->Duration() / 60; // duration in minutes
m_stopRecording = 0;
if (scraperVideo) {
m_s_videoType = scraperVideo->getVideoType();
m_s_dbid = scraperVideo->getDbId();
m_s_episode_number = scraperVideo->getEpisodeNumber();
m_s_season_number = scraperVideo->getSeasonNumber();
m_language = scraperVideo->getLanguage();
m_video_SD_HD = scraperVideo->getHD();
} else {
m_s_videoType = tNone;
}
}
void RecordingsItemRec::finalize() {
// everything that can be done without needing the VDR cRecording object
// utf8 sanitize all strings
utf8_sanitize_string(m_name_vdr);
utf8_sanitize_string(m_shortText);
utf8_sanitize_string(m_description);
utf8_sanitize_string(m_channelName);
utf8_sanitize_string(m_s_title);
utf8_sanitize_string(m_s_episode_name);
utf8_sanitize_string(m_s_IMDB_ID);
utf8_sanitize_string(m_s_release_date);
// get m_name, m_name_str, m_folder
const_split_iterator name_split(iterator_end(), m_name_vdr, '~');
--name_split;
m_name = *name_split;
m_name_str = name_split.pos();
if (name_split != iterator_begin()) {
// int len = std::distance((const char *)m_name_vdr.data(), name_split.pos());
// if (len < 2) esyslog("live, ERROR in finalize, len =%d, m_name_str = %s", len, m_name_vdr.c_str());
m_folder = cSv(m_name_vdr.data(), std::distance((const char *)m_name_vdr.data(), name_split.pos())-1);
}
m_seen = true;
}
bool RecordingsItemRec::StillRecording(const cRecording* recording) const {
if (m_stopRecording != std::numeric_limits<time_t>::max() ) return false;
if (recording && RecordingsManager::StillRecording(recording)) return true;
if (RecordingsManager::StillRecording(m_file_name)) return true;
m_stopRecording = time(NULL);
return false;
}
int RecordingsItemRec::FileSizeMB() const {
if (m_fileSizeMB < 0) {
int fs = DirSizeMB(m_file_name.c_str());
if (StillRecording())
return fs; // check again later for ongoing recordings
m_fileSizeMB = fs;
}
return m_fileSizeMB;
}
int RecordingsItemRec::NumberTsFiles() const {
if (m_number_ts_files < 0) {
int number_ts_files = GetNumberOfTsFiles(m_file_name);
if (StillRecording())
return number_ts_files; // check again later for ongoing recordings
m_number_ts_files = number_ts_files;
}
return m_number_ts_files;
}
int RecordingsItemRec::Duration() const {
if (m_duration < 0) {
LOCK_RECORDINGS_READ;
const cRecording* recording = Recordings->GetById(m_id);
if (recording) {
int duration = recording->LengthInSeconds();
if (StillRecording(recording)) return duration;
m_duration = duration;
} else
m_duration = 0; // avoid re-checks for not existing recording
}
return m_duration;
}
int RecordingsItemRec::RecordingErrors() const {
#if VDRVERSNUM >= 20505
if (m_recordingErrors < 0) {
LOCK_RECORDINGS_READ;
const cRecording* recording = Recordings->GetById(m_id);
if (recording && recording->Info() ) {
int recordingErrors = recording->Info()->Errors();
if (StillRecording(recording)) return recordingErrors;
m_recordingErrors = recordingErrors;
}
}
return m_recordingErrors;
#else
return 0;
#endif
}
void update_all_recordings () {
cMeasureTime timeIdentify, timeOverview, timeItemRec, time_update_all_recordings;
time_update_all_recordings.start();
bool change = false;
// mark all recordings in cache as not seen
for (RecordingsItemRec* r: all_recordings_iterator(iterator_begin() )) r->set_seen(false);
{
// increase vector with all_recordings[(int)(RecordingsManager::eSortOrder::id)] to the required size
int max_id = 0;
LOCK_RECORDINGS_READ;
for (const cRecording* recording = Recordings->First(); recording; recording = Recordings->Next(recording))
max_id = std::max(max_id, recording->Id());
dsyslog("live, max rec id %d, number of recordings %d", max_id, Recordings->Count());
if ((size_t)(max_id)+1 > RecordingsManager::all_recordings[(int)(RecordingsManager::eSortOrder::id)].size())
RecordingsManager::all_recordings[(int)(RecordingsManager::eSortOrder::id)].resize(max_id+1, nullptr);
// for each vdr recording: compare with cached recording:
// if equal: mark as seen
// if not equal: delete
// if not available (or just deleted); create, and mark as seen
for (const cRecording* recording = Recordings->First(); recording; recording = Recordings->Next(recording)) {
RecordingsItemRec *& live_rec = RecordingsManager::all_recordings[(int)(RecordingsManager::eSortOrder::id)][recording->Id()];
if (live_rec && live_rec->has_changed(recording)) {
dsyslog("live, recording %s has changed", recording->Name());
delete live_rec;
live_rec = nullptr;
} // check is there is a recording, and if yes: has it changed?
if (live_rec) live_rec->updateScraperDataIfStillRecording(recording);
if (!live_rec) {
change = true;
live_rec = new RecordingsItemRec(recording);
live_rec->finalize();
}
} // for recording = Recordings->First(); ...
}
/*
timeItemRec.print("live: scraper: all ");
timeIdentify.print("live: scraper: Identify ");
timeOverview.print("live: scraper: Overview ");
*/
// delete all non-seen cached recordings
for (RecordingsItemRec*& r: all_recordings_iterator(iterator_begin() )) if (!r->seen()) {
change = true;
dsyslog("live cache: delete recording %s", r->NameStr().c_str() );
delete r;
r = nullptr;
}
if (!change) return;
// update sorted recs
for (int sort_order = (int)RecordingsManager::eSortOrder::id + 1; sort_order < (int)RecordingsManager::eSortOrder::list_end; ++sort_order)
RecordingsManager::all_recordings[sort_order].clear();
// add sorted by name
RecordingsManager::m_sortOrder = RecordingsManager::eSortOrder::name;
std::vector<RecordingsItemRec*> &all_recordings_sorted = RecordingsManager::all_recordings[(int)(RecordingsManager::m_sortOrder)];
// dsyslog("live: RecordingsManager::update_all_recordings, sort recordings");
all_recordings_sorted.assign(all_recordings_iterator(), all_recordings_iterator(iterator_end() ));
std::sort(all_recordings_sorted.begin(), all_recordings_sorted.end(), RecordingsItemPtrCompare::getComp(RecordingsManager::m_sortOrder));
if (all_recordings_sorted.begin() == all_recordings_sorted.end())
dsyslog("live: RecordingsManager::update_all_recordings, after sort recordings, empty cont");
else
dsyslog("live: RecordingsManager::update_all_recordings, after sort recordings, first = %s", (*all_recordings_sorted.begin())->NameStr().c_str() );
time_update_all_recordings.stop();
time_update_all_recordings.print("live: time_update_all_recordings ");
}
void update_all_recordings_scraper() {
cMeasureTime time_update_all_recordings;
{
int all_rec_s = RecordingsManager::all_recordings[(int)(RecordingsManager::eSortOrder::id)].size();
LOCK_RECORDINGS_READ;
for (const cRecording* recording = Recordings->First(); recording; recording = Recordings->Next(recording)) {
if (recording->Id() >= all_rec_s) continue; // VDR has added recordings after last update of all_recordings
RecordingsItemRec *live_rec = RecordingsManager::all_recordings[(int)(RecordingsManager::eSortOrder::id)][recording->Id()];
if (!live_rec) continue;
time_update_all_recordings.start();
live_rec->updateScraperData(recording);
time_update_all_recordings.stop();
}
}
time_update_all_recordings.print("live: time_update_all_recordings_scraper ");