summaryrefslogtreecommitdiffstats
path: root/xbmc/pvr/PVRManager.cpp
blob: 715397e7fc8ea87ad8524f10e559c6c9b5cde55b (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
/*
 *  Copyright (C) 2012-2018 Team Kodi
 *  This file is part of Kodi - https://kodi.tv
 *
 *  SPDX-License-Identifier: GPL-2.0-or-later
 *  See LICENSES/README.md for more information.
 */

#include "PVRManager.h"

#include "FileItem.h"
#include "ServiceBroker.h"
#include "guilib/LocalizeStrings.h"
#include "interfaces/AnnouncementManager.h"
#include "messaging/ApplicationMessenger.h"
#include "pvr/PVRComponentRegistration.h"
#include "pvr/PVRDatabase.h"
#include "pvr/PVRPlaybackState.h"
#include "pvr/addons/PVRClient.h"
#include "pvr/addons/PVRClients.h"
#include "pvr/channels/PVRChannel.h"
#include "pvr/channels/PVRChannelGroup.h"
#include "pvr/channels/PVRChannelGroupInternal.h"
#include "pvr/channels/PVRChannelGroups.h"
#include "pvr/channels/PVRChannelGroupsContainer.h"
#include "pvr/epg/EpgInfoTag.h"
#include "pvr/guilib/PVRGUIActionsChannels.h"
#include "pvr/guilib/PVRGUIActionsPlayback.h"
#include "pvr/guilib/PVRGUIChannelIconUpdater.h"
#include "pvr/guilib/PVRGUIProgressHandler.h"
#include "pvr/guilib/guiinfo/PVRGUIInfo.h"
#include "pvr/providers/PVRProvider.h"
#include "pvr/providers/PVRProviders.h"
#include "pvr/recordings/PVRRecording.h"
#include "pvr/recordings/PVRRecordings.h"
#include "pvr/timers/PVRTimerInfoTag.h"
#include "pvr/timers/PVRTimers.h"
#include "settings/Settings.h"
#include "utils/JobManager.h"
#include "utils/Stopwatch.h"
#include "utils/StringUtils.h"
#include "utils/URIUtils.h"
#include "utils/log.h"

#include <algorithm>
#include <memory>
#include <mutex>
#include <string>
#include <utility>
#include <vector>

using namespace PVR;
using namespace std::chrono_literals;

namespace
{

class CPVRJob
{
public:
  virtual ~CPVRJob() = default;

  virtual bool DoWork() = 0;
  virtual const std::string GetType() const = 0;

protected:
};

template<typename F>
class CPVRLambdaJob : public CPVRJob
{
public:
  CPVRLambdaJob() = delete;
  CPVRLambdaJob(const std::string& type, F&& f) : m_type(type), m_f(std::forward<F>(f)) {}

  bool DoWork() override
  {
    m_f();
    return true;
  }

  const std::string GetType() const override { return m_type; }

private:
  std::string m_type;
  F m_f;
};

} // unnamed namespace

namespace PVR
{

class CPVRManagerJobQueue
{
public:
  CPVRManagerJobQueue() : m_triggerEvent(false) {}

  void Start();
  void Stop();
  void Clear();

  template<typename F>
  void Append(const std::string& type, F&& f)
  {
    AppendJob(new CPVRLambdaJob<F>(type, std::forward<F>(f)));
  }

  void ExecutePendingJobs();

  bool WaitForJobs(unsigned int milliSeconds)
  {
    return m_triggerEvent.Wait(std::chrono::milliseconds(milliSeconds));
  }

private:
  void AppendJob(CPVRJob* job);

  CCriticalSection m_critSection;
  CEvent m_triggerEvent;
  std::vector<CPVRJob*> m_pendingUpdates;
  bool m_bStopped = true;
};

} // namespace PVR

void CPVRManagerJobQueue::Start()
{
  std::unique_lock<CCriticalSection> lock(m_critSection);
  m_bStopped = false;
  m_triggerEvent.Set();
}

void CPVRManagerJobQueue::Stop()
{
  std::unique_lock<CCriticalSection> lock(m_critSection);
  m_bStopped = true;
  m_triggerEvent.Reset();
}

void CPVRManagerJobQueue::Clear()
{
  std::unique_lock<CCriticalSection> lock(m_critSection);
  for (CPVRJob* updateJob : m_pendingUpdates)
    delete updateJob;

  m_pendingUpdates.clear();
  m_triggerEvent.Set();
}

void CPVRManagerJobQueue::AppendJob(CPVRJob* job)
{
  std::unique_lock<CCriticalSection> lock(m_critSection);

  // check for another pending job of given type...
  if (std::any_of(m_pendingUpdates.cbegin(), m_pendingUpdates.cend(),
                  [job](CPVRJob* updateJob) { return updateJob->GetType() == job->GetType(); }))
  {
    delete job;
    return;
  }

  m_pendingUpdates.push_back(job);
  m_triggerEvent.Set();
}

void CPVRManagerJobQueue::ExecutePendingJobs()
{
  std::vector<CPVRJob*> pendingUpdates;

  {
    std::unique_lock<CCriticalSection> lock(m_critSection);

    if (m_bStopped)
      return;

    pendingUpdates = std::move(m_pendingUpdates);
    m_triggerEvent.Reset();
  }

  CPVRJob* job = nullptr;
  while (!pendingUpdates.empty())
  {
    job = pendingUpdates.front();
    pendingUpdates.erase(pendingUpdates.begin());

    job->DoWork();
    delete job;
  }
}

CPVRManager::CPVRManager()
  : CThread("PVRManager"),
    m_providers(new CPVRProviders),
    m_channelGroups(new CPVRChannelGroupsContainer),
    m_recordings(new CPVRRecordings),
    m_timers(new CPVRTimers),
    m_addons(new CPVRClients),
    m_guiInfo(new CPVRGUIInfo),
    m_components(new CPVRComponentRegistration),
    m_epgContainer(m_events),
    m_pendingUpdates(new CPVRManagerJobQueue),
    m_database(new CPVRDatabase),
    m_parentalTimer(new CStopWatch),
    m_playbackState(new CPVRPlaybackState),
    m_settings({CSettings::SETTING_PVRPOWERMANAGEMENT_ENABLED,
                CSettings::SETTING_PVRPOWERMANAGEMENT_SETWAKEUPCMD,
                CSettings::SETTING_PVRPARENTAL_ENABLED, CSettings::SETTING_PVRPARENTAL_DURATION})
{
  CServiceBroker::GetAnnouncementManager()->AddAnnouncer(this);
  m_actionListener.Init(*this);

  CLog::LogFC(LOGDEBUG, LOGPVR, "PVR Manager instance created");
}

CPVRManager::~CPVRManager()
{
  m_actionListener.Deinit(*this);
  CServiceBroker::GetAnnouncementManager()->RemoveAnnouncer(this);

  CLog::LogFC(LOGDEBUG, LOGPVR, "PVR Manager instance destroyed");
}

void CPVRManager::Announce(ANNOUNCEMENT::AnnouncementFlag flag,
                           const std::string& sender,
                           const std::string& message,
                           const CVariant& data)
{
  if (!IsStarted())
    return;

  if ((flag & (ANNOUNCEMENT::GUI)))
  {
    if (message == "OnScreensaverActivated")
      m_addons->OnPowerSavingActivated();
    else if (message == "OnScreensaverDeactivated")
      m_addons->OnPowerSavingDeactivated();
  }
}

std::shared_ptr<CPVRDatabase> CPVRManager::GetTVDatabase() const
{
  std::unique_lock<CCriticalSection> lock(m_critSection);
  if (!m_database || !m_database->IsOpen())
    CLog::LogF(LOGERROR, "Failed to open the PVR database");

  return m_database;
}

std::shared_ptr<CPVRProviders> CPVRManager::Providers() const
{
  std::unique_lock<CCriticalSection> lock(m_critSection);
  return m_providers;
}

std::shared_ptr<CPVRChannelGroupsContainer> CPVRManager::ChannelGroups() const
{
  std::unique_lock<CCriticalSection> lock(m_critSection);
  return m_channelGroups;
}

std::shared_ptr<CPVRRecordings> CPVRManager::Recordings() const
{
  std::unique_lock<CCriticalSection> lock(m_critSection);
  return m_recordings;
}

std::shared_ptr<CPVRTimers> CPVRManager::Timers() const
{
  std::unique_lock<CCriticalSection> lock(m_critSection);
  return m_timers;
}

std::shared_ptr<CPVRClients> CPVRManager::Clients() const
{
  // note: m_addons is const (only set/reset in ctor/dtor). no need for a lock here.
  return m_addons;
}

std::shared_ptr<CPVRClient> CPVRManager::GetClient(const CFileItem& item) const
{
  int iClientID = PVR_INVALID_CLIENT_ID;

  if (item.HasPVRChannelInfoTag())
    iClientID = item.GetPVRChannelInfoTag()->ClientID();
  else if (item.HasPVRRecordingInfoTag())
    iClientID = item.GetPVRRecordingInfoTag()->ClientID();
  else if (item.HasPVRTimerInfoTag())
    iClientID = item.GetPVRTimerInfoTag()->ClientID();
  else if (item.HasEPGInfoTag())
    iClientID = item.GetEPGInfoTag()->ClientID();
  else if (URIUtils::IsPVRChannel(item.GetPath()))
  {
    const std::shared_ptr<CPVRChannel> channel = m_channelGroups->GetByPath(item.GetPath());
    if (channel)
      iClientID = channel->ClientID();
  }
  else if (URIUtils::IsPVRRecording(item.GetPath()))
  {
    const std::shared_ptr<CPVRRecording> recording = m_recordings->GetByPath(item.GetPath());
    if (recording)
      iClientID = recording->ClientID();
  }
  return GetClient(iClientID);
}

std::shared_ptr<CPVRClient> CPVRManager::GetClient(int iClientId) const
{
  return m_addons->GetCreatedClient(iClientId);
}

std::shared_ptr<CPVRPlaybackState> CPVRManager::PlaybackState() const
{
  // note: m_playbackState is const (only set/reset in ctor/dtor). no need for a lock here.
  return m_playbackState;
}

CPVREpgContainer& CPVRManager::EpgContainer()
{
  // note: m_epgContainer is const (only set/reset in ctor/dtor). no need for a lock here.
  return m_epgContainer;
}

void CPVRManager::Clear()
{
  m_playbackState->Clear();
  m_pendingUpdates->Clear();

  std::unique_lock<CCriticalSection> lock(m_critSection);

  m_guiInfo.reset();
  m_timers.reset();
  m_recordings.reset();
  m_providers.reset();
  m_channelGroups.reset();
  m_parentalTimer.reset();
  m_database.reset();

  m_bEpgsCreated = false;
}

void CPVRManager::ResetProperties()
{
  std::unique_lock<CCriticalSection> lock(m_critSection);
  Clear();

  m_database.reset(new CPVRDatabase);
  m_providers.reset(new CPVRProviders);
  m_channelGroups.reset(new CPVRChannelGroupsContainer);
  m_recordings.reset(new CPVRRecordings);
  m_timers.reset(new CPVRTimers);
  m_guiInfo.reset(new CPVRGUIInfo);
  m_parentalTimer.reset(new CStopWatch);
  m_knownClients.clear();
}

void CPVRManager::Init()
{
  // initial check for enabled addons
  // if at least one pvr addon is enabled, PVRManager start up
  CServiceBroker::GetJobManager()->Submit([this] {
    Clients()->Start();
    return true;
  });
}

void CPVRManager::Start()
{
  std::unique_lock<CCriticalSection> initLock(m_startStopMutex);

  // Prevent concurrent starts
  if (IsInitialising())
    return;

  // Note: Stop() must not be called while holding pvr manager's mutex. Stop() calls
  // StopThread() which can deadlock if the worker thread tries to acquire pvr manager's
  // lock while StopThread() is waiting for the worker to exit. Thus, we introduce another
  // lock here (m_startStopMutex), which only gets hold while starting/restarting pvr manager.
  Stop(true);

  if (!m_addons->HasCreatedClients())
    return;

  CLog::Log(LOGINFO, "PVR Manager: Starting");
  SetState(ManagerState::STATE_STARTING);

  /* create the pvrmanager thread, which will ensure that all data will be loaded */
  Create();
  SetPriority(ThreadPriority::BELOW_NORMAL);
}

void CPVRManager::Stop(bool bRestart /* = false */)
{
  std::unique_lock<CCriticalSection> initLock(m_startStopMutex);

  // Prevent concurrent stops
  if (IsStopped())
    return;

  /* stop playback if needed */
  if (!bRestart && m_playbackState->IsPlaying())
  {
    CLog::LogFC(LOGDEBUG, LOGPVR, "Stopping PVR playback");
    CServiceBroker::GetAppMessenger()->SendMsg(TMSG_MEDIA_STOP);
  }

  CLog::Log(LOGINFO, "PVR Manager: Stopping");
  SetState(ManagerState::STATE_SSTOPPING);

  StopThread();
}

void CPVRManager::Unload()
{
  // stop pvr manager thread and clear all pvr data
  Stop();
  Clear();
}

void CPVRManager::Deinit()
{
  SetWakeupCommand();
  Unload();

  // release addons
  m_addons.reset();
}

CPVRManager::ManagerState CPVRManager::GetState() const
{
  std::unique_lock<CCriticalSection> lock(m_managerStateMutex);
  return m_managerState;
}

void CPVRManager::SetState(CPVRManager::ManagerState state)
{
  {
    std::unique_lock<CCriticalSection> lock(m_managerStateMutex);
    if (m_managerState == state)
      return;

    m_managerState = state;
  }

  PVREvent event;
  switch (state)
  {
    case ManagerState::STATE_ERROR:
      event = PVREvent::ManagerError;
      break;
    case ManagerState::STATE_STOPPED:
      event = PVREvent::ManagerStopped;
      break;
    case ManagerState::STATE_STARTING:
      event = PVREvent::ManagerStarting;
      break;
    case ManagerState::STATE_SSTOPPING:
      event = PVREvent::ManagerStopped;
      break;
    case ManagerState::STATE_INTERRUPTED:
      event = PVREvent::ManagerInterrupted;
      break;
    case ManagerState::STATE_STARTED:
      event = PVREvent::ManagerStarted;
      break;
    default:
      return;
  }

  PublishEvent(event);
}

void CPVRManager::PublishEvent(PVREvent event)
{
  m_events.Publish(event);
}

void CPVRManager::Process()
{
  m_addons->Continue();
  m_database->Open();

  if (!IsInitialising())
  {
    CLog::Log(LOGINFO, "PVR Manager: Start aborted");
    return;
  }

  UnloadComponents();

  if (!IsInitialising())
  {
    CLog::Log(LOGINFO, "PVR Manager: Start aborted");
    return;
  }

  // Wait for at least one client to come up and load/update data
  UpdateComponents(ManagerState::STATE_STARTING);

  if (!IsInitialising())
  {
    CLog::Log(LOGINFO, "PVR Manager: Start aborted");
    return;
  }

  // Load EPGs from database.
  m_epgContainer.Load();

  // Reinit playbackstate
  m_playbackState->ReInit();

  m_guiInfo->Start();
  m_epgContainer.Start();
  m_timers->Start();
  m_pendingUpdates->Start();

  SetState(ManagerState::STATE_STARTED);
  CLog::Log(LOGINFO, "PVR Manager: Started");

  bool bRestart(false);
  XbmcThreads::EndTime<> cachedImagesCleanupTimeout(30s); // first timeout after 30 secs

  while (IsStarted() && m_addons->HasCreatedClients() && !bRestart)
  {
    // In case any new client connected, load from db and fetch data update from new client(s)
    UpdateComponents(ManagerState::STATE_STARTED);

    if (cachedImagesCleanupTimeout.IsTimePast())
    {
      // We don't know for sure what to delete if there are not (yet) connected clients
      if (m_addons->HasIgnoredClients())
      {
        cachedImagesCleanupTimeout.Set(10s); // try again in 10 secs
      }
      else
      {
        // start a job to erase stale texture db entries and image files
        TriggerCleanupCachedImages();
        cachedImagesCleanupTimeout.Set(12h); // following timeouts after 12 hours
      }
    }

    /* first startup */
    if (m_bFirstStart)
    {
      {
        std::unique_lock<CCriticalSection> lock(m_critSection);
        m_bFirstStart = false;
      }

      /* start job to search for missing channel icons */
      TriggerSearchMissingChannelIcons();

      /* try to play channel on startup */
      TriggerPlayChannelOnStartup();
    }

    if (m_addons->AnyClientSupportingRecordingsSize())
      TriggerRecordingsSizeInProgressUpdate();

    /* execute the next pending jobs if there are any */
    try
    {
      m_pendingUpdates->ExecutePendingJobs();
    }
    catch (...)
    {
      CLog::LogF(
          LOGERROR,
          "An error occurred while trying to execute the last PVR update job, trying to recover");
      bRestart = true;
    }

    if (IsStarted() && !bRestart)
      m_pendingUpdates->WaitForJobs(1000);
  }

  m_addons->Stop();
  m_pendingUpdates->Stop();
  m_timers->Stop();
  m_epgContainer.Stop();
  m_guiInfo->Stop();

  SetState(ManagerState::STATE_INTERRUPTED);

  UnloadComponents();
  m_database->Close();

  ResetProperties();

  CLog::Log(LOGINFO, "PVR Manager: Stopped");
  SetState(ManagerState::STATE_STOPPED);
}

bool CPVRManager::SetWakeupCommand()
{
#if !defined(TARGET_DARWIN_EMBEDDED) && !defined(TARGET_WINDOWS_STORE)
  if (!m_settings.GetBoolValue(CSettings::SETTING_PVRPOWERMANAGEMENT_ENABLED))
    return false;

  const std::string strWakeupCommand(
      m_settings.GetStringValue(CSettings::SETTING_PVRPOWERMANAGEMENT_SETWAKEUPCMD));
  if (!strWakeupCommand.empty() && m_timers)
  {
    const CDateTime nextEvent = m_timers->GetNextEventTime();
    if (nextEvent.IsValid())
    {
      time_t iWakeupTime;
      nextEvent.GetAsTime(iWakeupTime);

      std::string strExecCommand = StringUtils::Format("{} {}", strWakeupCommand, iWakeupTime);

      const int iReturn = system(strExecCommand.c_str());
      if (iReturn != 0)
        CLog::LogF(LOGERROR, "PVR Manager failed to execute wakeup command '{}': {} ({})",
                   strExecCommand, strerror(iReturn), iReturn);

      return iReturn == 0;
    }
  }
#endif
  return false;
}

void CPVRManager::OnSleep()
{
  PublishEvent(PVREvent::SystemSleep);

  SetWakeupCommand();

  m_epgContainer.OnSystemSleep();

  m_addons->OnSystemSleep();
}

void CPVRManager::OnWake()
{
  m_addons->OnSystemWake();

  m_epgContainer.OnSystemWake();

  PublishEvent(PVREvent::SystemWake);

  /* start job to search for missing channel icons */
  TriggerSearchMissingChannelIcons();

  /* try to play channel on startup */
  TriggerPlayChannelOnStartup();

  /* trigger PVR data updates */
  TriggerChannelGroupsUpdate();
  TriggerProvidersUpdate();
  TriggerChannelsUpdate();
  TriggerRecordingsUpdate();
  TriggerEpgsCreate();
  TriggerTimersUpdate();
}

void CPVRManager::UpdateComponents(ManagerState stateToCheck)
{
  XbmcThreads::EndTime<> progressTimeout(30s);
  std::unique_ptr<CPVRGUIProgressHandler> progressHandler(
      new CPVRGUIProgressHandler(g_localizeStrings.Get(19235))); // PVR manager is starting up

  // Wait for at least one client to come up and load/update data
  while (!UpdateComponents(stateToCheck, progressHandler) && m_addons->HasCreatedClients() &&
         (stateToCheck == GetState()))
  {
    CThread::Sleep(1000ms);

    if (progressTimeout.IsTimePast())
      progressHandler.reset();
  }
}

bool CPVRManager::UpdateComponents(ManagerState stateToCheck,
                                   const std::unique_ptr<CPVRGUIProgressHandler>& progressHandler)
{
  // find clients which appeared since last check and update them
  const CPVRClientMap clientMap = m_addons->GetCreatedClients();
  if (clientMap.empty())
  {
    CLog::LogFC(LOGDEBUG, LOGPVR, "All created PVR clients gone!");
    m_knownClients.clear(); // start over
    PublishEvent(PVREvent::ClientsInvalidated);
    return false;
  }

  std::vector<std::shared_ptr<CPVRClient>> newClients;
  for (const auto& entry : clientMap)
  {
    // skip not (yet) connected clients
    if (entry.second->IgnoreClient())
    {
      CLog::LogFC(LOGDEBUG, LOGPVR, "Skipping not (yet) connected PVR client '{}'",
                  entry.second->ID());
      continue;
    }

    if (!IsKnownClient(entry.first))
    {
      m_knownClients.emplace_back(entry.second);
      newClients.emplace_back(entry.second);

      CLog::LogFC(LOGDEBUG, LOGPVR, "Adding new PVR client '{}' to list of known clients",
                  entry.second->ID());
    }
  }

  if (newClients.empty())
    return !m_knownClients.empty();

  // Load all channels and groups
  if (progressHandler)
    progressHandler->UpdateProgress(g_localizeStrings.Get(19236), 0); // Loading channels and groups

  if (!m_providers->Update(newClients) || (stateToCheck != GetState()))
  {
    CLog::LogF(LOGERROR, "Failed to load PVR providers.");
    m_knownClients.clear(); // start over
    PublishEvent(PVREvent::ClientsInvalidated);
    return false;
  }

  if (!m_channelGroups->Update(newClients) || (stateToCheck != GetState()))
  {
    CLog::LogF(LOGERROR, "Failed to load PVR channels / groups.");
    m_knownClients.clear(); // start over
    PublishEvent(PVREvent::ClientsInvalidated);
    return false;
  }

  // Load all timers
  if (progressHandler)
    progressHandler->UpdateProgress(g_localizeStrings.Get(19237), 50); // Loading timers

  if (!m_timers->Update(newClients) || (stateToCheck != GetState()))
  {
    CLog::LogF(LOGERROR, "Failed to load PVR timers.");
    m_knownClients.clear(); // start over
    PublishEvent(PVREvent::ClientsInvalidated);
    return false;
  }

  // Load all recordings
  if (progressHandler)
    progressHandler->UpdateProgress(g_localizeStrings.Get(19238), 75); // Loading recordings

  if (!m_recordings->Update(newClients) || (stateToCheck != GetState()))
  {
    CLog::LogF(LOGERROR, "Failed to load PVR recordings.");
    m_knownClients.clear(); // start over
    PublishEvent(PVREvent::ClientsInvalidated);
    return false;
  }

  // reinit playbackstate as new client may provide new last opened group / last played channel
  m_playbackState->ReInit();

  PublishEvent(PVREvent::ClientsInvalidated);
  return true;
}

void CPVRManager::UnloadComponents()
{
  m_recordings->Unload();
  m_timers->Unload();
  m_channelGroups->Unload();
  m_providers->Unload();
  m_epgContainer.Unload();
}

bool CPVRManager::IsKnownClient(int clientID) const
{
  return std::any_of(m_knownClients.cbegin(), m_knownClients.cend(),
                     [clientID](const auto& client) { return client->GetID() == clientID; });
}

void CPVRManager::TriggerPlayChannelOnStartup()
{
  if (IsStarted())
  {
    CServiceBroker::GetJobManager()->Submit(
        [this] { return Get<PVR::GUI::Playback>().PlayChannelOnStartup(); });
  }
}

void CPVRManager::RestartParentalTimer()
{
  if (m_parentalTimer)
    m_parentalTimer->StartZero();
}

bool CPVRManager::IsParentalLocked(const std::shared_ptr<CPVREpgInfoTag>& epgTag) const
{
  return m_channelGroups && epgTag &&
         IsCurrentlyParentalLocked(
             m_channelGroups->GetByUniqueID(epgTag->UniqueChannelID(), epgTag->ClientID()),
             epgTag->IsParentalLocked());
}

bool CPVRManager::IsParentalLocked(const std::shared_ptr<CPVRChannel>& channel) const
{
  return channel && IsCurrentlyParentalLocked(channel, channel->IsLocked());
}

bool CPVRManager::IsCurrentlyParentalLocked(const std::shared_ptr<CPVRChannel>& channel,
                                            bool bGenerallyLocked) const
{
  bool bReturn = false;

  if (!channel || !bGenerallyLocked)
    return bReturn;

  const std::shared_ptr<CPVRChannel> currentChannel = m_playbackState->GetPlayingChannel();

  if ( // if channel in question is currently playing it must be currently unlocked.
      (!currentChannel || channel != currentChannel) &&
      // parental control enabled
      m_settings.GetBoolValue(CSettings::SETTING_PVRPARENTAL_ENABLED))
  {
    float parentalDurationMs =
        m_settings.GetIntValue(CSettings::SETTING_PVRPARENTAL_DURATION) * 1000.0f;
    bReturn = m_parentalTimer && (!m_parentalTimer->IsRunning() ||
                                  m_parentalTimer->GetElapsedMilliseconds() > parentalDurationMs);
  }

  return bReturn;
}

void CPVRManager::OnPlaybackStarted(const CFileItem& item)
{
  m_playbackState->OnPlaybackStarted(item);
  Get<PVR::GUI::Channels>().OnPlaybackStarted(item);
  m_epgContainer.OnPlaybackStarted();
}

void CPVRManager::OnPlaybackStopped(const CFileItem& item)
{
  // Playback ended due to user interaction
  if (m_playbackState->OnPlaybackStopped(item))
    PublishEvent(PVREvent::ChannelPlaybackStopped);

  Get<PVR::GUI::Channels>().OnPlaybackStopped(item);
  m_epgContainer.OnPlaybackStopped();
}

void CPVRManager::OnPlaybackEnded(const CFileItem& item)
{
  // Playback ended, but not due to user interaction
  OnPlaybackStopped(item);
}

void CPVRManager::LocalizationChanged()
{
  std::unique_lock<CCriticalSection> lock(m_critSection);
  if (IsStarted())
  {
    static_cast<CPVRChannelGroupInternal*>(m_channelGroups->GetGroupAllRadio().get())
        ->CheckGroupName();
    static_cast<CPVRChannelGroupInternal*>(m_channelGroups->GetGroupAllTV().get())
        ->CheckGroupName();
  }
}

bool CPVRManager::EpgsCreated() const
{
  std::unique_lock<CCriticalSection> lock(m_critSection);
  return m_bEpgsCreated;
}

void CPVRManager::TriggerEpgsCreate()
{
  m_pendingUpdates->Append("pvr-create-epgs", [this]() { return CreateChannelEpgs(); });
}

void CPVRManager::TriggerRecordingsSizeInProgressUpdate()
{
  m_pendingUpdates->Append("pvr-update-recordings-size",
                           [this]() { return Recordings()->UpdateInProgressSize(); });
}

void CPVRManager::TriggerRecordingsUpdate(int clientId)
{
  m_pendingUpdates->Append("pvr-update-recordings-" + std::to_string(clientId), [this, clientId]() {
    if (!IsKnownClient(clientId))
      return;

    const std::shared_ptr<CPVRClient> client = GetClient(clientId);
    if (client)
      Recordings()->UpdateFromClients({client});
  });
}

void CPVRManager::TriggerRecordingsUpdate()
{
  m_pendingUpdates->Append("pvr-update-recordings",
                           [this]() { Recordings()->UpdateFromClients({}); });
}

void CPVRManager::TriggerTimersUpdate(int clientId)
{
  m_pendingUpdates->Append("pvr-update-timers-" + std::to_string(clientId), [this, clientId]() {
    if (!IsKnownClient(clientId))
      return;

    const std::shared_ptr<CPVRClient> client = GetClient(clientId);
    if (client)
      Timers()->UpdateFromClients({client});
  });
}

void CPVRManager::TriggerTimersUpdate()
{
  m_pendingUpdates->Append("pvr-update-timers", [this]() { Timers()->UpdateFromClients({}); });
}

void CPVRManager::TriggerProvidersUpdate(int clientId)
{
  m_pendingUpdates->Append("pvr-update-channel-providers-" + std::to_string(clientId),
                           [this, clientId]() {
                             if (!IsKnownClient(clientId))
                               return;

                             const std::shared_ptr<CPVRClient> client = GetClient(clientId);
                             if (client)
                               Providers()->UpdateFromClients({client});
                           });
}

void CPVRManager::TriggerProvidersUpdate()
{
  m_pendingUpdates->Append("pvr-update-channel-providers",
                           [this]() { Providers()->UpdateFromClients({}); });
}

void CPVRManager::TriggerChannelsUpdate(int clientId)
{
  m_pendingUpdates->Append("pvr-update-channels-" + std::to_string(clientId), [this, clientId]() {
    if (!IsKnownClient(clientId))
      return;

    const std::shared_ptr<CPVRClient> client = GetClient(clientId);
    if (client)
      ChannelGroups()->UpdateFromClients({client}, true);
  });
}

void CPVRManager::TriggerChannelsUpdate()
{
  m_pendingUpdates->Append("pvr-update-channels",
                           [this]() { ChannelGroups()->UpdateFromClients({}, true); });
}

void CPVRManager::TriggerChannelGroupsUpdate(int clientId)
{
  m_pendingUpdates->Append("pvr-update-channelgroups-" + std::to_string(clientId),
                           [this, clientId]() {
                             if (!IsKnownClient(clientId))
                               return;

                             const std::shared_ptr<CPVRClient> client = GetClient(clientId);
                             if (client)
                               ChannelGroups()->UpdateFromClients({client}, false);
                           });
}

void CPVRManager::TriggerChannelGroupsUpdate()
{
  m_pendingUpdates->Append("pvr-update-channelgroups",
                           [this]() { ChannelGroups()->UpdateFromClients({}, false); });
}

void CPVRManager::TriggerSearchMissingChannelIcons()
{
  m_pendingUpdates->Append("pvr-search-missing-channel-icons", [this]() {
    CPVRGUIChannelIconUpdater updater(
        {ChannelGroups()->GetGroupAllTV(), ChannelGroups()->GetGroupAllRadio()}, true);
    updater.SearchAndUpdateMissingChannelIcons();
    return true;
  });
}

void CPVRManager::TriggerSearchMissingChannelIcons(const std::shared_ptr<CPVRChannelGroup>& group)
{
  m_pendingUpdates->Append("pvr-search-missing-channel-icons-" + std::to_string(group->GroupID()),
                           [group]() {
                             CPVRGUIChannelIconUpdater updater({group}, false);
                             updater.SearchAndUpdateMissingChannelIcons();
                             return true;
                           });
}

void CPVRManager::TriggerCleanupCachedImages()
{
  m_pendingUpdates->Append("pvr-cleanup-cached-images", [this]() {
    int iCleanedImages = 0;
    CLog::Log(LOGINFO, "PVR Manager: Starting cleanup of cached images.");
    iCleanedImages += Recordings()->CleanupCachedImages();
    iCleanedImages += ChannelGroups()->CleanupCachedImages();
    iCleanedImages += Providers()->CleanupCachedImages();
    iCleanedImages += EpgContainer().CleanupCachedImages();
    CLog::Log(LOGINFO, "PVR Manager: Cleaned up {} cached images.", iCleanedImages);
    return true;
  });
}

void CPVRManager::ConnectionStateChange(CPVRClient* client,
                                        const std::string& connectString,
                                        PVR_CONNECTION_STATE state,
                                        const std::string& message)
{
  CServiceBroker::GetJobManager()->Submit([this, client, connectString, state, message] {
    Clients()->ConnectionStateChange(client, connectString, state, message);
    return true;
  });
}

bool CPVRManager::CreateChannelEpgs()
{
  if (EpgsCreated())
    return true;

  bool bEpgsCreated = m_channelGroups->CreateChannelEpgs();

  std::unique_lock<CCriticalSection> lock(m_critSection);
  m_bEpgsCreated = bEpgsCreated;
  return m_bEpgsCreated;
}