public inbox for git-commits@fedoraproject.org
help / color / mirror / Atom feed
From: Martin Gansser <mgansser@netcom-mail.de>
To: git-commits@fedoraproject.org
Subject: [rpms/vdr] rawhide: Add 16-numtracks-lock (for upstream), found with ThreadSanitizer and the
Date: Thu, 29 Oct 2026 09:49:40 GMT	[thread overview]
Message-ID: <179326738028.1.15507406684894207493.rpms-vdr-039db5a79bea@fedoraproject.org> (raw)

          A new commit has been pushed.

          Repo   : rpms/vdr
          Branch : rawhide
          Commit : 039db5a79bea3147c3845b100c1fc767c1127a6c
          Author : Martin Gansser <mgansser@netcom-mail.de>
          Date   : 2026-10-29T10:49:07+01:00
          Stats  : +2054/-2124 in 54 file(s)
          URL    : https://src.fedoraproject.org/rpms/vdr/c/039db5a79bea3147c3845b100c1fc767c1127a6c?branch=rawhide

          Log:
          Add 16-numtracks-lock (for upstream), found with ThreadSanitizer and the

dvd plugin: count the available tracks under mutexCurrentAudioTrack,
under which a player announces them

---
diff --git a/.gitignore b/.gitignore
index b2a8052..d6a889a 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,3 +1,4 @@
 -/*.gz
 -/*.bz2
 /vdr-2.8.3.tar.bz2
+/vdr-2.8.4.tar.bz2

diff --git a/sources b/sources
index 43f2abd..62022ae 100644
--- a/sources
+++ b/sources
@@ -1 +1 @@
-SHA512 (vdr-2.8.3.tar.bz2) = 7cb5c9d65b81fc82a72758bf24484f471269e9337d72b2e7438471e2108b11f871e99e9d9194cef1edebc272c9e26d6c15d287162d36ccefa60588442cf5abbe
+SHA512 (vdr-2.8.4.tar.bz2) = 2bc1c213e5a45c5a332ca8d3f12afd20cb263e1e62ce3e593e39ea45fd3218c665d96253185836ab5ab3890d0420535e01bf0c772fc81aa5049167656c731881

diff --git a/vdr-01-eitscan-activity-before-control.patch b/vdr-01-eitscan-activity-before-control.patch
new file mode 100644
index 0000000..b2a1672
--- /dev/null
+++ b/vdr-01-eitscan-activity-before-control.patch
@@ -0,0 +1,42 @@
+From: Dirk Nehring <dnehring@gmx.net>
+Subject: [PATCH] vdr: end the EPG scan before the control gets the key
+
+After EPGScanTimeout hours without a key the EIT scanner takes the
+primary device and remembers the live channel. A replay started without
+a key press (SVDRP PLAY, a plugin's SVDRP command, the live plugin)
+leaves that pending. The next real key made the main loop fetch the
+control first and call EITScanner.Activity() after it, which switches
+back to the live channel: cDevice::SwitchChannel() calls
+cControl::Shutdown(), which deletes the control, and the key was then
+passed to the deleted object (SIGSEGV in Interact->ProcessKey()).
+Activity() now runs before the control is fetched, so the key goes to
+live viewing.
+---
+--- a/vdr.c
++++ b/vdr.c
+@@ -1278,19 +1278,19 @@ int main(int argc, char *argv[])
+            NeedsFastResponse = Control && Control->NeedsFastResponse();
+            }
+         eKeys key = Interface->GetKey(!NeedsFastResponse);
+-        cOsdObject *Interact = Menu;
+-        cMutexLock ControlMutexLock;
+-        cControl *Control = NULL;
+-        if (!Menu)
+-           Interact = Control = cControl::Control(ControlMutexLock);
+         if (ISREALKEY(key)) {
+-           EITScanner.Activity();
++           EITScanner.Activity(); // may switch back to the live channel and thus delete the control, so this must be done before the control is fetched
+            // Cancel shutdown countdown:
+            if (ShutdownHandler.countdown)
+               ShutdownHandler.countdown.Cancel();
+            // Set user active for MinUserInactivity time in the future:
+            ShutdownHandler.SetUserInactiveTimeout();
+            }
++        cOsdObject *Interact = Menu;
++        cMutexLock ControlMutexLock;
++        cControl *Control = NULL;
++        if (!Menu)
++           Interact = Control = cControl::Control(ControlMutexLock);
+         // Keys that must work independent of any interactive mode:
+         switch (int(key)) {
+           // Menu control:

diff --git a/vdr-01-thread-atomics.patch b/vdr-01-thread-atomics.patch
deleted file mode 100644
index b60fbca..0000000
--- a/vdr-01-thread-atomics.patch
+++ /dev/null
@@ -1,147 +0,0 @@
-From: Dirk Nehring <dnehring@gmx.net>
-Subject: [PATCH] thread, ringbuffer: make the fields read without a lock atomic
-
-cMutex::Lock() and cRwLock::Lock() read the holder's thread id before
-they own the lock. cThread's active/running/childThreadId are written by
-the thread itself and read by Start()/Active()/Cancel() in other threads.
-cIoThrottle::Engaged() reads 'count' without the mutex, and the writing
-thread logs cRingBuffer::getThreadTid, which the reading thread sets.
-std::atomic makes these accesses defined; ThreadSanitizer no longer
-reports them.
-
----
---- a/ringbuffer.c
-+++ b/ringbuffer.c
-@@ -50,7 +50,7 @@ void cRingBuffer::UpdatePercentage(int Fill)
-   int percent = Fill * 100 / (Size() - 1) / PERCENTAGEDELTA * PERCENTAGEDELTA; // clamp down to nearest quantum
-   if (percent != lastPercent) {
-      if (percent >= PERCENTAGETHRESHOLD && percent > lastPercent || percent < PERCENTAGETHRESHOLD && lastPercent >= PERCENTAGETHRESHOLD) {
--        dsyslog("buffer usage: %d%% (tid=%d)", percent, getThreadTid);
-+        dsyslog("buffer usage: %d%% (tid=%d)", percent, getThreadTid.load());
-         lastPercent = percent;
-         }
-      }
---- a/ringbuffer.h
-+++ b/ringbuffer.h
-@@ -25,7 +25,7 @@ private:
-   int overflowBytes;
-   cIoThrottle *ioThrottle;
- protected:
--  tThreadId getThreadTid;
-+  std::atomic<tThreadId> getThreadTid; // set by the reading thread, logged by the writing one
-   int maxFill;//XXX
-   int lastPercent;
-   bool statistics;//XXX
---- a/thread.c
-+++ b/thread.c
-@@ -306,10 +306,10 @@ void *cThread::StartThread(cThread *Thread)
- {
-   Thread->childThreadId = ThreadId();
-   if (Thread->description) {
--     dsyslog("%s thread started (pid=%d, tid=%d, prio=%s)", Thread->description, getpid(), Thread->childThreadId, Thread->lowPriority ? "low" : "high");
-+     dsyslog("%s thread started (pid=%d, tid=%d, prio=%s)", Thread->description, getpid(), Thread->childThreadId.load(), Thread->lowPriority ? "low" : "high");
- #ifdef PR_SET_NAME
-      if (prctl(PR_SET_NAME, Thread->description, 0, 0, 0) < 0)
--        esyslog("%s thread naming failed (pid=%d, tid=%d)", Thread->description, getpid(), Thread->childThreadId);
-+        esyslog("%s thread naming failed (pid=%d, tid=%d)", Thread->description, getpid(), Thread->childThreadId.load());
- #endif
-      }
-   if (Thread->lowPriority) {
-@@ -318,7 +318,7 @@ void *cThread::StartThread(cThread *Thread)
-      }
-   Thread->Action();
-   if (Thread->description)
--     dsyslog("%s thread ended (pid=%d, tid=%d)", Thread->description, getpid(), Thread->childThreadId);
-+     dsyslog("%s thread ended (pid=%d, tid=%d)", Thread->description, getpid(), Thread->childThreadId.load());
-   Thread->running = false;
-   Thread->active = false;
-   return NULL;
-@@ -388,7 +388,7 @@ void cThread::Cancel(int WaitSeconds)
-                  return;
-               cCondWait::SleepMs(10);
-               }
--        esyslog("ERROR: %s thread %d won't end (waited %d seconds) - canceling it...", description ? description : "", childThreadId, WaitSeconds);
-+        esyslog("ERROR: %s thread %d won't end (waited %d seconds) - canceling it...", description ? description : "", childThreadId.load(), WaitSeconds);
-         }
-      pthread_cancel(childTid);
-      childTid = 0;
-@@ -926,7 +926,7 @@ bool cStateKey::StateChanged(void)
- // --- cIoThrottle -----------------------------------------------------------
- 
- cMutex cIoThrottle::mutex;
--int cIoThrottle::count = 0;
-+std::atomic<int> cIoThrottle::count(0);
- 
- cIoThrottle::cIoThrottle(void)
- {
-@@ -944,7 +944,7 @@ void cIoThrottle::Activate(void)
-   if (!active) {
-      count++;
-      active = true;
--     dsyslog("i/o throttle activated, count = %d (tid=%d)", count, cThread::ThreadId());
-+     dsyslog("i/o throttle activated, count = %d (tid=%d)", count.load(), cThread::ThreadId());
-      }
-   mutex.Unlock();
- }
-@@ -955,7 +955,7 @@ void cIoThrottle::Release(void)
-   if (active) {
-      count--;
-      active = false;
--     dsyslog("i/o throttle released, count = %d (tid=%d)", count, cThread::ThreadId());
-+     dsyslog("i/o throttle released, count = %d (tid=%d)", count.load(), cThread::ThreadId());
-      }
-   mutex.Unlock();
- }
---- a/thread.h
-+++ b/thread.h
-@@ -10,6 +10,7 @@
- #ifndef __THREAD_H
- #define __THREAD_H
- 
-+#include <atomic>
- #include <pthread.h>
- #include <stdio.h>
- #include <sys/types.h>
-@@ -56,7 +57,7 @@ class cRwLock {
- private:
-   pthread_rwlock_t rwlock;
-   int locked;
--  tThreadId writeLockThreadId;
-+  std::atomic<tThreadId> writeLockThreadId; // Lock() reads it without holding the lock
- public:
-   cRwLock(bool PreferWriter = false);
-   ~cRwLock();
-@@ -68,7 +69,7 @@ class cMutex {
-   friend class cCondVar;
- private:
-   pthread_mutex_t mutex;
--  tThreadId lockThreadId; // current holder, 0 == unlocked; lets Lock() short-circuit recursive entry
-+  std::atomic<tThreadId> lockThreadId; // current holder, 0 == unlocked; lets Lock() short-circuit recursive entry (read without holding the mutex)
-   int locked;
- public:
-   cMutex(void);
-@@ -85,10 +86,12 @@ public:
- class cThread {
-   friend class cThreadLock;
- private:
--  bool active;
--  bool running;
-+  // Shared by the thread and those that start, poll or cancel it; whoever
-+  // sees 'active' false must also see everything Action() did:
-+  std::atomic<bool> active;
-+  std::atomic<bool> running;
-   pthread_t childTid;
--  tThreadId childThreadId;
-+  std::atomic<tThreadId> childThreadId; // set by the thread itself, logged by Cancel()
-   cMutex mutex;
-   char *description;
-   bool lowPriority;
-@@ -278,7 +281,7 @@ public:
- class cIoThrottle {
- private:
-   static cMutex mutex;
--  static int count;
-+  static std::atomic<int> count; // Engaged() reads it without the mutex
-   bool active;
- public:
-   cIoThrottle(void);

diff --git a/vdr-02-device-track-atomics.patch b/vdr-02-device-track-atomics.patch
deleted file mode 100644
index 7ac2750..0000000
--- a/vdr-02-device-track-atomics.patch
+++ /dev/null
@@ -1,53 +0,0 @@
-From: Dirk Nehring <dnehring@gmx.net>
-Subject: [PATCH] device: make the current channel and track numbers atomic
-
-PlayTs() routes packets by currentAudioTrack/currentSubtitleTrack, and
-the skins read them through the getters, without a lock while other
-threads change them (user selection, PMT updates, channel switches).
-currentChannel is set by whichever thread switches the channel (e.g.
-SVDRP CHAN) and read everywhere through CurrentChannel().
-
----
---- a/device.c
-+++ b/device.c
-@@ -72,7 +72,7 @@ bool cDeviceHook::DeviceProvidesEIT(const cDevice *Device) const
- int cDevice::numDevices = 0;
- int cDevice::useDevice = 0;
- int cDevice::nextCardIndex = 0;
--int cDevice::currentChannel = 1;
-+std::atomic<int> cDevice::currentChannel(1);
- cDevice *cDevice::device[MAXDEVICES] = { NULL };
- cDevice *cDevice::primaryDevice = NULL;
- cList<cDeviceHook> cDevice::deviceHooks;
---- a/device.h
-+++ b/device.h
-@@ -266,7 +266,7 @@ private:
-   time_t occupiedTimeout;
-   int occupiedPriority;
- protected:
--  static int currentChannel;
-+  static std::atomic<int> currentChannel; // set by whichever thread switches the channel, read by any
- public:
-   virtual bool ProvidesSource(int Source) const;
-          ///< Returns true if this device can provide the given source.
-@@ -368,7 +368,7 @@ protected:
-   virtual bool SetChannelDevice(const cChannel *Channel, bool LiveView);
-          ///< Sets the device to the given channel (actual physical setup).
- public:
--  static int CurrentChannel(void) { return primaryDevice ? currentChannel : 0; }
-+  static int CurrentChannel(void) { return primaryDevice ? currentChannel.load() : 0; }
-          ///< Returns the number of the current channel on the primary device.
-   static void SetCurrentChannel(int ChannelNumber) { currentChannel = ChannelNumber; }
-          ///< Sets the number of the current channel on the primary device, without
-@@ -552,8 +552,9 @@ public:
- 
- private:
-   tTrackId availableTracks[ttMaxTrackTypes];
--  eTrackType currentAudioTrack;
--  eTrackType currentSubtitleTrack;
-+  // read without a lock by PlayTs() and the getters, while other threads change them:
-+  std::atomic<eTrackType> currentAudioTrack;
-+  std::atomic<eTrackType> currentSubtitleTrack;
-   cMutex mutexCurrentAudioTrack;
-   cMutex mutexCurrentSubtitleTrack;
-   int currentAudioTrackMissingCount;

diff --git a/vdr-02-osd-delete-before-destructor.patch b/vdr-02-osd-delete-before-destructor.patch
new file mode 100644
index 0000000..45cf823
--- /dev/null
+++ b/vdr-02-osd-delete-before-destructor.patch
@@ -0,0 +1,156 @@
+From: Dirk Nehring <dnehring@gmx.net>
+Subject: [PATCH] osd: take an OSD off the list before its destructor runs
+
+The subtitle converter and the SPU decoder delete their OSDs in their own
+threads, the skins in the main thread. ~cOsd() removed an OSD from the
+list only after the derived destructor had run, and then called
+SetActive(true) on Osds[0] in any case. So when the subtitle thread
+deleted its OSD while the main thread was destroying a menu, it called
+the output plugin's SetActive() on the half-destroyed menu OSD.
+
+cOsd::Delete() takes the OSD off the list first and activates the next
+one after the deletion, as before. ~cOsd() activates Osds[0] only if the
+deleted OSD was the active one, the only case in which it changes.
+---
+--- a/dvbspu.c
++++ b/dvbspu.c
+@@ -245,7 +245,7 @@ cDvbSpuDecoder::~cDvbSpuDecoder()
+ {
+     delete spubmp;
+     delete[] spu;
+-    delete osd;
++    cOsd::Delete(osd);
+ }
+ 
+ // SPUs must be scaled if screensize is not 720x576
+@@ -538,8 +538,7 @@ void cDvbSpuDecoder::Draw(void)
+ void cDvbSpuDecoder::Hide(void)
+ {
+     cMutexLock MutexLock(&mutex);
+-    delete osd;
+-    osd = NULL;
++    cOsd::Delete(osd);
+ }
+ 
+ void cDvbSpuDecoder::Empty(void)
+--- a/dvbsubtitle.c
++++ b/dvbsubtitle.c
+@@ -1385,7 +1385,7 @@ cDvbSubtitleConverter::~cDvbSubtitleConverter()
+ {
+   Cancel(3);
+   delete dvbSubtitleAssembler;
+-  delete osd;
++  cOsd::Delete(osd);
+   delete bitmaps;
+   delete pages;
+ }
+@@ -1395,7 +1395,7 @@ void cDvbSubtitleConverter::SetVisible(bool Visible)
+   LOCK_THREAD;
+   visible = Visible;
+   if (!visible)
+-     DELETENULL(osd);
++     cOsd::Delete(osd);
+   endVisible = -1;
+ }
+ 
+@@ -1420,7 +1420,7 @@ void cDvbSubtitleConverter::Reset(void)
+   Lock();
+   pages->Clear();
+   current = NULL;
+-  DELETENULL(osd);
++  cOsd::Delete(osd);
+   frozen = false;
+   ddsVersionNumber = -1;
+   Unlock();
+@@ -1528,13 +1528,13 @@ void cDvbSubtitleConverter::Action(void)
+               int NewSetupLevel = setupLevel;
+               if (LastSetupLevel != NewSetupLevel) {
+                  dbgoutput("closing osd<br>\n");
+-                 DELETENULL(osd);
++                 cOsd::Delete(osd);
+                  }
+               LastSetupLevel = NewSetupLevel;
+               }
+            int64_t STC = cDevice::PrimaryDevice()->GetSTC();
+            if (osd && current && current->Timeout() * 1000 - PtsDeltaMs(STC, current->Pts()) <= 0)
+-              DELETENULL(osd);
++              cOsd::Delete(osd);
+            for (cDvbSubtitleBitmaps *sb = bitmaps->First(); sb; ) {
+                // Calculate the Delta between the STC (the current timestamp of the video)
+                // and the bitmap's PTS (the timestamp when the bitmap shall be presented).
+@@ -1553,10 +1553,10 @@ void cDvbSubtitleConverter::Action(void)
+                      if (endVisible >= 0 && PtsDeltaMs(STC, endVisible) > TEMPSUBTITLETAIL) {
+                         visible = false;
+                         endVisible = -1;
+-                        DELETENULL(osd);
++                        cOsd::Delete(osd);
+                         }
+                      else if (!current->HasBitmaps() || current->Timeout() * 1000 - PtsDeltaMs(STC, current->Pts()) <= 0)
+-                        DELETENULL(osd);
++                        cOsd::Delete(osd);
+                      else if (visible && AssertOsd()) {
+                         dbgoutput("showing bitmap #%d of %d<br>\n", current->Index() + 1, bitmaps->Count());
+                         current->Draw(osd);
+--- a/osd.c
++++ b/osd.c
+@@ -1939,14 +1939,34 @@ cOsd::~cOsd()
+      DestroyPixmap(savedPixmap);
+   for (int i = 0; i < pixmaps.Size(); i++)
+       delete pixmaps[i];
++  if (Deregister() && Osds.Size())
++     Osds[0]->SetActive(true);
++}
++
++bool cOsd::Deregister(void)
++{
++  // Returns true if this was the active OSD. Only Osds[0] is active, and the
++  // others may be in their destructors in other threads, so they are left alone:
++  cMutexLock MutexLock(&mutex);
+   for (int i = 0; i < Osds.Size(); i++) {
+       if (Osds[i] == this) {
+          Osds.Remove(i);
+-         if (Osds.Size())
+-            Osds[0]->SetActive(true);
+-         break;
++         return i == 0;
+          }
+       }
++  return false;
++}
++
++void cOsd::Delete(cOsd *&Osd)
++{
++  if (Osd) {
++     bool Active = Osd->Deregister();
++     delete Osd;
++     Osd = NULL;
++     cMutexLock MutexLock(&mutex);
++     if (Active && Osds.Size())
++        Osds[0]->SetActive(true);
++     }
+ }
+ 
+ void cOsd::SetOsdPosition(int Left, int Top, int Width, int Height)
+--- a/osd.h
++++ b/osd.h
+@@ -769,6 +769,7 @@ private:
+   int left, top, width, height;
+   uint level;
+   bool active;
++  bool Deregister(void);
+ protected:
+   cOsd(int Left, int Top, uint Level);
+        ///< Initializes the OSD with the given coordinates.
+@@ -828,6 +829,12 @@ protected:
+ public:
+   virtual ~cOsd();
+        ///< Shuts down the OSD.
++  static void Delete(cOsd *&Osd);
++       ///< Deletes the given Osd (if any) and sets it to NULL.
++       ///< The OSD is taken off the list of open OSDs before its destructor
++       ///< runs, so that another thread deleting its own OSD meanwhile can't
++       ///< call SetActive() on this one. An OSD that is deleted outside the
++       ///< main thread should be deleted this way.
+   static int OsdLeft(void) { return osdLeft ? osdLeft : Setup.OSDLeft; }
+   static int OsdTop(void) { return osdTop ? osdTop : Setup.OSDTop; }
+   static int OsdWidth(void) { return osdWidth ? osdWidth : Setup.OSDWidth; }

diff --git a/vdr-03-device-player-atomics.patch b/vdr-03-device-player-atomics.patch
deleted file mode 100644
index f9c7300..0000000
--- a/vdr-03-device-player-atomics.patch
+++ /dev/null
@@ -1,140 +0,0 @@
-From: Dirk Nehring <dnehring@gmx.net>
-Subject: [PATCH] device, player: make the player/device pointers atomic
-
-cDevice::AttachPlayer() and Detach() set and clear cDevice::player and
-cPlayer::device from any thread, while the player's threads call the
-Device*() wrappers and other threads call Replaying() and the track
-setters. The readers loaded the pointer twice ('device ? device->X() :
-Y'), so a concurrent Detach() could clear it between check and call;
-each now acts on one snapshot.
-
----
---- a/device.c
-+++ b/device.c
-@@ -1190,8 +1190,8 @@ bool cDevice::SetCurrentAudioTrack(eTrackType Type)
-      if (IS_DOLBY_TRACK(Type))
-         SetDigitalAudioDevice(true);
-      currentAudioTrack = Type;
--     if (player)
--        player->SetAudioTrack(currentAudioTrack, GetTrack(currentAudioTrack));
-+     if (cPlayer *p = player)
-+        p->SetAudioTrack(currentAudioTrack, GetTrack(currentAudioTrack));
-      else
-         SetAudioTrackDevice(currentAudioTrack);
-      if (IS_AUDIO_TRACK(Type))
-@@ -1232,8 +1232,8 @@ bool cDevice::SetCurrentSubtitleTrack(eTrackType Type, bool Manual)
-        liveSubtitle = NULL;
-      }
-      delete ls;
--     if (player)
--        player->SetSubtitleTrack(currentSubtitleTrack, GetTrack(currentSubtitleTrack));
-+     if (cPlayer *p = player)
-+        p->SetSubtitleTrack(currentSubtitleTrack, GetTrack(currentSubtitleTrack));
-      else
-         SetSubtitleTrackDevice(currentSubtitleTrack);
-      if (currentSubtitleTrack != ttNone && !Replaying() && !Transferring()) {
-@@ -1444,9 +1444,9 @@ bool cDevice::AttachPlayer(cPlayer *Player)
-      player = Player;
-      if (!Transferring())
-         ClrAvailableTracks(false, true);
--     SetPlayMode(player->playMode);
--     player->device = this;
--     player->Activate(true);
-+     SetPlayMode(Player->playMode);
-+     Player->device = this;
-+     Player->Activate(true);
-      return true;
-      }
-   return false;
---- a/device.h
-+++ b/device.h
-@@ -651,7 +651,7 @@ public:
- // Player facilities
- 
- private:
--  cPlayer *player;
-+  std::atomic<cPlayer *> player; // cleared by Detach() in any thread, read without a lock
-   cPatPmtParser patPmtParser;
-   cTsToPes tsToPesVideo;
-   cTsToPes tsToPesAudio;
---- a/player.c
-+++ b/player.c
-@@ -25,16 +25,16 @@ cPlayer::~cPlayer()
- 
- int cPlayer::PlayPes(const uchar *Data, int Length, bool VideoOnly)
- {
--  if (device)
--     return device->PlayPes(Data, Length, VideoOnly);
-+  if (cDevice *d = device)
-+     return d->PlayPes(Data, Length, VideoOnly);
-   esyslog("ERROR: attempt to use cPlayer::PlayPes() without attaching to a cDevice!");
-   return -1;
- }
- 
- void cPlayer::Detach(void)
- {
--  if (device)
--     device->Detach(this);
-+  if (cDevice *d = device)
-+     d->Detach(this);
- }
- 
- // --- cControl --------------------------------------------------------------
---- a/player.h
-+++ b/player.h
-@@ -16,28 +16,28 @@
- class cPlayer {
-   friend class cDevice;
- private:
--  cDevice *device;
-+  std::atomic<cDevice *> device; // cleared by cDevice::Detach() while the player's threads use it
-   ePlayMode playMode;
- protected:
--  void DeviceClrAvailableTracks(bool DescriptionsOnly = false) { if (device) device->ClrAvailableTracks(DescriptionsOnly); }
--  bool DeviceSetAvailableTrack(eTrackType Type, int Index, uint16_t Id, const char *Language = NULL, const char *Description = NULL) { return device ? device->SetAvailableTrack(Type, Index, Id, Language, Description) : false; }
--  bool DeviceSetCurrentAudioTrack(eTrackType Type) { return device ? device->SetCurrentAudioTrack(Type) : false; }
--  bool DeviceSetCurrentSubtitleTrack(eTrackType Type) { return device ? device->SetCurrentSubtitleTrack(Type) : false; }
--  bool DevicePoll(cPoller &Poller, int TimeoutMs = 0) { return device ? device->Poll(Poller, TimeoutMs) : false; }
-+  void DeviceClrAvailableTracks(bool DescriptionsOnly = false) { if (cDevice *d = device) d->ClrAvailableTracks(DescriptionsOnly); }
-+  bool DeviceSetAvailableTrack(eTrackType Type, int Index, uint16_t Id, const char *Language = NULL, const char *Description = NULL) { cDevice *d = device; return d ? d->SetAvailableTrack(Type, Index, Id, Language, Description) : false; }
-+  bool DeviceSetCurrentAudioTrack(eTrackType Type) { cDevice *d = device; return d ? d->SetCurrentAudioTrack(Type) : false; }
-+  bool DeviceSetCurrentSubtitleTrack(eTrackType Type) { cDevice *d = device; return d ? d->SetCurrentSubtitleTrack(Type) : false; }
-+  bool DevicePoll(cPoller &Poller, int TimeoutMs = 0) { cDevice *d = device; return d ? d->Poll(Poller, TimeoutMs) : false; }
-   [[deprecated("use DeviceDrain() instead")]]
-   bool DeviceFlush(int TimeoutMs = 0) { return DeviceDrain(); }
--  bool DeviceDrain(void) { return device ? device->Drain() : false; }
--  bool DeviceHasIBPTrickSpeed(void) { return device ? device->HasIBPTrickSpeed() : false; }
--  bool DeviceIsPlayingVideo(void) { return device ? device->IsPlayingVideo() : false; }
--  void DeviceTrickSpeed(int Speed, bool Forward) { if (device) device->TrickSpeed(Speed, Forward); }
--  void DeviceClear(void) { if (device) device->Clear(); }
--  void DevicePlay(void) { if (device) device->Play(); }
--  void DeviceFreeze(void) { if (device) device->Freeze(); }
--  void DeviceMute(void) { if (device) device->Mute(); }
--  void DeviceSetVideoDisplayFormat(eVideoDisplayFormat VideoDisplayFormat) { if (device) device->SetVideoDisplayFormat(VideoDisplayFormat); }
--  void DeviceStillPicture(const uchar *Data, int Length) { if (device) device->StillPicture(Data, Length); }
--  void DeviceSetTempSubtitles(void) { if (device) device->SetTempSubtitles(); }
--  uint64_t DeviceGetSTC(void) { return device ? device->GetSTC() : -1; }
-+  bool DeviceDrain(void) { cDevice *d = device; return d ? d->Drain() : false; }
-+  bool DeviceHasIBPTrickSpeed(void) { cDevice *d = device; return d ? d->HasIBPTrickSpeed() : false; }
-+  bool DeviceIsPlayingVideo(void) { cDevice *d = device; return d ? d->IsPlayingVideo() : false; }
-+  void DeviceTrickSpeed(int Speed, bool Forward) { if (cDevice *d = device) d->TrickSpeed(Speed, Forward); }
-+  void DeviceClear(void) { if (cDevice *d = device) d->Clear(); }
-+  void DevicePlay(void) { if (cDevice *d = device) d->Play(); }
-+  void DeviceFreeze(void) { if (cDevice *d = device) d->Freeze(); }
-+  void DeviceMute(void) { if (cDevice *d = device) d->Mute(); }
-+  void DeviceSetVideoDisplayFormat(eVideoDisplayFormat VideoDisplayFormat) { if (cDevice *d = device) d->SetVideoDisplayFormat(VideoDisplayFormat); }
-+  void DeviceStillPicture(const uchar *Data, int Length) { if (cDevice *d = device) d->StillPicture(Data, Length); }
-+  void DeviceSetTempSubtitles(void) { if (cDevice *d = device) d->SetTempSubtitles(); }
-+  uint64_t DeviceGetSTC(void) { cDevice *d = device; return d ? d->GetSTC() : -1; }
-   void Detach(void);
-   virtual void Activate(bool On) {}
-        // This function is called right after the cPlayer has been attached to
-@@ -47,7 +47,7 @@ protected:
-        // Sends the given PES Data to the device and returns the number of
-        // bytes that have actually been accepted by the device (or a
-        // negative value in case of an error).
--  int PlayTs(const uchar *Data, int Length, bool VideoOnly = false) { return device ? device->PlayTs(Data, Length, VideoOnly) : -1; }
-+  int PlayTs(const uchar *Data, int Length, bool VideoOnly = false) { cDevice *d = device; return d ? d->PlayTs(Data, Length, VideoOnly) : -1; }
-        // Sends the given TS packet to the device and returns a positive number
-        // if the packet has been accepted by the device, or a negative value in
-        // case of an error.

diff --git a/vdr-03-pointer-snapshots.patch b/vdr-03-pointer-snapshots.patch
new file mode 100644
index 0000000..069146d
--- /dev/null
+++ b/vdr-03-pointer-snapshots.patch
@@ -0,0 +1,275 @@
+From: Dirk Nehring <dnehring@gmx.net>
+Subject: [PATCH] device, player, receiver: act on one snapshot of the pointers other threads clear
+
+cDevice::Detach() clears cPlayer::device and cReceiver::device, and
+cDevice::player, in whatever thread detaches, while the player's and
+the receiver's threads keep calling through them. cCamSlot::Assign()
+sets and clears cDevice::camSlot during another thread's channel
+switch in the same way. The readers loaded the pointer twice
+('device ? device->X() : Y', 'CamSlot() && CamSlot()->WantsTsData()'),
+so it could turn NULL between the check and the call. They now act on
+one snapshot, and the pointers are atomic.
+---
+--- a/device.c
++++ b/device.c
+@@ -454,8 +454,10 @@ cDevice *cDevice::GetDeviceForTransponder(const cChannel *Channel, int Priority)
+ 
+ void cDevice::ReleaseCamSlot(void)
+ {
+-  if (camSlot && !camSlot->IsDecrypting() && !camSlot->IsActivating())
+-     camSlot->Assign(NULL);
++  if (cCamSlot *cs = camSlot) {
++     if (!cs->IsDecrypting() && !cs->IsActivating())
++        cs->Assign(NULL);
++     }
+ }
+ 
+ bool cDevice::HasCi(void)
+@@ -924,7 +926,8 @@ eSetChannelResult cDevice::SetChannel(const cChannel *Channel, bool LiveView)
+ 
+   bool NeedsTransferMode = LiveView && Device != PrimaryDevice();
+   // If the CAM slot wants the TS data, we need to switch to Transfer Mode:
+-  if (!NeedsTransferMode && LiveView && IsPrimaryDevice() && CamSlot() && CamSlot()->WantsTsData())
++  cCamSlot *PrimaryCamSlot = CamSlot();
++  if (!NeedsTransferMode && LiveView && IsPrimaryDevice() && PrimaryCamSlot && PrimaryCamSlot->WantsTsData())
+      NeedsTransferMode = true;
+ 
+   eSetChannelResult Result = scrOk;
+@@ -948,8 +951,8 @@ eSetChannelResult cDevice::SetChannel(const cChannel *Channel, bool LiveView)
+         }
+      // Tell the camSlot about the channel switch and add all PIDs of this
+      // channel to it, for possible later decryption:
+-     if (camSlot)
+-        camSlot->AddChannel(Channel);
++     if (cCamSlot *cs = camSlot)
++        cs->AddChannel(Channel);
+      SetPowerSaveMode(false);
+      if (SetChannelDevice(Channel, LiveView)) {
+         // Start section handling:
+@@ -958,8 +961,8 @@ eSetChannelResult cDevice::SetChannel(const cChannel *Channel, bool LiveView)
+            sectionHandler->SetStatus(true);
+            }
+         // Start decrypting any PIDs that might have been set in SetChannelDevice():
+-        if (camSlot)
+-           camSlot->StartDecrypting();
++        if (cCamSlot *cs = camSlot)
++           cs->StartDecrypting();
+         }
+      else
+         Result = scrFailed;
+@@ -1256,8 +1259,8 @@ bool cDevice::SetCurrentSubtitleTrack(eTrackType Type, bool Manual)
+        liveSubtitle = NULL;
+      }
+      delete ls;
+-     if (player)
+-        player->SetSubtitleTrack(currentSubtitleTrack, GetTrack(currentSubtitleTrack));
++     if (cPlayer *p = player)
++        p->SetSubtitleTrack(currentSubtitleTrack, GetTrack(currentSubtitleTrack));
+      else
+         SetSubtitleTrackDevice(currentSubtitleTrack);
+      if (currentSubtitleTrack != ttNone && !Replaying() && !Transferring()) {
+@@ -1468,9 +1471,9 @@ bool cDevice::AttachPlayer(cPlayer *Player)
+      player = Player;
+      if (!Transferring())
+         ClrAvailableTracks(false, true);
+-     SetPlayMode(player->playMode);
+-     player->device = this;
+-     player->Activate(true);
++     SetPlayMode(Player->playMode);
++     Player->device = this;
++     Player->Activate(true);
+      return true;
+      }
+   return false;
+@@ -1950,20 +1953,21 @@ bool cDevice::AttachReceiver(cReceiver *Receiver)
+          Receiver->Activate(true);
+          Receiver->device = this;
+          receiver[i] = Receiver;
+-         if (camSlot && Receiver->priority > MINPRIORITY) { // priority check to avoid an infinite loop with the CAM slot's caPidReceiver
+-            camSlot->StartDecrypting();
+-            if (camSlot->WantsTsData()) {
++         cCamSlot *cs = camSlot;
++         if (cs && Receiver->priority > MINPRIORITY) { // priority check to avoid an infinite loop with the CAM slot's caPidReceiver
++            cs->StartDecrypting();
++            if (cs->WantsTsData()) {
+                Receiver->lastEitInjection = 0;
+                Receiver->startEitInjection = time(NULL);
+                }
+             if (CamSlots.NumReadyMasterSlots() > 1) { // don't try different CAMs if there is only one
+                Receiver->startScrambleDetection = time(NULL);
+                Receiver->scramblingTimeout = TS_SCRAMBLING_TIMEOUT;
+-               bool KnownToDecrypt = ChannelCamRelations.CamDecrypt(Receiver->ChannelID(), camSlot->MasterSlotNumber());
++               bool KnownToDecrypt = ChannelCamRelations.CamDecrypt(Receiver->ChannelID(), cs->MasterSlotNumber());
+                if (KnownToDecrypt)
+                   Receiver->scramblingTimeout *= 9; // give it time to receive ECM/EMM (must be less than MAXBROKENTIMEOUT in recorder.c!)
+                if (Receiver->ChannelID().Valid())
+-                  dsyslog("CAM %d: %sknown to decrypt channel %s (scramblingTimeout = %ds)", camSlot->MasterSlotNumber(), KnownToDecrypt ? "" : "not ", *Receiver->ChannelID().ToString(), Receiver->scramblingTimeout);
++                  dsyslog("CAM %d: %sknown to decrypt channel %s (scramblingTimeout = %ds)", cs->MasterSlotNumber(), KnownToDecrypt ? "" : "not ", *Receiver->ChannelID().ToString(), Receiver->scramblingTimeout);
+                }
+             }
+          if (patFilter && Receiver->ChannelID().Valid())
+@@ -1995,9 +1999,9 @@ void cDevice::Detach(cReceiver *Receiver, bool ReleaseCam)
+   Receiver->Activate(false);
+   for (int n = 0; n < Receiver->numPids; n++)
+       DelPid(Receiver->pids[n]);
+-  if (camSlot) {
++  if (cCamSlot *cs = camSlot) {
+      if (Receiver->priority > MINPRIORITY) { // priority check to avoid an infinite loop with the CAM slot's caPidReceiver
+-        camSlot->StartDecrypting();
++        cs->StartDecrypting();
+         if (ReleaseCam)
+            ReleaseCamSlot();
+         }
+--- a/device.h
++++ b/device.h
+@@ -10,6 +10,7 @@
+ #ifndef __DEVICE_H
+ #define __DEVICE_H
+ 
++#include <atomic>
+ #include "channels.h"
+ #include "ci.h"
+ #include "dvbsubtitle.h"
+@@ -476,7 +477,7 @@ public:
+ // Common Interface facilities:
+ 
+ private:
+-  cCamSlot *camSlot;
++  std::atomic<cCamSlot *> camSlot; // set by cCamSlot::Assign() in any thread, read without a lock
+   void ReleaseCamSlot(void);
+          ///< Releases the CAM slot if it is currently not used.
+ public:
+@@ -650,7 +651,7 @@ public:
+ // Player facilities
+ 
+ private:
+-  cPlayer *player;
++  std::atomic<cPlayer *> player; // cleared by Detach() in any thread, read without a lock
+   cPatPmtParser patPmtParser;
+   cTsToPes tsToPesVideo;
+   cTsToPes tsToPesAudio;
+--- a/player.c
++++ b/player.c
+@@ -25,16 +25,16 @@ cPlayer::~cPlayer()
+ 
+ int cPlayer::PlayPes(const uchar *Data, int Length, bool VideoOnly)
+ {
+-  if (device)
+-     return device->PlayPes(Data, Length, VideoOnly);
++  if (cDevice *d = device)
++     return d->PlayPes(Data, Length, VideoOnly);
+   esyslog("ERROR: attempt to use cPlayer::PlayPes() without attaching to a cDevice!");
+   return -1;
+ }
+ 
+ void cPlayer::Detach(void)
+ {
+-  if (device)
+-     device->Detach(this);
++  if (cDevice *d = device)
++     d->Detach(this);
+ }
+ 
+ // --- cControl --------------------------------------------------------------
+--- a/player.h
++++ b/player.h
+@@ -16,28 +16,28 @@
+ class cPlayer {
+   friend class cDevice;
+ private:
+-  cDevice *device;
++  std::atomic<cDevice *> device; // cleared by cDevice::Detach() while the player's threads use it
+   ePlayMode playMode;
+ protected:
+-  void DeviceClrAvailableTracks(bool DescriptionsOnly = false) { if (device) device->ClrAvailableTracks(DescriptionsOnly); }
+-  bool DeviceSetAvailableTrack(eTrackType Type, int Index, uint16_t Id, const char *Language = NULL, const char *Description = NULL) { return device ? device->SetAvailableTrack(Type, Index, Id, Language, Description) : false; }
+-  bool DeviceSetCurrentAudioTrack(eTrackType Type) { return device ? device->SetCurrentAudioTrack(Type) : false; }
+-  bool DeviceSetCurrentSubtitleTrack(eTrackType Type) { return device ? device->SetCurrentSubtitleTrack(Type) : false; }
+-  bool DevicePoll(cPoller &Poller, int TimeoutMs = 0) { return device ? device->Poll(Poller, TimeoutMs) : false; }
++  void DeviceClrAvailableTracks(bool DescriptionsOnly = false) { if (cDevice *d = device) d->ClrAvailableTracks(DescriptionsOnly); }
++  bool DeviceSetAvailableTrack(eTrackType Type, int Index, uint16_t Id, const char *Language = NULL, const char *Description = NULL) { cDevice *d = device; return d ? d->SetAvailableTrack(Type, Index, Id, Language, Description) : false; }
++  bool DeviceSetCurrentAudioTrack(eTrackType Type) { cDevice *d = device; return d ? d->SetCurrentAudioTrack(Type) : false; }
++  bool DeviceSetCurrentSubtitleTrack(eTrackType Type) { cDevice *d = device; return d ? d->SetCurrentSubtitleTrack(Type) : false; }
++  bool DevicePoll(cPoller &Poller, int TimeoutMs = 0) { cDevice *d = device; return d ? d->Poll(Poller, TimeoutMs) : false; }
+   [[deprecated("use DeviceDrain() instead")]]
+   bool DeviceFlush(int TimeoutMs = 0) { return DeviceDrain(); }
+-  bool DeviceDrain(void) { return device ? device->Drain() : false; }
+-  bool DeviceHasIBPTrickSpeed(void) { return device ? device->HasIBPTrickSpeed() : false; }
+-  bool DeviceIsPlayingVideo(void) { return device ? device->IsPlayingVideo() : false; }
+-  void DeviceTrickSpeed(int Speed, bool Forward) { if (device) device->TrickSpeed(Speed, Forward); }
+-  void DeviceClear(void) { if (device) device->Clear(); }
+-  void DevicePlay(void) { if (device) device->Play(); }
+-  void DeviceFreeze(void) { if (device) device->Freeze(); }
+-  void DeviceMute(void) { if (device) device->Mute(); }
+-  void DeviceSetVideoDisplayFormat(eVideoDisplayFormat VideoDisplayFormat) { if (device) device->SetVideoDisplayFormat(VideoDisplayFormat); }
+-  void DeviceStillPicture(const uchar *Data, int Length) { if (device) device->StillPicture(Data, Length); }
+-  void DeviceSetTempSubtitles(void) { if (device) device->SetTempSubtitles(); }
+-  uint64_t DeviceGetSTC(void) { return device ? device->GetSTC() : -1; }
++  bool DeviceDrain(void) { cDevice *d = device; return d ? d->Drain() : false; }
++  bool DeviceHasIBPTrickSpeed(void) { cDevice *d = device; return d ? d->HasIBPTrickSpeed() : false; }
++  bool DeviceIsPlayingVideo(void) { cDevice *d = device; return d ? d->IsPlayingVideo() : false; }
++  void DeviceTrickSpeed(int Speed, bool Forward) { if (cDevice *d = device) d->TrickSpeed(Speed, Forward); }
++  void DeviceClear(void) { if (cDevice *d = device) d->Clear(); }
++  void DevicePlay(void) { if (cDevice *d = device) d->Play(); }
++  void DeviceFreeze(void) { if (cDevice *d = device) d->Freeze(); }
++  void DeviceMute(void) { if (cDevice *d = device) d->Mute(); }
++  void DeviceSetVideoDisplayFormat(eVideoDisplayFormat VideoDisplayFormat) { if (cDevice *d = device) d->SetVideoDisplayFormat(VideoDisplayFormat); }
++  void DeviceStillPicture(const uchar *Data, int Length) { if (cDevice *d = device) d->StillPicture(Data, Length); }
++  void DeviceSetTempSubtitles(void) { if (cDevice *d = device) d->SetTempSubtitles(); }
++  uint64_t DeviceGetSTC(void) { cDevice *d = device; return d ? d->GetSTC() : -1; }
+   void Detach(void);
+   virtual void Activate(bool On) {}
+        // This function is called right after the cPlayer has been attached to
+@@ -47,7 +47,7 @@ protected:
+        // Sends the given PES Data to the device and returns the number of
+        // bytes that have actually been accepted by the device (or a
+        // negative value in case of an error).
+-  int PlayTs(const uchar *Data, int Length, bool VideoOnly = false) { return device ? device->PlayTs(Data, Length, VideoOnly) : -1; }
++  int PlayTs(const uchar *Data, int Length, bool VideoOnly = false) { cDevice *d = device; return d ? d->PlayTs(Data, Length, VideoOnly) : -1; }
+        // Sends the given TS packet to the device and returns a positive number
+        // if the packet has been accepted by the device, or a negative value in
+        // case of an error.
+--- a/receiver.c
++++ b/receiver.c
+@@ -45,8 +45,8 @@ bool cReceiver::AddPid(int Pid)
+      if (numPids < MAXRECEIVEPIDS) {
+         if (!WantsPid(Pid)) {
+            pids[numPids++] = Pid;
+-           if (device)
+-              device->AddPid(Pid);
++           if (cDevice *d = device)
++              d->AddPid(Pid);
+            }
+         }
+      else {
+@@ -95,8 +95,8 @@ void cReceiver::DelPid(int Pid)
+             for ( ; i < numPids; i++) // we also copy the terminating 0!
+                 pids[i] = pids[i + 1];
+             numPids--;
+-            if (device)
+-               device->DelPid(Pid);
++            if (cDevice *d = device)
++               d->DelPid(Pid);
+             return;
+             }
+          }
+@@ -124,6 +124,6 @@ bool cReceiver::WantsPid(int Pid)
+ 
+ void cReceiver::Detach(void)
+ {
+-  if (device)
+-     device->Detach(this);
++  if (cDevice *d = device)
++     d->Detach(this);
+ }
+--- a/receiver.h
++++ b/receiver.h
+@@ -17,7 +17,7 @@
+ class cReceiver {
+   friend class cDevice;
+ private:
+-  cDevice *device;
++  std::atomic<cDevice *> device; // cleared by cDevice::Detach() in any thread
+   tChannelID channelID;
+   int priority;
+   int pids[MAXRECEIVEPIDS];

diff --git a/vdr-04-receiver-atomics.patch b/vdr-04-receiver-atomics.patch
deleted file mode 100644
index a844c2c..0000000
--- a/vdr-04-receiver-atomics.patch
+++ /dev/null
@@ -1,74 +0,0 @@
-From: Dirk Nehring <dnehring@gmx.net>
-Subject: [PATCH] receiver: make the PID array and the device pointer atomic
-
-The device thread scans an attached receiver's PIDs in WantsPid() while
-cCaPidReceiver (EMM PIDs) and cCamSlot::BuildCaPmts() (ECM PIDs) change
-them in other threads; taking the device's receiver mutex there would
-invert the lock order against the CAM slot mutex. A transiently
-inconsistent PID set only misroutes single TS packets at the moment of
-the change. cDevice::Detach() clears 'device' while another thread may
-be in AddPid()/DelPid(), which now act on one snapshot.
-
----
---- a/receiver.c
-+++ b/receiver.c
-@@ -45,8 +45,8 @@ bool cReceiver::AddPid(int Pid)
-      if (numPids < MAXRECEIVEPIDS) {
-         if (!WantsPid(Pid)) {
-            pids[numPids++] = Pid;
--           if (device)
--              device->AddPid(Pid);
-+           if (cDevice *d = device)
-+              d->AddPid(Pid);
-            }
-         }
-      else {
-@@ -93,10 +93,10 @@ void cReceiver::DelPid(int Pid)
-      for (int i = 0; i < numPids; i++) {
-          if (pids[i] == Pid) {
-             for ( ; i < numPids; i++) // we also copy the terminating 0!
--                pids[i] = pids[i + 1];
-+                pids[i] = pids[i + 1].load();
-             numPids--;
--            if (device)
--               device->DelPid(Pid);
-+            if (cDevice *d = device)
-+               d->DelPid(Pid);
-             return;
-             }
-          }
-@@ -124,6 +124,6 @@ bool cReceiver::WantsPid(int Pid)
- 
- void cReceiver::Detach(void)
- {
--  if (device)
--     device->Detach(this);
-+  if (cDevice *d = device)
-+     d->Detach(this);
- }
---- a/receiver.h
-+++ b/receiver.h
-@@ -10,6 +10,7 @@
- #ifndef __RECEIVER_H
- #define __RECEIVER_H
- 
-+#include <atomic>
- #include "device.h"
- 
- #define MAXRECEIVEPIDS  64 // the maximum number of PIDs per receiver
-@@ -17,11 +18,12 @@
- class cReceiver {
-   friend class cDevice;
- private:
--  cDevice *device;
-+  std::atomic<cDevice *> device; // cleared by cDevice::Detach() in any thread
-   tChannelID channelID;
-   int priority;
--  int pids[MAXRECEIVEPIDS];
--  int numPids;
-+  // changed while attached (EMM/ECM PIDs), scanned by the device thread without a lock:
-+  std::atomic<int> pids[MAXRECEIVEPIDS];
-+  std::atomic<int> numPids;
-   time_t lastScrambledPacket;
-   time_t startScrambleDetection;
-   int scramblingTimeout;

diff --git a/vdr-04-thread-atomics.patch b/vdr-04-thread-atomics.patch
new file mode 100644
index 0000000..a4a56d5
--- /dev/null
+++ b/vdr-04-thread-atomics.patch
@@ -0,0 +1,160 @@
+From: Dirk Nehring <dnehring@gmx.net>
+Subject: [PATCH] thread, ringbuffer: make the fields read without a lock atomic
+
+cThread's 'active' and 'running' are written by the thread itself and
+read by Start(), Active() and Cancel() in other threads. A thread that
+sees 'active' turn false goes on to delete the object, so it must also
+see everything Action() did before; as plain bools this is not ensured
+(and ThreadSanitizer reports a race against every destructor that runs
+after Cancel()). Active() reads 'active' once more when pthread_kill()
+finds the thread gone, so that the caller is ordered after the thread's
+last store on that path too. cMutex::Lock() and cRwLock::Lock() read the
+holder's thread id before they own the lock, cIoThrottle::Engaged() reads
+'count' without the mutex, and childThreadId and cRingBuffer::getThreadTid
+are logged by a thread other than the one that sets them.
+---
+--- a/ringbuffer.c
++++ b/ringbuffer.c
+@@ -50,7 +50,7 @@ void cRingBuffer::UpdatePercentage(int Fill)
+   int percent = Fill * 100 / (Size() - 1) / PERCENTAGEDELTA * PERCENTAGEDELTA; // clamp down to nearest quantum
+   if (percent != lastPercent) {
+      if (percent >= PERCENTAGETHRESHOLD && percent > lastPercent || percent < PERCENTAGETHRESHOLD && lastPercent >= PERCENTAGETHRESHOLD) {
+-        dsyslog("buffer usage: %d%% (tid=%d)", percent, getThreadTid);
++        dsyslog("buffer usage: %d%% (tid=%d)", percent, getThreadTid.load());
+         lastPercent = percent;
+         }
+      }
+--- a/ringbuffer.h
++++ b/ringbuffer.h
+@@ -25,7 +25,7 @@ private:
+   int overflowBytes;
+   cIoThrottle *ioThrottle;
+ protected:
+-  tThreadId getThreadTid;
++  std::atomic<tThreadId> getThreadTid; // set by the reading thread, logged by the writing one
+   int maxFill;//XXX
+   int lastPercent;
+   bool statistics;//XXX
+--- a/thread.c
++++ b/thread.c
+@@ -306,10 +306,10 @@ void *cThread::StartThread(cThread *Thread)
+ {
+   Thread->childThreadId = ThreadId();
+   if (Thread->description) {
+-     dsyslog("%s thread started (pid=%d, tid=%d, prio=%s)", Thread->description, getpid(), Thread->childThreadId, Thread->lowPriority ? "low" : "high");
++     dsyslog("%s thread started (pid=%d, tid=%d, prio=%s)", Thread->description, getpid(), Thread->childThreadId.load(), Thread->lowPriority ? "low" : "high");
+ #ifdef PR_SET_NAME
+      if (prctl(PR_SET_NAME, Thread->description, 0, 0, 0) < 0)
+-        esyslog("%s thread naming failed (pid=%d, tid=%d)", Thread->description, getpid(), Thread->childThreadId);
++        esyslog("%s thread naming failed (pid=%d, tid=%d)", Thread->description, getpid(), Thread->childThreadId.load());
+ #endif
+      }
+   if (Thread->lowPriority) {
+@@ -318,7 +318,7 @@ void *cThread::StartThread(cThread *Thread)
+      }
+   Thread->Action();
+   if (Thread->description)
+-     dsyslog("%s thread ended (pid=%d, tid=%d)", Thread->description, getpid(), Thread->childThreadId);
++     dsyslog("%s thread ended (pid=%d, tid=%d)", Thread->description, getpid(), Thread->childThreadId.load());
+   Thread->running = false;
+   Thread->active = false;
+   return NULL;
+@@ -369,7 +369,8 @@ bool cThread::Active(void)
+         if (err != ESRCH)
+            LOG_ERROR;
+         childTid = 0;
+-        active = running = false;
++        if (active) // read before overwriting: a thread that ended by itself has cleared it, and seeing that orders its work before the caller's
++           active = running = false;
+         }
+      else
+         return true;
+@@ -388,7 +389,7 @@ void cThread::Cancel(int WaitSeconds)
+                  return;
+               cCondWait::SleepMs(10);
+               }
+-        esyslog("ERROR: %s thread %d won't end (waited %d seconds) - canceling it...", description ? description : "", childThreadId, WaitSeconds);
++        esyslog("ERROR: %s thread %d won't end (waited %d seconds) - canceling it...", description ? description : "", childThreadId.load(), WaitSeconds);
+         }
+      pthread_cancel(childTid);
+      childTid = 0;
+@@ -926,7 +927,7 @@ bool cStateKey::StateChanged(void)
+ // --- cIoThrottle -----------------------------------------------------------
+ 
+ cMutex cIoThrottle::mutex;
+-int cIoThrottle::count = 0;
++std::atomic<int> cIoThrottle::count(0);
+ 
+ cIoThrottle::cIoThrottle(void)
+ {
+@@ -944,7 +945,7 @@ void cIoThrottle::Activate(void)
+   if (!active) {
+      count++;
+      active = true;
+-     dsyslog("i/o throttle activated, count = %d (tid=%d)", count, cThread::ThreadId());
++     dsyslog("i/o throttle activated, count = %d (tid=%d)", count.load(), cThread::ThreadId());
+      }
+   mutex.Unlock();
+ }
+@@ -955,7 +956,7 @@ void cIoThrottle::Release(void)
+   if (active) {
+      count--;
+      active = false;
+-     dsyslog("i/o throttle released, count = %d (tid=%d)", count, cThread::ThreadId());
++     dsyslog("i/o throttle released, count = %d (tid=%d)", count.load(), cThread::ThreadId());
+      }
+   mutex.Unlock();
+ }
+--- a/thread.h
++++ b/thread.h
+@@ -10,6 +10,7 @@
+ #ifndef __THREAD_H
+ #define __THREAD_H
+ 
++#include <atomic>
+ #include <pthread.h>
+ #include <stdio.h>
+ #include <sys/types.h>
+@@ -56,7 +57,7 @@ class cRwLock {
+ private:
+   pthread_rwlock_t rwlock;
+   int locked;
+-  tThreadId writeLockThreadId;
++  std::atomic<tThreadId> writeLockThreadId; // Lock() reads it without holding the lock
+ public:
+   cRwLock(bool PreferWriter = false);
+   ~cRwLock();
+@@ -68,7 +69,7 @@ class cMutex {
+   friend class cCondVar;
+ private:
+   pthread_mutex_t mutex;
+-  tThreadId lockThreadId; // current holder, 0 == unlocked; lets Lock() short-circuit recursive entry
++  std::atomic<tThreadId> lockThreadId; // current holder, 0 == unlocked; lets Lock() short-circuit recursive entry (read without holding the mutex)
+   int locked;
+ public:
+   cMutex(void);
+@@ -85,10 +86,12 @@ public:
+ class cThread {
+   friend class cThreadLock;
+ private:
+-  bool active;
+-  bool running;
++  // Shared by the thread and those that start, poll or cancel it; whoever
++  // sees 'active' false must also see everything Action() did:
++  std::atomic<bool> active;
++  std::atomic<bool> running;
+   pthread_t childTid;
+-  tThreadId childThreadId;
++  std::atomic<tThreadId> childThreadId; // set by the thread itself, logged by Cancel()
+   cMutex mutex;
+   char *description;
+   bool lowPriority;
+@@ -278,7 +281,7 @@ public:
+ class cIoThrottle {
+ private:
+   static cMutex mutex;
+-  static int count;
++  static std::atomic<int> count; // Engaged() reads it without the mutex
+   bool active;
+ public:
+   cIoThrottle(void);

diff --git a/vdr-05-recorder-stop-timeout.patch b/vdr-05-recorder-stop-timeout.patch
new file mode 100644
index 0000000..447ed32
--- /dev/null
+++ b/vdr-05-recorder-stop-timeout.patch
@@ -0,0 +1,40 @@
+From: Dirk Nehring <dnehring@gmx.net>
+Subject: [PATCH] recorder: end the thread when no independent frame follows Stop()
+
+Action() leaves its loop only at the next independent frame after
+Running() turned false, so that the recording ends on a frame boundary.
+When no such frame arrives - the stream has stopped, or the recording
+is restarted by ChannelDataModified() because its PIDs were wrong - the
+thread never ends, and Cancel(3) kills it with pthread_cancel() after
+three seconds, inside cCondWait::Wait() with the mutex held, which
+~cCondWait() then destroys. Now the thread gives the stream two seconds
+for its independent frame and ends by itself after that.
+---
+--- a/recorder.c
++++ b/recorder.c
+@@ -241,6 +241,8 @@ void cRecorder::Action(void)
+   off_t pendFileSize = 0;
+   bool pendMissing = false;
+   int NumIframesSeen = 0;
++  cTimeMs StopTimeout;
++  bool Stopping = false;
+   working = true;
+   while (true) {
+ #ifdef TEST_VDSB
+@@ -329,8 +331,14 @@ void cRecorder::Action(void)
+            ShutdownHandler.RequestEmergencyExit();
+            t.Reset();
+            }
+-        if (!Running() && ShutdownHandler.EmergencyExitRequested())
+-           break;
++        if (!Running()) {
++           if (!Stopping) { // wait for the next independent frame, but less than Cancel(3) does - without video it never comes
++              Stopping = true;
++              StopTimeout.Set(2000);
++              }
++           if (StopTimeout.TimedOut() || ShutdownHandler.EmergencyExitRequested())
++              break;
++           }
+         }
+   // Estimate the number of missing frames in case the data stream was broken, but the timer
+   // didn't reach the timeout, yet:

diff --git a/vdr-05-transfer-atomics.patch b/vdr-05-transfer-atomics.patch
deleted file mode 100644
index 0f3697e..0000000
--- a/vdr-05-transfer-atomics.patch
+++ /dev/null
@@ -1,49 +0,0 @@
-From: Dirk Nehring <dnehring@gmx.net>
-Subject: [PATCH] transfer: make 'activated' and receiverDevice atomic
-
-Activate() sets 'activated' in the thread that attaches the player, and
-Receive() reads it in the receiver thread; the atomic also makes the
-PAT/PMT that Activate() plays visible before Receive()'s first PlayTs().
-receiverDevice is set and cleared by whichever thread creates or
-destroys the transfer control (e.g. SVDRP CHAN), and read without a lock
-by cDevice::ActualDevice() and the skins.
-
----
---- a/transfer.c
-+++ b/transfer.c
-@@ -71,7 +71,7 @@ void cTransfer::Receive(const uchar *Data, int Length)
- 
- // --- cTransferControl ------------------------------------------------------
- 
--cDevice *cTransferControl::receiverDevice = NULL;
-+std::atomic<cDevice *> cTransferControl::receiverDevice(NULL);
- 
- cTransferControl::cTransferControl(cDevice *ReceiverDevice, const cChannel *Channel)
- :cControl(NULL, true)
---- a/transfer.h
-+++ b/transfer.h
-@@ -10,13 +10,14 @@
- #ifndef __TRANSFER_H
- #define __TRANSFER_H
- 
-+#include <atomic>
- #include "player.h"
- #include "receiver.h"
- #include "remux.h"
- 
- class cTransfer : public cReceiver, public cPlayer {
- private:
--  bool activated;
-+  std::atomic<bool> activated; // set by Activate() after the PAT/PMT, checked by Receive() in the receiver thread
-   time_t lastErrorReport;
-   int numLostPackets;
-   cPatPmtGenerator patPmtGenerator;
-@@ -31,7 +32,7 @@ public:
- class cTransferControl : public cControl {
- private:
-   cTransfer *transfer;
--  static cDevice *receiverDevice;
-+  static std::atomic<cDevice *> receiverDevice; // set and cleared by the switching thread, read by any
- public:
-   cTransferControl(cDevice *ReceiverDevice, const cChannel *Channel);
-   ~cTransferControl();

diff --git a/vdr-06-dvbplayer-atomics.patch b/vdr-06-dvbplayer-atomics.patch
deleted file mode 100644
index a3a6aab..0000000
--- a/vdr-06-dvbplayer-atomics.patch
+++ /dev/null
@@ -1,86 +0,0 @@
-From: Dirk Nehring <dnehring@gmx.net>
-Subject: [PATCH] dvbplayer: make the state read without the thread lock atomic
-
-The control functions change playMode, playDir, trickSpeed and readIndex
-under LOCK_THREAD, but Action() reads some of them before taking it, and
-GetIndex(), GetFrameNumber() and GetReplayMode() read them from the main
-thread. cNonBlockingFileReader changes buffer, wanted and length under
-its thread lock, but WaitForDataMs() reads them under newDataMutex only
-and Reading() without any lock.
-
----
---- a/dvbplayer.c
-+++ b/dvbplayer.c
-@@ -129,9 +129,10 @@ int cPtsIndex::FindFrameNumber(uint32_t Pts, bool Forward, bool Still)
- class cNonBlockingFileReader : public cThread {
- private:
-   cUnbufferedFile *f;
--  uchar *buffer;
--  int wanted;
--  int length;
-+  // changed under the thread lock, read without it by Reading() and WaitForDataMs():
-+  std::atomic<uchar *> buffer;
-+  std::atomic<int> wanted;
-+  std::atomic<int> length;
-   cCondWait newSet;
-   cCondVar newDataCond;
-   cMutex newDataMutex;
-@@ -201,12 +202,13 @@ void cNonBlockingFileReader::Action(void)
-   while (Running()) {
-         Lock();
-         if (f && buffer && length < wanted) {
--           int r = f->Read(buffer + length, wanted - length);
-+           uchar *b = buffer;
-+           int r = f->Read(b + length, wanted - length);
-            if (r > 0)
-               length += r;
-            else if (r == 0) { // r == 0 means EOF
-               if (length > 0)
--                 wanted = length; // already read something, so return the rest
-+                 wanted = length.load(); // already read something, so return the rest
-               else
-                  length = wanted = 0; // report EOF
-               }
-@@ -256,10 +258,11 @@ private:
-   bool pauseLive;
-   bool eof;
-   bool firstPacket;
--  ePlayModes playMode;
--  ePlayDirs playDir;
--  int trickSpeed;
--  int readIndex;
-+  // changed under LOCK_THREAD, read without it in Action() and by the Get*() functions:
-+  std::atomic<ePlayModes> playMode;
-+  std::atomic<ePlayDirs> playDir;
-+  std::atomic<int> trickSpeed;
-+  std::atomic<int> readIndex;
-   bool readIndependent;
-   cFrame *readFrame;
-   cFrame *playFrame;
-@@ -458,7 +461,7 @@ void cDvbPlayer::Action(void)
- 
-   readIndex = Resume();
-   if (readIndex > 0)
--     isyslog("resuming replay at index %d (%s)", readIndex, *IndexToHMSF(readIndex, true, framesPerSecond));
-+     isyslog("resuming replay at index %d (%s)", readIndex.load(), *IndexToHMSF(readIndex, true, framesPerSecond));
-   else if (Setup.SkipEdited && marks) {
-      cStateKey StateKey;
-      marks->Lock(StateKey);
-@@ -817,7 +820,7 @@ void cDvbPlayer::Forward(void)
-             TrickSpeed(Setup.MultiSpeedMode ? -1 : -MAX_SPEEDS);
-             }
-             break;
--       default: esyslog("ERROR: unknown playMode %d (%s)", playMode, __FUNCTION__);
-+       default: esyslog("ERROR: unknown playMode %d (%s)", playMode.load(), __FUNCTION__);
-        }
-      }
- }
-@@ -869,7 +872,7 @@ void cDvbPlayer::Backward(void)
-             TrickSpeed(Setup.MultiSpeedMode ? -1 : -MAX_SPEEDS);
-             }
-             break;
--       default: esyslog("ERROR: unknown playMode %d (%s)", playMode, __FUNCTION__);
-+       default: esyslog("ERROR: unknown playMode %d (%s)", playMode.load(), __FUNCTION__);
-        }
-      }
- }

diff --git a/vdr-06-timer-flags-atomic.patch b/vdr-06-timer-flags-atomic.patch
new file mode 100644
index 0000000..58d1d87
--- /dev/null
+++ b/vdr-06-timer-flags-atomic.patch
@@ -0,0 +1,64 @@
+From: Dirk Nehring <dnehring@gmx.net>
+Subject: [PATCH] timers: change the timer flags atomically
+
+cRecordControl::Stop() clears tfRecording through cTimer::SetRecording(),
+and cRecordControls::ChannelDataModified() calls it from the main loop
+while holding only the channels lock (taking the timers lock there would
+invert the lock order). Other threads may change the flags of the same
+timer at that time under the timers lock (SVDRP, plugins), and with
+'flags |= Flags' one of the two changes can get lost. The member stays a
+plain uint, because the timer editor hands its address to
+cMenuEditBitItem.
+---
+--- a/timers.c
++++ b/timers.c
+@@ -255,7 +255,7 @@ cTimer& cTimer::operator= (const cTimer &Timer)
+      deferred     = 0;
+      pending      = Timer.pending;
+      inVpsMargin  = Timer.inVpsMargin;
+-     flags        = Timer.flags;
++     __atomic_store_n(&flags, __atomic_load_n(&Timer.flags, __ATOMIC_RELAXED), __ATOMIC_RELAXED);
+      channel      = Timer.channel;
+      day          = Timer.day;
+      weekdays     = Timer.weekdays;
+@@ -324,7 +324,7 @@ cString cTimer::ToText(bool UseChannelID) const
+ {
+   strreplace(pattern, ':', '|');
+   strreplace(file, ':', '|');
+-  cString buffer = cString::sprintf("%u:%s:%s:%04d:%04d:%d:%d:%s:%s", flags, UseChannelID ? *Channel()->GetChannelID().ToString() : *itoa(Channel()->Number()), *PrintDay(day, weekdays, true), start, stop, priority, lifetime, *PatternAndFile(), aux ? aux : "");
++  cString buffer = cString::sprintf("%u:%s:%s:%04d:%04d:%d:%d:%s:%s", __atomic_load_n(&flags, __ATOMIC_RELAXED), UseChannelID ? *Channel()->GetChannelID().ToString() : *itoa(Channel()->Number()), *PrintDay(day, weekdays, true), start, stop, priority, lifetime, *PatternAndFile(), aux ? aux : "");
+   strreplace(pattern, '|', ':');
+   strreplace(file, '|', ':');
+   return buffer;
+@@ -1117,24 +1117,27 @@ void cTimer::SetDeferred(int Seconds)
+   isyslog("timer %s deferred for %d seconds", *ToDescr(), Seconds);
+ }
+ 
++// The flags are changed without the timers lock (see cRecordControls::ChannelDataModified()).
++// They stay a plain uint, because the timer editor hands their address to cMenuEditBitItem:
++
+ void cTimer::SetFlags(uint Flags)
+ {
+-  flags |= Flags;
++  __atomic_fetch_or(&flags, Flags, __ATOMIC_RELAXED);
+ }
+ 
+ void cTimer::ClrFlags(uint Flags)
+ {
+-  flags &= ~Flags;
++  __atomic_fetch_and(&flags, ~Flags, __ATOMIC_RELAXED);
+ }
+ 
+ void cTimer::InvFlags(uint Flags)
+ {
+-  flags ^= Flags;
++  __atomic_fetch_xor(&flags, Flags, __ATOMIC_RELAXED);
+ }
+ 
+ bool cTimer::HasFlags(uint Flags) const
+ {
+-  return (flags & Flags) == Flags;
++  return (__atomic_load_n(&flags, __ATOMIC_RELAXED) & Flags) == Flags;
+ }
+ 
+ void cTimer::Skip(void)

diff --git a/vdr-07-dvbtuner-atomics.patch b/vdr-07-dvbtuner-atomics.patch
deleted file mode 100644
index 4c3e716..0000000
--- a/vdr-07-dvbtuner-atomics.patch
+++ /dev/null
@@ -1,72 +0,0 @@
-From: Dirk Nehring <dnehring@gmx.net>
-Subject: [PATCH] dvbdevice: make the tuner state read without the mutex atomic
-
-The tuner thread changes tunerStatus under its mutex, while Locked() and
-IsTunedTo() read it and the destructor sets it without the mutex.
-frontendType and positioner are set by the tuner thread and read by
-other threads through FrontendType() and Positioner(); GetPositioner()
-now publishes the positioner only after SetFrontend().
-
----
---- a/dvbdevice.c
-+++ b/dvbdevice.c
-@@ -533,7 +533,7 @@ class cDvbTuner : public cThread {
- private:
-   static cMutex bondMutex;
-   enum eTunerStatus { tsIdle, tsSet, tsPositioning, tsTuned, tsLocked };
--  int frontendType;
-+  std::atomic<int> frontendType; // FrontendType() reads it without the mutex
-   const cDvbDevice *device;
-   mutable int fd_frontend;
-   int adapter;
-@@ -552,10 +552,10 @@ private:
-   mutable const cDiseqc *lastDiseqc;
-   int diseqcOffset;
-   mutable int lastSource;
--  cPositioner *positioner;
-+  std::atomic<cPositioner *> positioner; // Positioner() reads it without the mutex
-   const cScr *scr;
-   mutable bool lnbPowerTurnedOn;
--  eTunerStatus tunerStatus;
-+  std::atomic<eTunerStatus> tunerStatus; // Locked() and the destructor use it without the mutex
-   mutable cMutex mutex;
-   cCondVar locked;
-   cCondVar newSet;
-@@ -1482,11 +1482,13 @@ static unsigned int FrequencyToHz(unsigned int f)
- 
- cPositioner *cDvbTuner::GetPositioner(void)
- {
--  if (!positioner) {
--     positioner = cPositioner::GetPositioner();
--     positioner->SetFrontend(fd_frontend);
-+  cPositioner *p = positioner;
-+  if (!p) {
-+     p = cPositioner::GetPositioner();
-+     p->SetFrontend(fd_frontend);
-+     positioner = p;
-      }
--  return positioner;
-+  return p;
- }
- 
- void cDvbTuner::ExecuteDiseqc(const cDiseqc *Diseqc, int *Frequency)
-@@ -1712,8 +1714,8 @@ void cDvbTuner::Action(void)
-                tunerStatus = SetFrontend() ? tsPositioning : tsIdle;
-                continue;
-           case tsPositioning:
--               if (positioner) {
--                  if (positioner->IsMoving())
-+               if (cPositioner *p = positioner) {
-+                  if (p->IsMoving())
-                      break; // we want the TimedWait() below!
-                   else if (diseqcOffset) {
-                      lastDiseqc = NULL;
-@@ -1776,7 +1778,7 @@ void cDvbTuner::Action(void)
-                   continue;
-                   }
-                break;
--          default: esyslog("ERROR: unknown tuner status %d", tunerStatus);
-+          default: esyslog("ERROR: unknown tuner status %d", tunerStatus.load());
-           }
-         newSet.TimedWait(mutex, WaitTime);
-         }

diff --git a/vdr-07-track-description-copy.patch b/vdr-07-track-description-copy.patch
new file mode 100644
index 0000000..424d012
--- /dev/null
+++ b/vdr-07-track-description-copy.patch
@@ -0,0 +1,127 @@
+From: Dirk Nehring <dnehring@gmx.net>
+Subject: [PATCH] device, menu, skins: read track descriptions through a locked copy
+
+The skins' DrawTrack() and the audio and subtitle track menus read the
+track table through GetTrack(), a bare pointer into
+cDevice::availableTracks[], while other threads rewrite the entries
+under mutexCurrentAudioTrack: a channel switch (e.g. SVDRP CHAN) clears
+and refills the table, and a player announces its tracks with every PES
+packet (the dvd plugin also their language and description). So a
+description could be read while it was being overwritten.
+cDevice::GetTrackId() copies an entry under that mutex.
+---
+--- a/device.c
++++ b/device.c
+@@ -1184,6 +1184,16 @@ const tTrackId *cDevice::GetTrack(eTrackType Type)
+   return (ttNone < Type && Type < ttMaxTrackTypes) ? &availableTracks[Type] : NULL;
+ }
+ 
++bool cDevice::GetTrackId(eTrackType Type, tTrackId &TrackId)
++{
++  cMutexLock MutexLock(&mutexCurrentAudioTrack);
++  if (const tTrackId *Track = GetTrack(Type)) {
++     TrackId = *Track;
++     return true;
++     }
++  return false;
++}
++
+ int cDevice::NumTracks(eTrackType FirstTrack, eTrackType LastTrack) const
+ {
+   int n = 0;
+--- a/device.h
++++ b/device.h
+@@ -582,6 +582,11 @@ public:
+   const tTrackId *GetTrack(eTrackType Type);
+        ///< Returns a pointer to the given track id, or NULL if Type is not
+        ///< less than ttMaxTrackTypes.
++  bool GetTrackId(eTrackType Type, tTrackId &TrackId);
++       ///< Copies the given track id into TrackId and returns true, or returns
++       ///< false if Type is not a valid track type. Unlike GetTrack() this may be
++       ///< used while another thread switches the channel, which rewrites the
++       ///< track table.
+   int NumTracks(eTrackType FirstTrack, eTrackType LastTrack) const;
+        ///< Returns the number of tracks in the given range that are currently
+        ///< available.
+--- a/menu.c
++++ b/menu.c
+@@ -5402,10 +5402,10 @@ cDisplayTracks::cDisplayTracks(void)
+   audioChannel = cDevice::PrimaryDevice()->GetAudioChannel();
+   eTrackType CurrentAudioTrack = cDevice::PrimaryDevice()->GetCurrentAudioTrack();
+   for (int i = ttAudioFirst; i <= ttDolbyLast; i++) {
+-      const tTrackId *TrackId = cDevice::PrimaryDevice()->GetTrack(eTrackType(i));
+-      if (TrackId && TrackId->id) {
++      tTrackId TrackId;
++      if (cDevice::PrimaryDevice()->GetTrackId(eTrackType(i), TrackId) && TrackId.id) {
+          types[numTracks] = eTrackType(i);
+-         descriptions[numTracks] = strdup(*TrackId->description ? TrackId->description : *TrackId->language ? TrackId->language : *itoa(i));
++         descriptions[numTracks] = strdup(*TrackId.description ? TrackId.description : *TrackId.language ? TrackId.language : *itoa(i));
+          if (i == CurrentAudioTrack)
+             track = numTracks;
+          numTracks++;
+@@ -5523,10 +5523,10 @@ cDisplaySubtitleTracks::cDisplaySubtitleTracks(void)
+   numTracks++;
+   eTrackType CurrentSubtitleTrack = cDevice::PrimaryDevice()->GetCurrentSubtitleTrack();
+   for (int i = ttSubtitleFirst; i <= ttSubtitleLast; i++) {
+-      const tTrackId *TrackId = cDevice::PrimaryDevice()->GetTrack(eTrackType(i));
+-      if (TrackId && TrackId->id) {
++      tTrackId TrackId;
++      if (cDevice::PrimaryDevice()->GetTrackId(eTrackType(i), TrackId) && TrackId.id) {
+          types[numTracks] = eTrackType(i);
+-         descriptions[numTracks] = strdup(*TrackId->description ? TrackId->description : *TrackId->language ? TrackId->language : *itoa(i));
++         descriptions[numTracks] = strdup(*TrackId.description ? TrackId.description : *TrackId.language ? TrackId.language : *itoa(i));
+          if (i == CurrentSubtitleTrack)
+             track = numTracks;
+          numTracks++;
+--- a/skinlcars.c
++++ b/skinlcars.c
+@@ -492,10 +492,11 @@ void cSkinLCARSDisplayChannel::DrawDate(void)
+ void cSkinLCARSDisplayChannel::DrawTrack(void)
+ {
+   cDevice *Device = cDevice::PrimaryDevice();
+-  const tTrackId *Track = Device->GetTrack(Device->GetCurrentAudioTrack());
+-  if (Track ? strcmp(lastTrackId.description, Track->description) : *lastTrackId.description) {
+-     osd->DrawText(xc03, yc07, Track ? Track->description : "", Theme.Color(clrTrackName), Theme.Color(clrBackground), cFont::GetFont(fontOsd), xc07 - xc03);
+-     strn0cpy(lastTrackId.description, Track ? Track->description : "", sizeof(lastTrackId.description));
++  tTrackId TrackId;
++  bool Track = Device->GetTrackId(Device->GetCurrentAudioTrack(), TrackId);
++  if (Track ? strcmp(lastTrackId.description, TrackId.description) : *lastTrackId.description) {
++     osd->DrawText(xc03, yc07, Track ? TrackId.description : "", Theme.Color(clrTrackName), Theme.Color(clrBackground), cFont::GetFont(fontOsd), xc07 - xc03);
++     strn0cpy(lastTrackId.description, Track ? TrackId.description : "", sizeof(lastTrackId.description));
+      }
+ }
+ 
+@@ -1897,10 +1898,11 @@ void cSkinLCARSDisplayReplay::DrawDate(void)
+ void cSkinLCARSDisplayReplay::DrawTrack(void)
+ {
+   cDevice *Device = cDevice::PrimaryDevice();
+-  const tTrackId *Track = Device->GetTrack(Device->GetCurrentAudioTrack());
+-  if (Track ? strcmp(lastTrackId.description, Track->description) : *lastTrackId.description) {
+-     osd->DrawText(xp03, yp04, Track ? Track->description : "", Theme.Color(clrTrackName), Theme.Color(clrBackground), cFont::GetFont(fontOsd), xp07 - xp03);
+-     strn0cpy(lastTrackId.description, Track ? Track->description : "", sizeof(lastTrackId.description));
++  tTrackId TrackId;
++  bool Track = Device->GetTrackId(Device->GetCurrentAudioTrack(), TrackId);
++  if (Track ? strcmp(lastTrackId.description, TrackId.description) : *lastTrackId.description) {
++     osd->DrawText(xp03, yp04, Track ? TrackId.description : "", Theme.Color(clrTrackName), Theme.Color(clrBackground), cFont::GetFont(fontOsd), xp07 - xp03);
++     strn0cpy(lastTrackId.description, Track ? TrackId.description : "", sizeof(lastTrackId.description));
+      }
+ }
+ 
+--- a/skinsttng.c
++++ b/skinsttng.c
+@@ -338,10 +338,11 @@ void cSkinSTTNGDisplayChannel::Flush(void)
+            lastDate = date;
+            }
+         cDevice *Device = cDevice::PrimaryDevice();
+-        const tTrackId *Track = Device->GetTrack(Device->GetCurrentAudioTrack());
+-        if (Track ? strcmp(lastTrackId.description, Track->description) : *lastTrackId.description) {
+-           osd->DrawText(x3 + TextFrame, y6, Track ? Track->description : "", Theme.Color(clrChannelName), frameColor, font, x4 - x3 - w - 2 * TextFrame);
+-           strn0cpy(lastTrackId.description, Track ? Track->description : "", sizeof(lastTrackId.description));
++        tTrackId TrackId;
++        bool Track = Device->GetTrackId(Device->GetCurrentAudioTrack(), TrackId);
++        if (Track ? strcmp(lastTrackId.description, TrackId.description) : *lastTrackId.description) {
++           osd->DrawText(x3 + TextFrame, y6, Track ? TrackId.description : "", Theme.Color(clrChannelName), frameColor, font, x4 - x3 - w - 2 * TextFrame);
++           strn0cpy(lastTrackId.description, Track ? TrackId.description : "", sizeof(lastTrackId.description));
+            }
+         int DeviceNumber = cDevice::ActualDevice()->DeviceNumber() + 1;
+         if (DeviceNumber != lastDeviceNumber || time(NULL) != lastSignalDisplay) {

diff --git a/vdr-08-dvbplayer-atomics.patch b/vdr-08-dvbplayer-atomics.patch
new file mode 100644
index 0000000..3a08f85
--- /dev/null
+++ b/vdr-08-dvbplayer-atomics.patch
@@ -0,0 +1,89 @@
+From: Dirk Nehring <dnehring@gmx.net>
+Subject: [PATCH] dvbplayer: make the state read without the thread lock atomic
+
+The control functions change playMode, playDir, trickSpeed and readIndex
+under LOCK_THREAD, but Action() reads some of them before taking it, and
+GetIndex(), GetFrameNumber() and GetReplayMode() read them from the main
+thread. NextFile() clears 'eof' from the main thread's Goto() while
+Action() tests it before sleeping. cNonBlockingFileReader changes
+buffer, wanted and length under its thread lock, but WaitForDataMs()
+reads them under newDataMutex only and Reading() without any lock.
+---
+--- a/dvbplayer.c
++++ b/dvbplayer.c
+@@ -129,9 +129,10 @@ int cPtsIndex::FindFrameNumber(uint32_t Pts, bool Forward, bool Still)
+ class cNonBlockingFileReader : public cThread {
+ private:
+   cUnbufferedFile *f;
+-  uchar *buffer;
+-  int wanted;
+-  int length;
++  // changed under the thread lock, read without it by Reading() and WaitForDataMs():
++  std::atomic<uchar *> buffer;
++  std::atomic<int> wanted;
++  std::atomic<int> length;
+   cCondWait newSet;
+   cCondVar newDataCond;
+   cMutex newDataMutex;
+@@ -201,12 +202,13 @@ void cNonBlockingFileReader::Action(void)
+   while (Running()) {
+         Lock();
+         if (f && buffer && length < wanted) {
+-           int r = f->Read(buffer + length, wanted - length);
++           uchar *b = buffer;
++           int r = f->Read(b + length, wanted - length);
+            if (r > 0)
+               length += r;
+            else if (r == 0) { // r == 0 means EOF
+               if (length > 0)
+-                 wanted = length; // already read something, so return the rest
++                 wanted = length.load(); // already read something, so return the rest
+               else
+                  length = wanted = 0; // report EOF
+               }
+@@ -254,12 +256,13 @@ private:
+   double framesPerSecond;
+   bool isPesRecording;
+   bool pauseLive;
+-  bool eof;
++  std::atomic<bool> eof; // cleared by NextFile() from the main thread, tested by Action() before sleeping
+   bool firstPacket;
+-  ePlayModes playMode;
+-  ePlayDirs playDir;
+-  int trickSpeed;
+-  int readIndex;
++  // changed under LOCK_THREAD, read without it in Action() and by the Get*() functions:
++  std::atomic<ePlayModes> playMode;
++  std::atomic<ePlayDirs> playDir;
++  std::atomic<int> trickSpeed;
++  std::atomic<int> readIndex;
+   bool readIndependent;
+   cFrame *readFrame;
+   cFrame *playFrame;
+@@ -458,7 +461,7 @@ void cDvbPlayer::Action(void)
+ 
+   readIndex = Resume();
+   if (readIndex > 0)
+-     isyslog("resuming replay at index %d (%s)", readIndex, *IndexToHMSF(readIndex, true, framesPerSecond));
++     isyslog("resuming replay at index %d (%s)", readIndex.load(), *IndexToHMSF(readIndex, true, framesPerSecond));
+   else if (Setup.SkipEdited && marks) {
+      cStateKey StateKey;
+      marks->Lock(StateKey);
+@@ -815,7 +818,7 @@ void cDvbPlayer::Forward(void)
+             TrickSpeed(Setup.MultiSpeedMode ? -1 : -MAX_SPEEDS);
+             }
+             break;
+-       default: esyslog("ERROR: unknown playMode %d (%s)", playMode, __FUNCTION__);
++       default: esyslog("ERROR: unknown playMode %d (%s)", playMode.load(), __FUNCTION__);
+        }
+      }
+ }
+@@ -867,7 +870,7 @@ void cDvbPlayer::Backward(void)
+             TrickSpeed(Setup.MultiSpeedMode ? -1 : -MAX_SPEEDS);
+             }
+             break;
+-       default: esyslog("ERROR: unknown playMode %d (%s)", playMode, __FUNCTION__);
++       default: esyslog("ERROR: unknown playMode %d (%s)", playMode.load(), __FUNCTION__);
+        }
+      }
+ }

diff --git a/vdr-08-dvbtuner-channel-lock.patch b/vdr-08-dvbtuner-channel-lock.patch
deleted file mode 100644
index 5ad15c1..0000000
--- a/vdr-08-dvbtuner-channel-lock.patch
+++ /dev/null
@@ -1,38 +0,0 @@
-From: Dirk Nehring <dnehring@gmx.net>
-Subject: [PATCH] dvbdevice: read the tuner's channel only under its mutex
-
-SetChannel() reassigns 'channel' under the tuner mutex, which frees its
-old name and parameter strings, while IsTunedTo() (device selection in
-other threads) and GetSignalStrength()/GetSignalQuality() (skins) read
-it without the mutex. The signal functions take it only for the SSI/SQI
-calculation: their frontend ioctls can take hundreds of milliseconds on
-USB tuners, and holding the mutex across them would stall the tuner
-thread.
-
----
---- a/dvbdevice.c
-+++ b/dvbdevice.c
-@@ -798,6 +798,7 @@ cDvbTuner *cDvbTuner::GetBondedMaster(void)
- 
- bool cDvbTuner::IsTunedTo(const cChannel *Channel) const
- {
-+  cMutexLock MutexLock(&mutex); // SetChannel() reassigns 'channel', freeing its strings
-   if (tunerStatus == tsIdle)
-      return false; // not tuned to
-   if (channel.Source() != Channel->Source() || channel.Transponder() != Channel->Transponder() || channel.Srate() != Channel->Srate())
-@@ -1257,6 +1258,7 @@ int cDvbTuner::GetSignalStrength(void) const
-       int FeFec = (Props[3].u.st.len > 0) ? (int)Props[3].u.data : -1;
-       int Signal = 0;
-       if (Props[0].u.st.len > 0) {
-+         cMutexLock MutexLock(&mutex); // for 'channel' (see IsTunedTo()), but not across the slow ioctls above, which would stall the tuner thread
-          switch (Props[0].u.st.stat[0].scale) {
-            case FE_SCALE_DECIBEL:  Signal = StrengthToSSI(&channel, Props[0].u.st.stat[0].svalue, FeMod, FeCod, FeFec);
-                                    break;
-@@ -1335,6 +1337,7 @@ int cDvbTuner::GetSignalQuality(void) const
-          }
-       int Cnr = 0;
-       if (Props[0].u.st.len > 0) {
-+         cMutexLock MutexLock(&mutex); // for 'channel', see GetSignalStrength()
-          switch (Props[0].u.st.stat[0].scale) {
-            case FE_SCALE_DECIBEL:  Cnr = SignalToSQI(&channel, Props[0].u.st.stat[0].svalue, Ber, FeMod, FeCod, FeFec);
-                                    break;

diff --git a/vdr-09-dvbdevice-atomics.patch b/vdr-09-dvbdevice-atomics.patch
new file mode 100644
index 0000000..cccaa27
--- /dev/null
+++ b/vdr-09-dvbdevice-atomics.patch
@@ -0,0 +1,95 @@
+From: Dirk Nehring <dnehring@gmx.net>
+Subject: [PATCH] dvbdevice: make the tuner state and the bonding flag atomic
+
+The tuner thread changes tunerStatus under its mutex, while Locked() and
+IsTunedTo() read it and the destructor sets it without the mutex.
+frontendType and positioner are set by the tuner thread and read by
+other threads through FrontendType() and Positioner(); GetPositioner()
+now publishes the positioner only after SetFrontend().
+
+The const ProvidesChannel() stores needsDetachBondedReceivers for the
+following SetChannelDevice(), and GetDevice() calls it on whichever
+thread switches a channel, so an SVDRP CHAN and the main thread can
+write it at the same time. The value still belongs to the last query.
+---
+--- a/dvbdevice.c
++++ b/dvbdevice.c
+@@ -533,7 +533,7 @@ class cDvbTuner : public cThread {
+ private:
+   static cMutex bondMutex;
+   enum eTunerStatus { tsIdle, tsSet, tsPositioning, tsTuned, tsLocked };
+-  int frontendType;
++  std::atomic<int> frontendType; // FrontendType() reads it without the mutex
+   const cDvbDevice *device;
+   mutable int fd_frontend;
+   int adapter;
+@@ -552,10 +552,10 @@ private:
+   mutable const cDiseqc *lastDiseqc;
+   int diseqcOffset;
+   mutable int lastSource;
+-  cPositioner *positioner;
++  std::atomic<cPositioner *> positioner; // Positioner() reads it without the mutex
+   const cScr *scr;
+   mutable bool lnbPowerTurnedOn;
+-  eTunerStatus tunerStatus;
++  std::atomic<eTunerStatus> tunerStatus; // Locked() and the destructor use it without the mutex
+   mutable cMutex mutex;
+   cCondVar locked;
+   cCondVar newSet;
+@@ -1489,11 +1489,13 @@ static unsigned int FrequencyToHz(unsigned int f)
+ 
+ cPositioner *cDvbTuner::GetPositioner(void)
+ {
+-  if (!positioner) {
+-     positioner = cPositioner::GetPositioner();
+-     positioner->SetFrontend(fd_frontend);
++  cPositioner *p = positioner;
++  if (!p) {
++     p = cPositioner::GetPositioner();
++     p->SetFrontend(fd_frontend);
++     positioner = p;
+      }
+-  return positioner;
++  return p;
+ }
+ 
+ void cDvbTuner::ExecuteDiseqc(const cDiseqc *Diseqc, int *Frequency)
+@@ -1719,8 +1721,8 @@ void cDvbTuner::Action(void)
+                tunerStatus = SetFrontend() ? tsPositioning : tsIdle;
+                continue;
+           case tsPositioning:
+-               if (positioner) {
+-                  if (positioner->IsMoving())
++               if (cPositioner *p = positioner) {
++                  if (p->IsMoving())
+                      break; // we want the TimedWait() below!
+                   else if (diseqcOffset) {
+                      lastDiseqc = NULL;
+@@ -1783,7 +1785,7 @@ void cDvbTuner::Action(void)
+                   continue;
+                   }
+                break;
+-          default: esyslog("ERROR: unknown tuner status %d", tunerStatus);
++          default: esyslog("ERROR: unknown tuner status %d", tunerStatus.load());
+           }
+         newSet.TimedWait(mutex, WaitTime);
+         }
+--- a/dvbdevice.h
++++ b/dvbdevice.h
+@@ -12,6 +12,7 @@
+ 
+ #include <linux/dvb/frontend.h>
+ #include <linux/dvb/version.h>
++#include <atomic>
+ #include "device.h"
+ 
+ #define DVBAPIVERSION (DVB_API_VERSION << 8 | DVB_API_VERSION_MINOR)
+@@ -185,7 +186,7 @@ private:
+   bool checkTsBuffer;
+   static cMutex bondMutex;
+   cDvbDevice *bondedDevice;
+-  mutable bool needsDetachBondedReceivers;
++  mutable std::atomic<bool> needsDetachBondedReceivers; // set by ProvidesChannel() on whichever thread asks
+ public:
+   cDvbDevice(int Adapter, int Frontend);
+   virtual ~cDvbDevice() override;

diff --git a/vdr-09-sections-sdt-atomics.patch b/vdr-09-sections-sdt-atomics.patch
deleted file mode 100644
index 2b96cdf..0000000
--- a/vdr-09-sections-sdt-atomics.patch
+++ /dev/null
@@ -1,35 +0,0 @@
-From: Dirk Nehring <dnehring@gmx.net>
-Subject: [PATCH] sections, sdt: make the section handler's status flags atomic
-
-cSectionHandler::SetStatus() changes on/waitForLock/flush under the
-thread lock, but Action() reads them for its poll() timeout and resets
-'flush' outside of it. cSdtFilter's transponderState is set by the
-section handler thread and read by the tuner thread through
-TransponderWrong().
-
----
---- a/sdt.h
-+++ b/sdt.h
-@@ -24,7 +24,7 @@ private:
-   int lastNid;
-   int lastTid;
-   cPatFilter *patFilter;
--  enum eTransponderState transponderState;
-+  std::atomic<eTransponderState> transponderState; // set by the section handler thread, read by the tuner thread
- protected:
-   virtual void Process(u_short Pid, u_char Tid, const u_char *Data, int Length) override;
- public:
---- a/sections.h
-+++ b/sections.h
-@@ -26,8 +26,9 @@ private:
-   cSectionHandlerPrivate *shp;
-   cDevice *device;
-   int statusCount;
--  bool on, waitForLock;
--  bool flush;
-+  // SetStatus() changes these under the thread lock, Action() also uses them outside of it:
-+  std::atomic<bool> on, waitForLock;
-+  std::atomic<bool> flush;
-   bool startFilters;
-   cTimeMs flushTimer;
-   cList<cFilter> filters;

diff --git a/vdr-10-device-state-atomics.patch b/vdr-10-device-state-atomics.patch
new file mode 100644
index 0000000..f855fcc
--- /dev/null
+++ b/vdr-10-device-state-atomics.patch
@@ -0,0 +1,124 @@
+From: Dirk Nehring <dnehring@gmx.net>
+Subject: [PATCH] device, transfer: make the channel, track, volume and mute state atomic
+
+PlayTs() routes packets by currentAudioTrack and currentSubtitleTrack,
+and the skins read them through the getters, without a lock while other
+threads change them (user selection, PMT updates, channel switches).
+currentChannel and cTransferControl::receiverDevice are set by whichever
+thread switches the channel (e.g. SVDRP CHAN) and read everywhere
+through CurrentChannel(), ActualDevice() and ReceiverDevice().
+autoSelectPreferredSubtitleLanguage is set by EnsureSubtitleTrack() from
+the player thread's PMT parsing as well as from the main thread's
+channel switch. SetVolume() and ToggleMute() run on whichever thread
+handles the key or the SVDRP VOLU command, while skins and plugins read
+IsMute() and CurrentVolume().
+---
+--- a/device.c
++++ b/device.c
+@@ -72,7 +72,7 @@ bool cDeviceHook::DeviceProvidesEIT(const cDevice *Device) const
+ int cDevice::numDevices = 0;
+ int cDevice::useDevice = 0;
+ int cDevice::nextCardIndex = 0;
+-int cDevice::currentChannel = 1;
++std::atomic<int> cDevice::currentChannel(1);
+ cDevice *cDevice::device[MAXDEVICES] = { NULL };
+ cDevice *cDevice::primaryDevice = NULL;
+ cList<cDeviceHook> cDevice::deviceHooks;
+@@ -1118,7 +1118,7 @@ void cDevice::SetVolume(int Volume, bool Absolute)
+   volume = constrain(int(floor((Absolute ? Volume : volume + Volume) / VolumeDelta + 0.5) * VolumeDelta), 0, MAXVOLUME);
+   SetVolumeDevice(MAXVOLUME - int(pow(1.0 - pow(double(volume) / MAXVOLUME, VolumeLinearize), 1.0 / VolumeLinearize) * MAXVOLUME));
+   Absolute |= mute;
+-  cStatus::MsgSetVolume(Absolute ? volume : volume - OldVolume, Absolute);
++  cStatus::MsgSetVolume(Absolute ? volume.load() : volume - OldVolume, Absolute);
+   if (volume > 0) {
+      mute = false;
+      Audios.MuteAudio(mute);
+--- a/device.h
++++ b/device.h
+@@ -267,7 +267,7 @@ private:
+   time_t occupiedTimeout;
+   int occupiedPriority;
+ protected:
+-  static int currentChannel;
++  static std::atomic<int> currentChannel; // set by whichever thread switches the channel, read by any
+ public:
+   virtual bool ProvidesSource(int Source) const;
+          ///< Returns true if this device can provide the given source.
+@@ -369,7 +369,7 @@ protected:
+   virtual bool SetChannelDevice(const cChannel *Channel, bool LiveView);
+          ///< Sets the device to the given channel (actual physical setup).
+ public:
+-  static int CurrentChannel(void) { return primaryDevice ? currentChannel : 0; }
++  static int CurrentChannel(void) { return primaryDevice ? currentChannel.load() : 0; }
+          ///< Returns the number of the current channel on the primary device.
+   static void SetCurrentChannel(int ChannelNumber) { currentChannel = ChannelNumber; }
+          ///< Sets the number of the current channel on the primary device, without
+@@ -553,12 +553,13 @@ public:
+ 
+ private:
+   tTrackId availableTracks[ttMaxTrackTypes];
+-  eTrackType currentAudioTrack;
+-  eTrackType currentSubtitleTrack;
++  // read without a lock by PlayTs() and the getters, while other threads change them:
++  std::atomic<eTrackType> currentAudioTrack;
++  std::atomic<eTrackType> currentSubtitleTrack;
+   cMutex mutexCurrentAudioTrack;
+   cMutex mutexCurrentSubtitleTrack;
+   int currentAudioTrackMissingCount;
+-  bool autoSelectPreferredSubtitleLanguage;
++  std::atomic<bool> autoSelectPreferredSubtitleLanguage; // set by EnsureSubtitleTrack() on the player and main threads
+   bool keepTracks;
+   int pre_1_3_19_PrivateStream;
+ protected:
+@@ -624,8 +625,9 @@ public:
+ // Audio facilities
+ 
+ private:
+-  bool mute;
+-  int volume;
++  // changed by whichever thread handles the key or SVDRP command, read by skins and plugins:
++  std::atomic<bool> mute;
++  std::atomic<int> volume;
+ protected:
+   virtual int GetAudioChannelDevice(void);
+        ///< Gets the current audio channel, which is stereo (0), mono left (1) or
+@@ -639,7 +641,7 @@ protected:
+        ///< Only used by the original "full featured" DVB cards - do not use for new
+        ///< developments!
+ public:
+-  bool IsMute(void) const { return mute; }
++  bool IsMute(void) const { return mute.load(); }
+   bool ToggleMute(void);
+        ///< Turns the volume off or on and returns the new mute state.
+   int GetAudioChannel(void);
+@@ -651,7 +653,7 @@ public:
+   void SetVolume(int Volume, bool Absolute = false);
+        ///< Sets the volume to the given value, either absolutely or relative to
+        ///< the current volume.
+-  static int CurrentVolume(void) { return primaryDevice ? primaryDevice->volume : 0; }//XXX???
++  static int CurrentVolume(void) { return primaryDevice ? primaryDevice->volume.load() : 0; }//XXX???
+ 
+ // Player facilities
+ 
+--- a/transfer.c
++++ b/transfer.c
+@@ -75,7 +75,7 @@ void cTransfer::Receive(const uchar *Data, int Length)
+ 
+ // --- cTransferControl ------------------------------------------------------
+ 
+-cDevice *cTransferControl::receiverDevice = NULL;
++std::atomic<cDevice *> cTransferControl::receiverDevice(NULL);
+ 
+ cTransferControl::cTransferControl(cDevice *ReceiverDevice, const cChannel *Channel)
+ :cControl(NULL, true)
+--- a/transfer.h
++++ b/transfer.h
+@@ -31,7 +31,7 @@ public:
+ class cTransferControl : public cControl {
+ private:
+   cTransfer *transfer;
+-  static cDevice *receiverDevice;
++  static std::atomic<cDevice *> receiverDevice; // set and cleared by the switching thread, read by any
+ public:
+   cTransferControl(cDevice *ReceiverDevice, const cChannel *Channel);
+   ~cTransferControl();

diff --git a/vdr-10-svdrp-ready-atomic.patch b/vdr-10-svdrp-ready-atomic.patch
deleted file mode 100644
index 166935b..0000000
--- a/vdr-10-svdrp-ready-atomic.patch
+++ /dev/null
@@ -1,18 +0,0 @@
-From: Dirk Nehring <dnehring@gmx.net>
-Subject: [PATCH] svdrp: make the server handler's 'ready' flag atomic
-
-Action() sets it once the listening socket is up, while WaitUntilReady()
-polls it from the main thread.
-
----
---- a/svdrp.c
-+++ b/svdrp.c
-@@ -2785,7 +2785,7 @@ void SetSVDRPGrabImageDir(const char *GrabImageDir)
- 
- class cSVDRPServerHandler : public cThread {
- private:
--  bool ready;
-+  std::atomic<bool> ready; // set by Action(), polled by WaitUntilReady() in the main thread
-   cSocket tcpSocket;
-   cVector<cSVDRPServer *> serverConnections;
-   void HandleServerConnection(void);

diff --git a/vdr-11-dvbsubtitle-atomics.patch b/vdr-11-dvbsubtitle-atomics.patch
deleted file mode 100644
index 3cded8e..0000000
--- a/vdr-11-dvbsubtitle-atomics.patch
+++ /dev/null
@@ -1,43 +0,0 @@
-From: Dirk Nehring <dnehring@gmx.net>
-Subject: [PATCH] dvbsubtitle: make 'frozen' and setupLevel atomic
-
-Action() reads 'frozen' outside the thread lock, while Freeze() (from
-cDevice::Play()/Freeze()) and Reset() set it in other threads.
-SetupChanged() increments the static setupLevel in the main thread,
-which Action() polls.
-
----
---- a/dvbsubtitle.c
-+++ b/dvbsubtitle.c
-@@ -1353,7 +1353,7 @@ void cDvbSubtitleBitmaps::DbgDump(int WindowWidth, int WindowHeight)
- 
- #define SUBTITLE_RETENTION 120 // seconds
- 
--int cDvbSubtitleConverter::setupLevel = 0;
-+std::atomic<int> cDvbSubtitleConverter::setupLevel(0);
- 
- cDvbSubtitleConverter::cDvbSubtitleConverter(void)
- :cThread("subtitle converter")
---- a/dvbsubtitle.h
-+++ b/dvbsubtitle.h
-@@ -12,6 +12,7 @@
- #ifndef __DVBSUBTITLE_H
- #define __DVBSUBTITLE_H
- 
-+#include <atomic>
- #include "osd.h"
- #include "thread.h"
- #include "tools.h"
-@@ -22,10 +23,10 @@ class cDvbSubtitleBitmaps;
- 
- class cDvbSubtitleConverter : public cThread {
- private:
--  static int setupLevel;
-+  static std::atomic<int> setupLevel; // incremented by SetupChanged() in the main thread, read by Action()
-   cDvbSubtitleAssembler *dvbSubtitleAssembler;
-   cOsd *osd;
--  bool frozen;
-+  std::atomic<bool> frozen; // set by Freeze() and Reset() in other threads, read by Action() without the lock
-   int ddsVersionNumber;
-   int displayWidth;
-   int displayHeight;

diff --git a/vdr-11-receiver-pids-atomic.patch b/vdr-11-receiver-pids-atomic.patch
new file mode 100644
index 0000000..206f141
--- /dev/null
+++ b/vdr-11-receiver-pids-atomic.patch
@@ -0,0 +1,27 @@
+From: Dirk Nehring <dnehring@gmx.net>
+Subject: [PATCH] receiver: make the PID array atomic
+
+The device thread scans an attached receiver's PIDs in WantsPid() while
+cCaPidReceiver (EMM PIDs) and cCamSlot::BuildCaPmts() (ECM PIDs) change
+them in other threads. Taking the device's receiver mutex there would
+invert the lock order against the CAM slot mutex, and a transiently
+inconsistent PID set only misroutes single TS packets at the moment of
+the change, so the entries are atomic instead.
+---
+--- a/receiver.c
++++ b/receiver.c
+@@ -95,3 +95,3 @@ void cReceiver::DelPid(int Pid)
+             for ( ; i < numPids; i++) // we also copy the terminating 0!
+-                pids[i] = pids[i + 1];
++                pids[i] = pids[i + 1].load();
+             numPids--;
+--- a/receiver.h
++++ b/receiver.h
+@@ -22,4 +22,5 @@ private:
+   int priority;
+-  int pids[MAXRECEIVEPIDS];
+-  int numPids;
++  // changed while attached (EMM/ECM PIDs), scanned by the device thread without a lock:
++  std::atomic<int> pids[MAXRECEIVEPIDS];
++  std::atomic<int> numPids;
+   time_t lastScrambledPacket;

diff --git a/vdr-12-device-camslot-atomic.patch b/vdr-12-device-camslot-atomic.patch
deleted file mode 100644
index d461537..0000000
--- a/vdr-12-device-camslot-atomic.patch
+++ /dev/null
@@ -1,109 +0,0 @@
-From: Dirk Nehring <dnehring@gmx.net>
-Subject: [PATCH] device: make the camSlot pointer atomic
-
-cCamSlot::Assign() sets it through SetCamSlot(), possibly in another
-thread's channel switch, while the receiver and play threads read it
-without a lock. ReleaseCamSlot(), SetChannel(), AttachReceiver() and
-Detach() loaded it more than once ('CamSlot() &&
-CamSlot()->WantsTsData()'), so it could turn NULL between check and use;
-they now act on one snapshot. AddPid()/DelPid() are converted by the
-patch that moves their CAM notification out of mutexPids.
-
----
---- a/device.c
-+++ b/device.c
-@@ -454,8 +454,10 @@ cDevice *cDevice::GetDeviceForTransponder(const cChannel *Channel, int Priority)
- 
- void cDevice::ReleaseCamSlot(void)
- {
--  if (camSlot && !camSlot->IsDecrypting() && !camSlot->IsActivating())
--     camSlot->Assign(NULL);
-+  if (cCamSlot *cs = camSlot) {
-+     if (!cs->IsDecrypting() && !cs->IsActivating())
-+        cs->Assign(NULL);
-+     }
- }
- 
- bool cDevice::HasCi(void)
-@@ -911,7 +913,8 @@ eSetChannelResult cDevice::SetChannel(const cChannel *Channel, bool LiveView)
- 
-   bool NeedsTransferMode = LiveView && Device != PrimaryDevice();
-   // If the CAM slot wants the TS data, we need to switch to Transfer Mode:
--  if (!NeedsTransferMode && LiveView && IsPrimaryDevice() && CamSlot() && CamSlot()->WantsTsData())
-+  cCamSlot *PrimaryCamSlot = CamSlot();
-+  if (!NeedsTransferMode && LiveView && IsPrimaryDevice() && PrimaryCamSlot && PrimaryCamSlot->WantsTsData())
-      NeedsTransferMode = true;
- 
-   eSetChannelResult Result = scrOk;
-@@ -935,8 +938,8 @@ eSetChannelResult cDevice::SetChannel(const cChannel *Channel, bool LiveView)
-         }
-      // Tell the camSlot about the channel switch and add all PIDs of this
-      // channel to it, for possible later decryption:
--     if (camSlot)
--        camSlot->AddChannel(Channel);
-+     if (cCamSlot *cs = camSlot)
-+        cs->AddChannel(Channel);
-      SetPowerSaveMode(false);
-      if (SetChannelDevice(Channel, LiveView)) {
-         // Start section handling:
-@@ -945,8 +948,8 @@ eSetChannelResult cDevice::SetChannel(const cChannel *Channel, bool LiveView)
-            sectionHandler->SetStatus(true);
-            }
-         // Start decrypting any PIDs that might have been set in SetChannelDevice():
--        if (camSlot)
--           camSlot->StartDecrypting();
-+        if (cCamSlot *cs = camSlot)
-+           cs->StartDecrypting();
-         }
-      else
-         Result = scrFailed;
-@@ -1926,20 +1929,21 @@ bool cDevice::AttachReceiver(cReceiver *Receiver)
-          Receiver->Activate(true);
-          Receiver->device = this;
-          receiver[i] = Receiver;
--         if (camSlot && Receiver->priority > MINPRIORITY) { // priority check to avoid an infinite loop with the CAM slot's caPidReceiver
--            camSlot->StartDecrypting();
--            if (camSlot->WantsTsData()) {
-+         cCamSlot *cs = camSlot;
-+         if (cs && Receiver->priority > MINPRIORITY) { // priority check to avoid an infinite loop with the CAM slot's caPidReceiver
-+            cs->StartDecrypting();
-+            if (cs->WantsTsData()) {
-                Receiver->lastEitInjection = 0;
-                Receiver->startEitInjection = time(NULL);
-                }
-             if (CamSlots.NumReadyMasterSlots() > 1) { // don't try different CAMs if there is only one
-                Receiver->startScrambleDetection = time(NULL);
-                Receiver->scramblingTimeout = TS_SCRAMBLING_TIMEOUT;
--               bool KnownToDecrypt = ChannelCamRelations.CamDecrypt(Receiver->ChannelID(), camSlot->MasterSlotNumber());
-+               bool KnownToDecrypt = ChannelCamRelations.CamDecrypt(Receiver->ChannelID(), cs->MasterSlotNumber());
-                if (KnownToDecrypt)
-                   Receiver->scramblingTimeout *= 9; // give it time to receive ECM/EMM (must be less than MAXBROKENTIMEOUT in recorder.c!)
-                if (Receiver->ChannelID().Valid())
--                  dsyslog("CAM %d: %sknown to decrypt channel %s (scramblingTimeout = %ds)", camSlot->MasterSlotNumber(), KnownToDecrypt ? "" : "not ", *Receiver->ChannelID().ToString(), Receiver->scramblingTimeout);
-+                  dsyslog("CAM %d: %sknown to decrypt channel %s (scramblingTimeout = %ds)", cs->MasterSlotNumber(), KnownToDecrypt ? "" : "not ", *Receiver->ChannelID().ToString(), Receiver->scramblingTimeout);
-                }
-             }
-          if (patFilter && Receiver->ChannelID().Valid())
-@@ -1971,9 +1975,9 @@ void cDevice::Detach(cReceiver *Receiver, bool ReleaseCam)
-   Receiver->Activate(false);
-   for (int n = 0; n < Receiver->numPids; n++)
-       DelPid(Receiver->pids[n]);
--  if (camSlot) {
-+  if (cCamSlot *cs = camSlot) {
-      if (Receiver->priority > MINPRIORITY) { // priority check to avoid an infinite loop with the CAM slot's caPidReceiver
--        camSlot->StartDecrypting();
-+        cs->StartDecrypting();
-         if (ReleaseCam)
-            ReleaseCamSlot();
-         }
---- a/device.h
-+++ b/device.h
-@@ -476,7 +476,7 @@ public:
- // Common Interface facilities:
- 
- private:
--  cCamSlot *camSlot;
-+  std::atomic<cCamSlot *> camSlot; // set by cCamSlot::Assign() in any thread, read without a lock
-   void ReleaseCamSlot(void);
-          ///< Releases the CAM slot if it is currently not used.
- public:

diff --git a/vdr-12-section-filter-atomics.patch b/vdr-12-section-filter-atomics.patch
new file mode 100644
index 0000000..21a6c2d
--- /dev/null
+++ b/vdr-12-section-filter-atomics.patch
@@ -0,0 +1,103 @@
+From: Dirk Nehring <dnehring@gmx.net>
+Subject: [PATCH] sections, sdt, eit, eitscan: make the flags and timestamps shared between threads atomic
+
+cSectionHandler::SetStatus() changes on, waitForLock and flush under
+the thread lock, but Action() reads them for its poll() timeout and
+resets 'flush' outside of it. cSdtFilter's transponderState is set by
+the section handler thread and read by the tuner thread through
+TransponderWrong(). SVDRP SCAN clears cEITScanner::lastActivity from
+the SVDRP thread while the main loop reads it in Active(), and SVDRP
+CLRE sets cEitFilter::disableUntil while the section handler threads
+test it in Process().
+---
+--- a/eit.c
++++ b/eit.c
+@@ -491,7 +491,7 @@ cTDT::cTDT(const u_char *Data)
+ 
+ // --- cEitFilter ------------------------------------------------------------
+ 
+-time_t cEitFilter::disableUntil = 0;
++std::atomic<time_t> cEitFilter::disableUntil(0);
+ 
+ cEitFilter::cEitFilter(void)
+ {
+--- a/eit.h
++++ b/eit.h
+@@ -10,6 +10,7 @@
+ #ifndef __EIT_H
+ #define __EIT_H
+ 
++#include <atomic>
+ #include "filter.h"
+ #include "tools.h"
+ 
+@@ -49,7 +50,7 @@ class cEitFilter : public cFilter {
+ private:
+   cMutex mutex;
+   cEitTablesHash eitTablesHash;
+-  static time_t disableUntil;
++  static std::atomic<time_t> disableUntil; // set by SVDRP CLRE, read by Process() on the section handler threads
+ protected:
+   virtual void Process(u_short Pid, u_char Tid, const u_char *Data, int Length) override;
+ public:
+--- a/eitscan.h
++++ b/eitscan.h
+@@ -10,6 +10,7 @@
+ #ifndef __EITSCAN_H
+ #define __EITSCAN_H
+ 
++#include <atomic>
+ #include <time.h>
+ #include "channels.h"
+ #include "config.h"
+@@ -24,7 +25,8 @@ private:
+          ScanTimeout = 20
+        };
+   bool paused;
+-  time_t lastScan, lastActivity;
++  time_t lastScan;
++  std::atomic<time_t> lastActivity; // cleared by ForceScan() from the SVDRP thread, read by Active() in the main loop
+   int currentChannel;
+   cScanList *scanList;
+   cTransponderList *transponderList;
+--- a/sdt.h
++++ b/sdt.h
+@@ -10,6 +10,7 @@
+ #ifndef __SDT_H
+ #define __SDT_H
+ 
++#include <atomic>
+ #include "filter.h"
+ #include "pat.h"
+ 
+@@ -24,7 +25,7 @@ private:
+   int lastNid;
+   int lastTid;
+   cPatFilter *patFilter;
+-  enum eTransponderState transponderState;
++  std::atomic<eTransponderState> transponderState; // set by the section handler thread, read by the tuner thread
+ protected:
+   virtual void Process(u_short Pid, u_char Tid, const u_char *Data, int Length) override;
+ public:
+--- a/sections.h
++++ b/sections.h
+@@ -10,6 +10,7 @@
+ #ifndef __SECTIONS_H
+ #define __SECTIONS_H
+ 
++#include <atomic>
+ #include <time.h>
+ #include "filter.h"
+ #include "thread.h"
+@@ -26,8 +27,9 @@ private:
+   cSectionHandlerPrivate *shp;
+   cDevice *device;
+   int statusCount;
+-  bool on, waitForLock;
+-  bool flush;
++  // SetStatus() changes these under the thread lock, Action() also uses them outside of it:
++  std::atomic<bool> on, waitForLock;
++  std::atomic<bool> flush;
+   bool startFilters;
+   cTimeMs flushTimer;
+   cList<cFilter> filters;

diff --git a/vdr-13-camslot-assign-lock-scope.patch b/vdr-13-camslot-assign-lock-scope.patch
deleted file mode 100644
index bea722a..0000000
--- a/vdr-13-camslot-assign-lock-scope.patch
+++ /dev/null
@@ -1,135 +0,0 @@
-From: Dirk Nehring <dnehring@gmx.net>
-Subject: [PATCH] ci: don't hold the CAM slot mutex across device calls in Assign()
-
-Assign() held the slot mutex while calling cDevice::Detach(),
-SetCamSlot() and AttachReceiver(), which take the device's receiver
-mutex and thread lock, while AttachReceiver() -> AddPid() ->
-cCamSlot::SetPid() takes the receiver mutex first and the slot mutex
-last. Two threads switching channels on CAM devices could deadlock. A
-new assignMutex serializes Assign(), and the slot mutex only guards the
-assignedDevice updates; Device() reads that without a lock, so it is
-atomic.
-
----
---- a/ci.c
-+++ b/ci.c
-@@ -2220,41 +2220,54 @@ cCamSlot *cCamSlot::MtdSpawn(void)
- 
- bool cCamSlot::Assign(cDevice *Device, bool Query)
- {
--  cMutexLock MutexLock(&mutex);
--  if (Device == assignedDevice)
--     return true;
--  if (ciAdapter) {
--     int OldDeviceNumber = 0;
--     if (assignedDevice && !Query) {
--        OldDeviceNumber = assignedDevice->DeviceNumber() + 1;
--        if (caPidReceiver)
--           assignedDevice->Detach(caPidReceiver);
--        assignedDevice->SetCamSlot(NULL);
--        assignedDevice = NULL;
--        }
--     if (ciAdapter->Assign(Device, true)) {
--        if (!Query) {
--           StopDecrypting();
--           if (ciAdapter->Assign(Device)) {
--              if (Device) {
--                 Device->SetCamSlot(this);
--                 assignedDevice = Device;
--                 if (caPidReceiver) {
--                    caPidReceiver->Reset();
--                    Device->AttachReceiver(caPidReceiver);
--                    }
--                 dsyslog("CAM %d: assigned to device %d", MasterSlotNumber(), Device->DeviceNumber() + 1);
--                 }
--              else {
--                 CancelActivation();
--                 dsyslog("CAM %d: unassigned from device %d", MasterSlotNumber(), OldDeviceNumber);
-+  // 'mutex' isn't held across the cDevice calls below: they take the device's
-+  // receiver lock, under which AttachReceiver() -> AddPid() -> SetPid() takes
-+  // 'mutex'. Readers may briefly see no assigned device, which is harmless:
-+  cMutexLock AssignMutexLock(&assignMutex);
-+  cDevice *OldDevice = NULL;
-+  {
-+    cMutexLock MutexLock(&mutex);
-+    if (Device == assignedDevice)
-+       return true;
-+    if (!ciAdapter)
-+       return false;
-+    if (assignedDevice && !Query) {
-+       OldDevice = assignedDevice;
-+       assignedDevice = NULL;
-+       }
-+  }
-+  int OldDeviceNumber = 0;
-+  if (OldDevice) {
-+     OldDeviceNumber = OldDevice->DeviceNumber() + 1;
-+     if (caPidReceiver)
-+        OldDevice->Detach(caPidReceiver);
-+     OldDevice->SetCamSlot(NULL);
-+     }
-+  if (ciAdapter->Assign(Device, true)) {
-+     if (!Query) {
-+        StopDecrypting();
-+        if (ciAdapter->Assign(Device)) {
-+           if (Device) {
-+              Device->SetCamSlot(this);
-+              {
-+                cMutexLock MutexLock(&mutex);
-+                assignedDevice = Device;
-+              }
-+              if (caPidReceiver) {
-+                 caPidReceiver->Reset();
-+                 Device->AttachReceiver(caPidReceiver);
-                  }
-+              dsyslog("CAM %d: assigned to device %d", MasterSlotNumber(), Device->DeviceNumber() + 1);
-+              }
-+           else {
-+              CancelActivation();
-+              dsyslog("CAM %d: unassigned from device %d", MasterSlotNumber(), OldDeviceNumber);
-               }
--           else
--              return false;
-            }
--        return true;
-+        else
-+           return false;
-         }
-+     return true;
-      }
-   return false;
- }
-@@ -2264,8 +2277,8 @@ bool cCamSlot::Devices(cVector<int> &DeviceNumbers)
-   cMutexLock MutexLock(&mutex);
-   if (mtdHandler)
-      return mtdHandler->Devices(DeviceNumbers);
--  if (assignedDevice)
--     DeviceNumbers.Append(assignedDevice->DeviceNumber());
-+  if (cDevice *d = assignedDevice)
-+     DeviceNumbers.Append(d->DeviceNumber());
-   return DeviceNumbers.Size() > 0;
- }
- 
---- a/ci.h
-+++ b/ci.h
-@@ -10,6 +10,7 @@
- #ifndef __CI_H
- #define __CI_H
- 
-+#include <atomic>
- #include <stdint.h>
- #include <stdio.h>
- #include "channels.h"
-@@ -236,10 +237,11 @@ class cCamSlot : public cListObject {
-   friend class cMtdCamSlot;
- private:
-   cMutex mutex;
-+  cMutex assignMutex; // serializes Assign(), which can't hold 'mutex' across its cDevice calls
-   cCondVar processed;
-   cCiAdapter *ciAdapter;
-   cCamSlot *masterSlot;
--  cDevice *assignedDevice;
-+  std::atomic<cDevice *> assignedDevice; // Device() reads it without the mutex
-   cCaPidReceiver *caPidReceiver;
-   cCaActivationReceiver *caActivationReceiver;
-   int slotIndex;

diff --git a/vdr-13-shared-flags-atomic.patch b/vdr-13-shared-flags-atomic.patch
new file mode 100644
index 0000000..f189fd5
--- /dev/null
+++ b/vdr-13-shared-flags-atomic.patch
@@ -0,0 +1,117 @@
+From: Dirk Nehring <dnehring@gmx.net>
+Subject: [PATCH] svdrp, dvbsubtitle, recording, recorder: make the remaining shared flags atomic
+
+Each of these is set by one thread and read by another without a lock:
+- cSVDRPServerHandler::ready: set by Action() once the listening socket
+  is up, polled by WaitUntilReady() in the main thread.
+- cDvbSubtitleConverter::frozen: set by Freeze() and Reset() in other
+  threads, read by Action() outside the thread lock; setupLevel:
+  incremented by SetupChanged() in the main thread, polled by Action().
+- cRecordings::lastUpdate: stored by Update() from whichever thread asks
+  for a rescan (SVDRP UPDR, the cutter, timers), read by the main loop's
+  NeedsUpdate().
+- cRecorder::working: set and cleared by the recorder thread, tested by
+  the receiver thread in Receive() for every packet.
+---
+--- a/dvbsubtitle.c
++++ b/dvbsubtitle.c
+@@ -1356,7 +1356,7 @@ void cDvbSubtitleBitmaps::DbgDump(int WindowWidth, int WindowHeight)
+ 
+ #define SUBTITLE_RETENTION 120 // seconds
+ 
+-int cDvbSubtitleConverter::setupLevel = 0;
++std::atomic<int> cDvbSubtitleConverter::setupLevel(0);
+ 
+ cDvbSubtitleConverter::cDvbSubtitleConverter(void)
+ :cThread("subtitle converter")
+--- a/dvbsubtitle.h
++++ b/dvbsubtitle.h
+@@ -12,6 +12,7 @@
+ #ifndef __DVBSUBTITLE_H
+ #define __DVBSUBTITLE_H
+ 
++#include <atomic>
+ #include "osd.h"
+ #include "thread.h"
+ #include "tools.h"
+@@ -22,10 +23,10 @@ class cDvbSubtitleBitmaps;
+ 
+ class cDvbSubtitleConverter : public cThread {
+ private:
+-  static int setupLevel;
++  static std::atomic<int> setupLevel; // incremented by SetupChanged() in the main thread, read by Action()
+   cDvbSubtitleAssembler *dvbSubtitleAssembler;
+   cOsd *osd;
+-  bool frozen;
++  std::atomic<bool> frozen; // set by Freeze() and Reset() in other threads, read by Action() without the lock
+   int ddsVersionNumber;
+   int displayWidth;
+   int displayHeight;
+--- a/recorder.h
++++ b/recorder.h
+@@ -10,6 +10,7 @@
+ #ifndef __RECORDER_H
+ #define __RECORDER_H
+ 
++#include <atomic>
+ #include "receiver.h"
+ #include "recording.h"
+ #include "remux.h"
+@@ -26,7 +27,7 @@ private:
+   cIndexFile *index;
+   cUnbufferedFile *recordFile;
+   char *recordingName;
+-  bool working;
++  std::atomic<bool> working; // set by the recorder thread, read by the receiver thread in Receive()
+   bool firstIframeSeen;
+   off_t fileSize;
+   time_t lastDiskSpaceCheck;
+--- a/recording.c
++++ b/recording.c
+@@ -1742,7 +1742,7 @@ cRecordings cRecordings::deletedRecordings(true);
+ int cRecordings::lastRecordingId = 0;
+ char *cRecordings::updateFileName = NULL;
+ cVideoDirectoryScannerThread *cRecordings::videoDirectoryScannerThread = NULL;
+-time_t cRecordings::lastUpdate = 0;
++std::atomic<time_t> cRecordings::lastUpdate(0);
+ 
+ cRecordings::cRecordings(bool Deleted)
+ :cList<cRecording>(Deleted ? "4 DelRecs" : "3 Recordings")
+--- a/recording.h
++++ b/recording.h
+@@ -10,6 +10,7 @@
+ #ifndef __RECORDING_H
+ #define __RECORDING_H
+ 
++#include <atomic>
+ #include <time.h>
+ #include "channels.h"
+ #include "config.h"
+@@ -276,7 +277,7 @@ private:
+   static cRecordings deletedRecordings;
+   static int lastRecordingId;
+   static char *updateFileName;
+-  static time_t lastUpdate;
++  static std::atomic<time_t> lastUpdate; // written by Update() from any thread, polled by the main loop
+   static cVideoDirectoryScannerThread *videoDirectoryScannerThread;
+   static const char *UpdateFileName(void);
+ public:
+--- a/svdrp.c
++++ b/svdrp.c
+@@ -15,6 +15,7 @@
+ 
+ #include "svdrp.h"
+ #include <arpa/inet.h>
++#include <atomic>
+ #include <ctype.h>
+ #include <errno.h>
+ #include <fcntl.h>
+@@ -2785,7 +2786,7 @@ void SetSVDRPGrabImageDir(const char *GrabImageDir)
+ 
+ class cSVDRPServerHandler : public cThread {
+ private:
+-  bool ready;
++  std::atomic<bool> ready; // set by Action(), polled by WaitUntilReady() in the main thread
+   cSocket tcpSocket;
+   cVector<cSVDRPServer *> serverConnections;
+   void HandleServerConnection(void);

diff --git a/vdr-14-ci-dump-thread-local.patch b/vdr-14-ci-dump-thread-local.patch
new file mode 100644
index 0000000..dfafdb7
--- /dev/null
+++ b/vdr-14-ci-dump-thread-local.patch
@@ -0,0 +1,21 @@
+From: Dirk Nehring <dnehring@gmx.net>
+Subject: [PATCH] ci: make the TPDU dump switch thread-local
+
+cCiTransportConnection::Poll() and cCiDateTime::SendDateTime() switch
+DumpTPDUDataTransfer off and back on around the TPDU they send, in the
+CI adapter thread. cCamSlot::Write() reads it in whichever thread
+assigns the slot (e.g. SVDRP CHAN -> Assign() -> SendCaPmt()). As the
+switch is only meant for the TPDU the same thread sends, each thread
+now has its own.
+---
+--- a/ci.c
++++ b/ci.c
+@@ -28,7 +28,7 @@
+ #include "tools.h"
+ 
+ // Set these to 'true' for debug output:
+-static bool DumpTPDUDataTransfer = false;
++static thread_local bool DumpTPDUDataTransfer = false; // Poll() and cCiDateTime switch it off around their own TPDUs, while other threads write CA PMTs
+ static bool DebugProtocol = false;
+ static bool DumpPolls = false;
+ static bool DumpDateTime = false;

diff --git a/vdr-14-device-pid-notify-lock-scope.patch b/vdr-14-device-pid-notify-lock-scope.patch
deleted file mode 100644
index 321d8a6..0000000
--- a/vdr-14-device-pid-notify-lock-scope.patch
+++ /dev/null
@@ -1,211 +0,0 @@
-From: Dirk Nehring <dnehring@gmx.net>
-Subject: [PATCH] device: call cCamSlot::SetPid() and DetachAll() outside of mutexPids
-
-AddPid()/DelPid() called cCamSlot::SetPid(), which takes the mutexes of
-cCaPidReceiver and the CAM slot, and on errors DetachAll(), which takes
-mutexReceiver, while holding mutexPids. Those locks are held elsewhere
-while AddPid()/DelPid() take mutexPids: cCamSlot::BuildCaPmts() and
-cCaPidReceiver::AddEmmPid()/DelEmmPids() change their ECM and EMM PIDs
-through cReceiver -> cDevice::AddPid()/DelPid(), and AttachReceiver()
-holds mutexReceiver. The notification is now collected under the lock
-and delivered after releasing it.
-
----
---- a/device.c
-+++ b/device.c
-@@ -568,98 +568,111 @@ bool cDevice::HasPid(int Pid) const
- 
- bool cDevice::AddPid(int Pid, ePidType PidType, int StreamType)
- {
--  cMutexLock MutexLock(&mutexPids);
--  if (Pid || PidType == ptPcr) {
--     int n = -1;
--     int a = -1;
--     if (PidType != ptPcr) { // PPID always has to be explicit
--        for (int i = 0; i < MAXPIDHANDLES; i++) {
--            if (i != ptPcr) {
--               if (pidHandles[i].pid == Pid)
--                  n = i;
--               else if (a < 0 && i >= ptOther && !pidHandles[i].used)
--                  a = i;
--               }
--            }
--        }
--     if (n >= 0) {
--        // The Pid is already in use
--        if (++pidHandles[n].used == 2 && n <= ptTeletext) {
--           // It's a special PID that may have to be switched into "tap" mode
--           PRINTPIDS("A");
--           if (!SetPid(&pidHandles[n], n, true)) {
--              esyslog("ERROR: can't set PID %d on device %d", Pid, DeviceNumber() + 1);
--              if (PidType <= ptTeletext)
--                 DetachAll(Pid);
--              DelPid(Pid, PidType);
--              return false;
-+  // cCamSlot::SetPid() and DetachAll() are called after releasing mutexPids:
-+  // the locks they take are held while calling AddPid() elsewhere (the CAM
-+  // slot's and cCaPidReceiver's mutexes when adding ECM/EMM PIDs, mutexReceiver
-+  // in AttachReceiver()):
-+  cCamSlot *NotifySlot = NULL;
-+  bool Failed = false;
-+  {
-+    cMutexLock MutexLock(&mutexPids);
-+    if (Pid || PidType == ptPcr) {
-+       int n = -1;
-+       int a = -1;
-+       if (PidType != ptPcr) { // PPID always has to be explicit
-+          for (int i = 0; i < MAXPIDHANDLES; i++) {
-+              if (i != ptPcr) {
-+                 if (pidHandles[i].pid == Pid)
-+                    n = i;
-+                 else if (a < 0 && i >= ptOther && !pidHandles[i].used)
-+                    a = i;
-+                 }
-               }
--           if (camSlot)
--              camSlot->SetPid(Pid, true);
--           }
--        PRINTPIDS("a");
--        return true;
--        }
--     else if (PidType < ptOther) {
--        // The Pid is not yet in use and it is a special one
--        n = PidType;
--        }
--     else if (a >= 0) {
--        // The Pid is not yet in use and we have a free slot
--        n = a;
--        }
--     else {
--        esyslog("ERROR: no free slot for PID %d on device %d", Pid, DeviceNumber() + 1);
--        return false;
--        }
--     if (n >= 0) {
--        pidHandles[n].pid = Pid;
--        pidHandles[n].streamType = StreamType;
--        pidHandles[n].used = 1;
--        PRINTPIDS("C");
--        if (!SetPid(&pidHandles[n], n, true)) {
--           esyslog("ERROR: can't set PID %d on device %d", Pid, DeviceNumber() + 1);
--           if (PidType <= ptTeletext)
--              DetachAll(Pid);
--           DelPid(Pid, PidType);
--           return false;
--           }
--        if (camSlot)
--           camSlot->SetPid(Pid, true);
--        }
-+          }
-+       if (n >= 0) {
-+          // The Pid is already in use
-+          if (++pidHandles[n].used == 2 && n <= ptTeletext) {
-+             // It's a special PID that may have to be switched into "tap" mode
-+             PRINTPIDS("A");
-+             if (!SetPid(&pidHandles[n], n, true)) {
-+                esyslog("ERROR: can't set PID %d on device %d", Pid, DeviceNumber() + 1);
-+                Failed = true;
-+                }
-+             else
-+                NotifySlot = camSlot;
-+             }
-+          PRINTPIDS("a");
-+          }
-+       else {
-+          if (PidType < ptOther) {
-+             // The Pid is not yet in use and it is a special one
-+             n = PidType;
-+             }
-+          else if (a >= 0) {
-+             // The Pid is not yet in use and we have a free slot
-+             n = a;
-+             }
-+          else {
-+             esyslog("ERROR: no free slot for PID %d on device %d", Pid, DeviceNumber() + 1);
-+             return false;
-+             }
-+          pidHandles[n].pid = Pid;
-+          pidHandles[n].streamType = StreamType;
-+          pidHandles[n].used = 1;
-+          PRINTPIDS("C");
-+          if (!SetPid(&pidHandles[n], n, true)) {
-+             esyslog("ERROR: can't set PID %d on device %d", Pid, DeviceNumber() + 1);
-+             Failed = true;
-+             }
-+          else
-+             NotifySlot = camSlot;
-+          }
-+       }
-+  }
-+  if (Failed) {
-+     if (PidType <= ptTeletext)
-+        DetachAll(Pid);
-+     DelPid(Pid, PidType);
-+     return false;
-      }
-+  if (NotifySlot)
-+     NotifySlot->SetPid(Pid, true);
-   return true;
- }
- 
- void cDevice::DelPid(int Pid, ePidType PidType)
- {
--  cMutexLock MutexLock(&mutexPids);
--  if (Pid || PidType == ptPcr) {
--     int n = -1;
--     if (PidType == ptPcr)
--        n = PidType; // PPID always has to be explicit
--     else {
--        for (int i = 0; i < MAXPIDHANDLES; i++) {
--            if (pidHandles[i].pid == Pid) {
--               n = i;
--               break;
--               }
--            }
--        }
--     if (n >= 0 && pidHandles[n].used) {
--        PRINTPIDS("D");
--        if (--pidHandles[n].used < 2) {
--           SetPid(&pidHandles[n], n, false);
--           if (pidHandles[n].used == 0) {
--              pidHandles[n].handle = -1;
--              pidHandles[n].pid = 0;
--              if (camSlot)
--                 camSlot->SetPid(Pid, false);
-+  cCamSlot *NotifySlot = NULL; // notified after releasing mutexPids, see AddPid()
-+  {
-+    cMutexLock MutexLock(&mutexPids);
-+    if (Pid || PidType == ptPcr) {
-+       int n = -1;
-+       if (PidType == ptPcr)
-+          n = PidType; // PPID always has to be explicit
-+       else {
-+          for (int i = 0; i < MAXPIDHANDLES; i++) {
-+              if (pidHandles[i].pid == Pid) {
-+                 n = i;
-+                 break;
-+                 }
-               }
--           }
--        PRINTPIDS("E");
--        }
--     }
-+          }
-+       if (n >= 0 && pidHandles[n].used) {
-+          PRINTPIDS("D");
-+          if (--pidHandles[n].used < 2) {
-+             SetPid(&pidHandles[n], n, false);
-+             if (pidHandles[n].used == 0) {
-+                pidHandles[n].handle = -1;
-+                pidHandles[n].pid = 0;
-+                NotifySlot = camSlot;
-+                }
-+             }
-+          PRINTPIDS("E");
-+          }
-+       }
-+  }
-+  if (NotifySlot)
-+     NotifySlot->SetPid(Pid, false);
- }
- 
- bool cDevice::SetPid(cPidHandle *Handle, int Type, bool On)

diff --git a/vdr-15-channels-obsolete-name.patch b/vdr-15-channels-obsolete-name.patch
new file mode 100644
index 0000000..4831ddf
--- /dev/null
+++ b/vdr-15-channels-obsolete-name.patch
@@ -0,0 +1,35 @@
+From: Dirk Nehring <dnehring@gmx.net>
+Subject: [PATCH] channels: mark obsolete channels without switching Setup.ShowChannelNamesWithSource
+
+cChannels::MarkObsoleteChannels() switches the setting off and back on
+around the rename, in the section handler thread, to get the plain
+names from Name() and ShortName(), while cChannel::Name() reads the
+setting in any thread (e.g. the tuner thread for its log messages).
+cChannels now reads the plain names directly.
+---
+--- a/channels.c
++++ b/channels.c
+@@ -1125,11 +1125,8 @@ bool cChannels::MarkObsoleteChannels(int Source, int Nid, int Tid)
+   bool ChannelsModified = false;
+   for (cChannel *Channel = First(); Channel; Channel = Next(Channel)) {
+       if (time(NULL) - Channel->Seen() > CHANNELTIMEOBSOLETE && Channel->Source() == Source && Channel->Nid() == Nid && Channel->Tid() == Tid && Channel->Rid() == 0) {
+-         int OldShowChannelNamesWithSource = Setup.ShowChannelNamesWithSource;
+-         Setup.ShowChannelNamesWithSource = 0;
+-         if (!endswith(Channel->Name(), CHANNELMARKOBSOLETE))
+-            ChannelsModified |= Channel->SetName(cString::sprintf("%s %s", Channel->Name(), CHANNELMARKOBSOLETE), Channel->ShortName(), cString::sprintf("%s %s", CHANNELMARKOBSOLETE, Channel->Provider()));
+-         Setup.ShowChannelNamesWithSource = OldShowChannelNamesWithSource;
++         if (!endswith(Channel->name, CHANNELMARKOBSOLETE)) // the plain names, whatever Setup.ShowChannelNamesWithSource says
++            ChannelsModified |= Channel->SetName(cString::sprintf("%s %s", Channel->name, CHANNELMARKOBSOLETE), Channel->shortName, cString::sprintf("%s %s", CHANNELMARKOBSOLETE, Channel->Provider()));
+          }
+       }
+   return ChannelsModified;
+--- a/channels.h
++++ b/channels.h
+@@ -89,6 +89,7 @@ class cChannel : public cListObject {
+   friend class cMenuEditChannel;
+   friend class cMenuSetupMisc;
+   friend class cDvbSourceParam;
++  friend class cChannels; // MarkObsoleteChannels() renames with the plain names
+ private:
+   static cString ToText(const cChannel *Channel);
+   char *name;

diff --git a/vdr-15-control-mutex-null.patch b/vdr-15-control-mutex-null.patch
deleted file mode 100644
index 653304c..0000000
--- a/vdr-15-control-mutex-null.patch
+++ /dev/null
@@ -1,31 +0,0 @@
-From: Dirk Nehring <dnehring@gmx.net>
-Subject: [PATCH] player: don't keep the control mutex locked when Control() returns NULL
-
-cControl::Control() left the caller's cMutexLock locked even when it
-returned NULL. The main loop holds that lock across its whole key
-dispatch, where cDisplayChannel takes the Channels lock, while
-cControl::Shutdown() is called with the Channels lock held
-(cChannels::SwitchTo() -> cDevice::SwitchChannel()): a lock order
-inversion, with no control to protect. The mutex now stays locked only
-when a control is returned.
-
----
---- a/player.c
-+++ b/player.c
-@@ -77,8 +77,14 @@ cControl *cControl::Control(cMutexLock &MutexLock, bool Hidden, bool *LockedOthe
-   int Timeout = cThread::IsMainThread() ? 0 : CONTROL_LOCK_TIMEOUT;
-   if (LockedOtherwise)
-      *LockedOtherwise = false;
--  if (MutexLock.Lock(&mutex, Timeout, LockedOtherwise))
--     return (control && (!control->hidden || Hidden)) ? control : NULL;
-+  // Only a control needs the caller to keep the mutex locked. The main loop holds
-+  // it across its key dispatch, which takes the Channels lock, while
-+  // cControl::Shutdown() is called with the Channels lock held:
-+  cMutexLock ControlMutexLock;
-+  if (ControlMutexLock.Lock(&mutex, Timeout, LockedOtherwise)) {
-+     if (control && (!control->hidden || Hidden) && MutexLock.Lock(&mutex)) // recursive, stays locked for the caller
-+        return control;
-+     }
-   return NULL;
- }
- 

diff --git a/vdr-16-numtracks-lock.patch b/vdr-16-numtracks-lock.patch
new file mode 100644
index 0000000..048a59d
--- /dev/null
+++ b/vdr-16-numtracks-lock.patch
@@ -0,0 +1,32 @@
+From: Dirk Nehring <dnehring@gmx.net>
+Subject: [PATCH] device: count the available tracks under the track mutex
+
+The audio and subtitle track menus (cDisplayTracks::Create() and
+cDisplaySubtitleTracks::Create()) ask NumAudioTracks() and
+NumSubtitleTracks() on the main thread, which read the ids in
+cDevice::availableTracks[] without a lock. Meanwhile a player announces
+its tracks through SetAvailableTrack() with every PES packet and a channel
+switch clears them in ClrAvailableTracks(), both under
+mutexCurrentAudioTrack. ThreadSanitizer reported this with the dvd plugin
+when the audio track menu was opened during a replay.
+
+NumTracks() now takes mutexCurrentAudioTrack as well; it is mutable
+because NumTracks() is const. Nothing else is called while it is held,
+and since the mutex is recursive, SetAvailableTrack() can still call
+NumAudioTracks().
+---
+--- a/device.c
++++ b/device.c
+@@ -1196,6 +1196,7 @@ bool cDevice::GetTrackId(eTrackType Type, tTrackId &TrackId)
+ 
+ int cDevice::NumTracks(eTrackType FirstTrack, eTrackType LastTrack) const
+ {
++  cMutexLock MutexLock(&mutexCurrentAudioTrack);
+   int n = 0;
+   for (int i = FirstTrack; i <= LastTrack; i++) {
+       if (availableTracks[i].id)
+--- a/device.h
++++ b/device.h
+@@ -559 +559 @@ private:
+-  cMutex mutexCurrentAudioTrack;
++  mutable cMutex mutexCurrentAudioTrack;

diff --git a/vdr-16-osd-deregister-before-delete.patch b/vdr-16-osd-deregister-before-delete.patch
deleted file mode 100644
index 6a71e4c..0000000
--- a/vdr-16-osd-deregister-before-delete.patch
+++ /dev/null
@@ -1,287 +0,0 @@
-From: Dirk Nehring <dnehring@gmx.net>
-Subject: [PATCH] osd: deregister an OSD from the global list before deleting it
-
-OSDs are deleted in different threads (skins in the main thread,
-subtitle converters in their own). ~cOsd() removed the OSD from Osds
-only after the derived destructor had run, so another thread's ~cOsd()
-could still call Osds[0]->SetActive() on it: a virtual call into a
-half-destroyed object. cOsd::Deregister() unlinks the OSD and activates
-the next one under the OSD mutex, and cOsd::Delete() deregisters before
-deleting. The core deletes its OSDs that way; ~cOsd() still deregisters
-for plugins that don't.
-
----
---- a/dvbsubtitle.c
-+++ b/dvbsubtitle.c
-@@ -1382,7 +1382,7 @@ cDvbSubtitleConverter::~cDvbSubtitleConverter()
- {
-   Cancel(3);
-   delete dvbSubtitleAssembler;
--  delete osd;
-+  cOsd::Delete(osd);
-   delete bitmaps;
-   delete pages;
- }
-@@ -1392,7 +1392,7 @@ void cDvbSubtitleConverter::SetVisible(bool Visible)
-   LOCK_THREAD;
-   visible = Visible;
-   if (!visible)
--     DELETENULL(osd);
-+     cOsd::Delete(osd);
-   endVisible = -1;
- }
- 
-@@ -1417,7 +1417,7 @@ void cDvbSubtitleConverter::Reset(void)
-   Lock();
-   pages->Clear();
-   current = NULL;
--  DELETENULL(osd);
-+  cOsd::Delete(osd);
-   frozen = false;
-   ddsVersionNumber = -1;
-   Unlock();
-@@ -1525,13 +1525,13 @@ void cDvbSubtitleConverter::Action(void)
-               int NewSetupLevel = setupLevel;
-               if (LastSetupLevel != NewSetupLevel) {
-                  dbgoutput("closing osd<br>\n");
--                 DELETENULL(osd);
-+                 cOsd::Delete(osd);
-                  }
-               LastSetupLevel = NewSetupLevel;
-               }
-            int64_t STC = cDevice::PrimaryDevice()->GetSTC();
-            if (osd && current && current->Timeout() * 1000 - PtsDeltaMs(STC, current->Pts()) <= 0)
--              DELETENULL(osd);
-+              cOsd::Delete(osd);
-            for (cDvbSubtitleBitmaps *sb = bitmaps->First(); sb; ) {
-                // Calculate the Delta between the STC (the current timestamp of the video)
-                // and the bitmap's PTS (the timestamp when the bitmap shall be presented).
-@@ -1550,10 +1550,10 @@ void cDvbSubtitleConverter::Action(void)
-                      if (endVisible >= 0 && PtsDeltaMs(STC, endVisible) > TEMPSUBTITLETAIL) {
-                         visible = false;
-                         endVisible = -1;
--                        DELETENULL(osd);
-+                        cOsd::Delete(osd);
-                         }
-                      else if (!current->HasBitmaps() || current->Timeout() * 1000 - PtsDeltaMs(STC, current->Pts()) <= 0)
--                        DELETENULL(osd);
-+                        cOsd::Delete(osd);
-                      else if (visible && AssertOsd()) {
-                         dbgoutput("showing bitmap #%d of %d<br>\n", current->Index() + 1, bitmaps->Count());
-                         current->Draw(osd);
---- a/osd.c
-+++ b/osd.c
-@@ -1939,6 +1939,12 @@ cOsd::~cOsd()
-      DestroyPixmap(savedPixmap);
-   for (int i = 0; i < pixmaps.Size(); i++)
-       delete pixmaps[i];
-+  Deregister(); // in case the owner didn't use Delete()
-+}
-+
-+void cOsd::Deregister(void)
-+{
-+  cMutexLock MutexLock(&mutex);
-   for (int i = 0; i < Osds.Size(); i++) {
-       if (Osds[i] == this) {
-          Osds.Remove(i);
-@@ -1949,6 +1955,15 @@ cOsd::~cOsd()
-       }
- }
- 
-+void cOsd::Delete(cOsd *&Osd)
-+{
-+  if (Osd) {
-+     Osd->Deregister();
-+     delete Osd;
-+     Osd = NULL;
-+     }
-+}
-+
- void cOsd::SetOsdPosition(int Left, int Top, int Width, int Height)
- {
-   osdLeft = Left;
---- a/osd.h
-+++ b/osd.h
-@@ -828,6 +828,14 @@ protected:
- public:
-   virtual ~cOsd();
-        ///< Shuts down the OSD.
-+  void Deregister(void);
-+       ///< Removes this OSD from the list of open OSDs and activates the next one.
-+       ///< An OSD shall be deregistered before it is deleted (see Delete()): while
-+       ///< its derived destructor runs, another thread deleting its own OSD could
-+       ///< otherwise still call SetActive() on it. ~cOsd() deregisters as well, for
-+       ///< code that doesn't.
-+  static void Delete(cOsd *&Osd);
-+       ///< Deregisters and deletes the given Osd (if any) and sets it to NULL.
-   static int OsdLeft(void) { return osdLeft ? osdLeft : Setup.OSDLeft; }
-   static int OsdTop(void) { return osdTop ? osdTop : Setup.OSDTop; }
-   static int OsdWidth(void) { return osdWidth ? osdWidth : Setup.OSDWidth; }
---- a/skinclassic.c
-+++ b/skinclassic.c
-@@ -111,7 +111,7 @@ cSkinClassicDisplayChannel::cSkinClassicDisplayChannel(bool WithInfo)
- 
- cSkinClassicDisplayChannel::~cSkinClassicDisplayChannel()
- {
--  delete osd;
-+  cOsd::Delete(osd);
- }
- 
- void cSkinClassicDisplayChannel::SetChannel(const cChannel *Channel, int Number)
-@@ -234,7 +234,7 @@ cSkinClassicDisplayMenu::cSkinClassicDisplayMenu(void)
- 
- cSkinClassicDisplayMenu::~cSkinClassicDisplayMenu()
- {
--  delete osd;
-+  cOsd::Delete(osd);
- }
- 
- void cSkinClassicDisplayMenu::DrawScrollbar(int Total, int Offset, int Shown, int Top, int Height, bool CanScrollUp, bool CanScrollDown)
-@@ -510,7 +510,7 @@ cSkinClassicDisplayReplay::cSkinClassicDisplayReplay(bool ModeOnly)
- 
- cSkinClassicDisplayReplay::~cSkinClassicDisplayReplay()
- {
--  delete osd;
-+  cOsd::Delete(osd);
- }
- 
- void cSkinClassicDisplayReplay::SetTitle(const char *Title)
-@@ -607,7 +607,7 @@ cSkinClassicDisplayVolume::cSkinClassicDisplayVolume(void)
- 
- cSkinClassicDisplayVolume::~cSkinClassicDisplayVolume()
- {
--  delete osd;
-+  cOsd::Delete(osd);
- }
- 
- void cSkinClassicDisplayVolume::SetVolume(int Current, int Total, bool Mute)
-@@ -685,7 +685,7 @@ cSkinClassicDisplayTracks::cSkinClassicDisplayTracks(const char *Title, int NumT
- 
- cSkinClassicDisplayTracks::~cSkinClassicDisplayTracks()
- {
--  delete osd;
-+  cOsd::Delete(osd);
- }
- 
- void cSkinClassicDisplayTracks::SetItem(const char *Text, int Index, bool Current)
-@@ -745,7 +745,7 @@ cSkinClassicDisplayMessage::cSkinClassicDisplayMessage(void)
- 
- cSkinClassicDisplayMessage::~cSkinClassicDisplayMessage()
- {
--  delete osd;
-+  cOsd::Delete(osd);
- }
- 
- void cSkinClassicDisplayMessage::SetMessage(eMessageType Type, const char *Text)
---- a/skinlcars.c
-+++ b/skinlcars.c
-@@ -477,7 +477,7 @@ cSkinLCARSDisplayChannel::~cSkinLCARSDisplayChannel()
- {
-   delete tallFont;
-   delete tinyFont;
--  delete osd;
-+  cOsd::Delete(osd);
- }
- 
- void cSkinLCARSDisplayChannel::DrawDate(void)
-@@ -956,7 +956,7 @@ cSkinLCARSDisplayMenu::~cSkinLCARSDisplayMenu()
- {
-   delete tallFont;
-   delete tinyFont;
--  delete osd;
-+  cOsd::Delete(osd);
- }
- 
- void cSkinLCARSDisplayMenu::SetMenuCategory(eMenuCategory MenuCategory)
-@@ -1882,7 +1882,7 @@ cSkinLCARSDisplayReplay::cSkinLCARSDisplayReplay(bool ModeOnly)
- 
- cSkinLCARSDisplayReplay::~cSkinLCARSDisplayReplay()
- {
--  delete osd;
-+  cOsd::Delete(osd);
- }
- 
- void cSkinLCARSDisplayReplay::DrawDate(void)
-@@ -2026,7 +2026,7 @@ cSkinLCARSDisplayVolume::cSkinLCARSDisplayVolume(void)
- 
- cSkinLCARSDisplayVolume::~cSkinLCARSDisplayVolume()
- {
--  delete osd;
-+  cOsd::Delete(osd);
- }
- 
- void cSkinLCARSDisplayVolume::SetVolume(int Current, int Total, bool Mute)
-@@ -2152,7 +2152,7 @@ cSkinLCARSDisplayTracks::cSkinLCARSDisplayTracks(const char *Title, int NumTrack
- 
- cSkinLCARSDisplayTracks::~cSkinLCARSDisplayTracks()
- {
--  delete osd;
-+  cOsd::Delete(osd);
- }
- 
- void cSkinLCARSDisplayTracks::SetItem(const char *Text, int Index, bool Current)
-@@ -2243,7 +2243,7 @@ cSkinLCARSDisplayMessage::cSkinLCARSDisplayMessage(void)
- 
- cSkinLCARSDisplayMessage::~cSkinLCARSDisplayMessage()
- {
--  delete osd;
-+  cOsd::Delete(osd);
- }
- 
- void cSkinLCARSDisplayMessage::SetMessage(eMessageType Type, const char *Text)
---- a/skinsttng.c
-+++ b/skinsttng.c
-@@ -259,7 +259,7 @@ cSkinSTTNGDisplayChannel::cSkinSTTNGDisplayChannel(bool WithInfo)
- 
- cSkinSTTNGDisplayChannel::~cSkinSTTNGDisplayChannel()
- {
--  delete osd;
-+  cOsd::Delete(osd);
- }
- 
- void cSkinSTTNGDisplayChannel::SetChannel(const cChannel *Channel, int Number)
-@@ -501,7 +501,7 @@ cSkinSTTNGDisplayMenu::cSkinSTTNGDisplayMenu(void)
- 
- cSkinSTTNGDisplayMenu::~cSkinSTTNGDisplayMenu()
- {
--  delete osd;
-+  cOsd::Delete(osd);
- }
- 
- void cSkinSTTNGDisplayMenu::DrawScrollbar(int Total, int Offset, int Shown, int Top, int Height, bool CanScrollUp, bool CanScrollDown)
-@@ -883,7 +883,7 @@ cSkinSTTNGDisplayReplay::cSkinSTTNGDisplayReplay(bool ModeOnly)
- 
- cSkinSTTNGDisplayReplay::~cSkinSTTNGDisplayReplay()
- {
--  delete osd;
-+  cOsd::Delete(osd);
- }
- 
- void cSkinSTTNGDisplayReplay::SetTitle(const char *Title)
-@@ -1006,7 +1006,7 @@ cSkinSTTNGDisplayVolume::cSkinSTTNGDisplayVolume(void)
- 
- cSkinSTTNGDisplayVolume::~cSkinSTTNGDisplayVolume()
- {
--  delete osd;
-+  cOsd::Delete(osd);
- }
- 
- void cSkinSTTNGDisplayVolume::SetVolume(int Current, int Total, bool Mute)
-@@ -1151,7 +1151,7 @@ cSkinSTTNGDisplayTracks::cSkinSTTNGDisplayTracks(const char *Title, int NumTrack
- 
- cSkinSTTNGDisplayTracks::~cSkinSTTNGDisplayTracks()
- {
--  delete osd;
-+  cOsd::Delete(osd);
- }
- 
- void cSkinSTTNGDisplayTracks::SetItem(const char *Text, int Index, bool Current)
-@@ -1258,7 +1258,7 @@ cSkinSTTNGDisplayMessage::cSkinSTTNGDisplayMessage(void)
- 
- cSkinSTTNGDisplayMessage::~cSkinSTTNGDisplayMessage()
- {
--  delete osd;
-+  cOsd::Delete(osd);
- }
- 
- void cSkinSTTNGDisplayMessage::SetMessage(eMessageType Type, const char *Text)

diff --git a/vdr-17-skins-locked-track-copy.patch b/vdr-17-skins-locked-track-copy.patch
deleted file mode 100644
index 069ddd6..0000000
--- a/vdr-17-skins-locked-track-copy.patch
+++ /dev/null
@@ -1,95 +0,0 @@
-From: Dirk Nehring <dnehring@gmx.net>
-Subject: [PATCH] device, skins: read the current track through a locked copy
-
-The skins' DrawTrack() read the audio track description through
-GetTrack(), a bare pointer into cDevice::availableTracks[], while a
-channel switch in another thread (e.g. SVDRP CHAN) clears and refills
-that table under mutexCurrentAudioTrack. cDevice::GetTrackId() copies
-the entry under that mutex.
-
----
---- a/device.c
-+++ b/device.c
-@@ -1179,6 +1179,16 @@ const tTrackId *cDevice::GetTrack(eTrackType Type)
-   return (ttNone < Type && Type < ttMaxTrackTypes) ? &availableTracks[Type] : NULL;
- }
- 
-+bool cDevice::GetTrackId(eTrackType Type, tTrackId &TrackId)
-+{
-+  cMutexLock MutexLock(&mutexCurrentAudioTrack);
-+  if (const tTrackId *Track = GetTrack(Type)) {
-+     TrackId = *Track;
-+     return true;
-+     }
-+  return false;
-+}
-+
- int cDevice::NumTracks(eTrackType FirstTrack, eTrackType LastTrack) const
- {
-   int n = 0;
---- a/device.h
-+++ b/device.h
-@@ -582,6 +582,11 @@ public:
-   const tTrackId *GetTrack(eTrackType Type);
-        ///< Returns a pointer to the given track id, or NULL if Type is not
-        ///< less than ttMaxTrackTypes.
-+  bool GetTrackId(eTrackType Type, tTrackId &TrackId);
-+       ///< Copies the given track id into TrackId and returns true, or returns
-+       ///< false if Type is not a valid track type. Unlike GetTrack() this may be
-+       ///< used while another thread switches the channel, which rewrites the
-+       ///< track table.
-   int NumTracks(eTrackType FirstTrack, eTrackType LastTrack) const;
-        ///< Returns the number of tracks in the given range that are currently
-        ///< available.
---- a/skinlcars.c
-+++ b/skinlcars.c
-@@ -492,10 +492,11 @@ void cSkinLCARSDisplayChannel::DrawDate(void)
- void cSkinLCARSDisplayChannel::DrawTrack(void)
- {
-   cDevice *Device = cDevice::PrimaryDevice();
--  const tTrackId *Track = Device->GetTrack(Device->GetCurrentAudioTrack());
--  if (Track ? strcmp(lastTrackId.description, Track->description) : *lastTrackId.description) {
--     osd->DrawText(xc03, yc07, Track ? Track->description : "", Theme.Color(clrTrackName), Theme.Color(clrBackground), cFont::GetFont(fontOsd), xc07 - xc03);
--     strn0cpy(lastTrackId.description, Track ? Track->description : "", sizeof(lastTrackId.description));
-+  tTrackId TrackId;
-+  bool Track = Device->GetTrackId(Device->GetCurrentAudioTrack(), TrackId);
-+  if (Track ? strcmp(lastTrackId.description, TrackId.description) : *lastTrackId.description) {
-+     osd->DrawText(xc03, yc07, Track ? TrackId.description : "", Theme.Color(clrTrackName), Theme.Color(clrBackground), cFont::GetFont(fontOsd), xc07 - xc03);
-+     strn0cpy(lastTrackId.description, Track ? TrackId.description : "", sizeof(lastTrackId.description));
-      }
- }
- 
-@@ -1897,10 +1898,11 @@ void cSkinLCARSDisplayReplay::DrawDate(void)
- void cSkinLCARSDisplayReplay::DrawTrack(void)
- {
-   cDevice *Device = cDevice::PrimaryDevice();
--  const tTrackId *Track = Device->GetTrack(Device->GetCurrentAudioTrack());
--  if (Track ? strcmp(lastTrackId.description, Track->description) : *lastTrackId.description) {
--     osd->DrawText(xp03, yp04, Track ? Track->description : "", Theme.Color(clrTrackName), Theme.Color(clrBackground), cFont::GetFont(fontOsd), xp07 - xp03);
--     strn0cpy(lastTrackId.description, Track ? Track->description : "", sizeof(lastTrackId.description));
-+  tTrackId TrackId;
-+  bool Track = Device->GetTrackId(Device->GetCurrentAudioTrack(), TrackId);
-+  if (Track ? strcmp(lastTrackId.description, TrackId.description) : *lastTrackId.description) {
-+     osd->DrawText(xp03, yp04, Track ? TrackId.description : "", Theme.Color(clrTrackName), Theme.Color(clrBackground), cFont::GetFont(fontOsd), xp07 - xp03);
-+     strn0cpy(lastTrackId.description, Track ? TrackId.description : "", sizeof(lastTrackId.description));
-      }
- }
- 
---- a/skinsttng.c
-+++ b/skinsttng.c
-@@ -338,10 +338,11 @@ void cSkinSTTNGDisplayChannel::Flush(void)
-            lastDate = date;
-            }
-         cDevice *Device = cDevice::PrimaryDevice();
--        const tTrackId *Track = Device->GetTrack(Device->GetCurrentAudioTrack());
--        if (Track ? strcmp(lastTrackId.description, Track->description) : *lastTrackId.description) {
--           osd->DrawText(x3 + TextFrame, y6, Track ? Track->description : "", Theme.Color(clrChannelName), frameColor, font, x4 - x3 - w - 2 * TextFrame);
--           strn0cpy(lastTrackId.description, Track ? Track->description : "", sizeof(lastTrackId.description));
-+        tTrackId TrackId;
-+        bool Track = Device->GetTrackId(Device->GetCurrentAudioTrack(), TrackId);
-+        if (Track ? strcmp(lastTrackId.description, TrackId.description) : *lastTrackId.description) {
-+           osd->DrawText(x3 + TextFrame, y6, Track ? TrackId.description : "", Theme.Color(clrChannelName), frameColor, font, x4 - x3 - w - 2 * TextFrame);
-+           strn0cpy(lastTrackId.description, Track ? TrackId.description : "", sizeof(lastTrackId.description));
-            }
-         int DeviceNumber = cDevice::ActualDevice()->DeviceNumber() + 1;
-         if (DeviceNumber != lastDeviceNumber || time(NULL) != lastSignalDisplay) {

diff --git a/vdr-18-tsbuffer-get-timeout.patch b/vdr-18-tsbuffer-get-timeout.patch
deleted file mode 100644
index da23b32..0000000
--- a/vdr-18-tsbuffer-get-timeout.patch
+++ /dev/null
@@ -1,23 +0,0 @@
-From: Dirk Nehring <dnehring@gmx.net>
-Subject: [PATCH] device: let the TS buffer consumer re-check every 10 ms
-
-cTSBuffer's ring signals its consumer only once it is 10% full, which
-live traffic rarely reaches, so cDevice::Action() waits for the 100 ms
-get timeout: the first packets of a new channel reach the receivers in
-100 ms steps, and a receiver that was told to stop notices it up to
-100 ms late. With 10 ms, the first video PES of a same-transponder zap
-arrived about 85 ms earlier (median); the extra wake-ups cost no
-measurable CPU time.
-
----
---- a/device.c
-+++ b/device.c
-@@ -2048,7 +2048,7 @@ cTSBuffer::cTSBuffer(int File, int Size, int DeviceNumber)
-   deviceNumber = DeviceNumber;
-   delivered = 0;
-   ringBuffer = new cRingBufferLinear(Size, TS_SIZE, true, "TS");
--  ringBuffer->SetTimeouts(100, 100);
-+  ringBuffer->SetTimeouts(100, 10); // the ring signals Get() only above 10% fill, too late for live TV
-   ringBuffer->SetIoThrottle();
-   Start();
- }

diff --git a/vdr-19-dvbplayer-pause-stuckateof.patch b/vdr-19-dvbplayer-pause-stuckateof.patch
deleted file mode 100644
index 3057b44..0000000
--- a/vdr-19-dvbplayer-pause-stuckateof.patch
+++ /dev/null
@@ -1,21 +0,0 @@
-From: Dirk Nehring <dnehring@gmx.net>
-Subject: [PATCH] dvbplayer: a pause at the end of a recording is no stuck STC
-
-While paused, Action() leaves the loop body with 'continue' before the
-end-of-recording handling, so its 'StuckAtEof = 0' for pmPause never
-runs. During the drain at the end StuckAtEof is set almost all the time
-(the loop runs every 3 ms, the STC moves once per frame), so after a
-pause there of more than MAXSTUCKATEOF seconds, Play ended the replay at
-once, and what the device still held was never shown.
-
----
---- a/dvbplayer.c
-+++ b/dvbplayer.c
-@@ -626,6 +626,7 @@ void cDvbPlayer::Action(void)
-                 }
-              }
-           else {
-+             StuckAtEof = 0; // the STC stands still while paused, which is no stall
-              Sleep = true;
-              continue;
-              }

diff --git a/vdr-20-dvbplayer-last-frame.patch b/vdr-20-dvbplayer-last-frame.patch
deleted file mode 100644
index 8c21719..0000000
--- a/vdr-20-dvbplayer-last-frame.patch
+++ /dev/null
@@ -1,46 +0,0 @@
-From: Dirk Nehring <dnehring@gmx.net>
-Subject: [PATCH] dvbplayer: don't end a replay when the STC reaches the last frame read
-
-A forward replay also stopped once the STC reached LastReadFrame, the
-last frame in decode order. With B-frames that isn't the last frame
-shown, so the device was still playing out the tail (80-100 ms with
-1080i H.264 or SD MPEG-2, a multiple of that in slow motion). Without
-the replay OSD this went unnoticed, since the main loop tore the replay
-down only up to a second later; with the OSD open it did so at once.
-Drain() now tells when the device has shown everything, and
-MAXSTUCKATEOF covers devices that don't implement it.
-
----
---- a/dvbplayer.c
-+++ b/dvbplayer.c
-@@ -485,7 +485,6 @@ void cDvbPlayer::Action(void)
-   bool WaitingForData = false;
-   time_t StuckAtEof = 0;
-   uint32_t LastStc = 0;
--  int LastReadFrame = -1;
-   int SwitchToPlayFrame = 0;
-   bool CutIn = false;
-   bool AtLastMark = false;
-@@ -590,7 +589,6 @@ void cDvbPlayer::Action(void)
-                    int r = nonBlockingFileReader->Result(&b);
-                    if (r > 0) {
-                       WaitingForData = false;
--                      LastReadFrame = readIndex;
-                       int64_t Pts = isPesRecording ? (PesHasPts(b) ? PesGetPts(b) : -1) : TsGetPts(b, r);
-                       readFrame = new cFrame(b, -r, ftUnknown, readIndex, Pts, readIndependent); // hands over b to the ringBuffer
-                       if (AtLastMark) {
-@@ -714,11 +712,9 @@ void cDvbPlayer::Action(void)
-                 StuckAtEof = time(NULL);
-              LastStc = Stc;
-              int Index = ptsIndex.FindIndex(Stc, playMode == pmStill);
--             if (playDir == pdForward && !SwitchToPlayFrame) {
--                if (Index >= LastReadFrame)
--                   break; // automatically stop at end of recording
--                }
--             else if (Index <= 0 || SwitchToPlayFrame && Index >= SwitchToPlayFrame)
-+             // The end of a forward replay is decided above: the last frame read isn't the
-+             // last one shown if there are B-frames.
-+             if ((playDir != pdForward || SwitchToPlayFrame) && (Index <= 0 || SwitchToPlayFrame && Index >= SwitchToPlayFrame))
-                 SwitchToPlay = true;
-              if (SwitchToPlay) {
-                 if (!SwitchToPlayFrame) {

diff --git a/vdr-21-dvbplayer-growing-recording.patch b/vdr-21-dvbplayer-growing-recording.patch
deleted file mode 100644
index 7ad0781..0000000
--- a/vdr-21-dvbplayer-growing-recording.patch
+++ /dev/null
@@ -1,77 +0,0 @@
-From: Dirk Nehring <dnehring@gmx.net>
-Subject: [PATCH] dvbplayer, recording: keep replaying a recording that is still being written
-
-Replaying a recording in progress hits eof whenever the recorder writes
-nothing for longer than cIndexFile's catch-up time, and draining the
-device there ended the replay while the recording went on. In forward
-play such an eof is now a stall (no drain, no timeout), and StuckAtEof
-is reset whenever a frame is played, so a stall doesn't count at the
-real end. Once the recording has ended, CatchUp() closes the index file
-instead of waiting the full catch-up time on every read past the end
-(the rest trickled out at about one frame per second, or not at all),
-which also makes IsStillRecording() say so.
-
----
---- a/dvbplayer.c
-+++ b/dvbplayer.c
-@@ -641,6 +641,7 @@ void cDvbPlayer::Action(void)
- 
-           if (playFrame) {
-              eof = false;
-+             StuckAtEof = 0; // a stall at the end of a growing recording must not count at its real end
-              if (!p) {
-                 p = playFrame->Data();
-                 pc = playFrame->Count();
-@@ -698,10 +699,12 @@ void cDvbPlayer::Action(void)
- 
-           if (eof || SwitchToPlayFrame) {
-              bool SwitchToPlay = false;
-+             // In a recording that is still being written, eof in forward play is only a stall:
-+             bool FinalEof = eof && (!index || !index->IsStillRecording() || playDir != pdForward);
-              uint32_t Stc = DeviceGetSTC();
-              if (playMode == pmPause)
-                 StuckAtEof = 0;
--             else if (eof && DeviceDrain() || StuckAtEof && time(NULL) - StuckAtEof > MAXSTUCKATEOF) {
-+             else if (FinalEof && DeviceDrain() || (!eof || FinalEof) && StuckAtEof && time(NULL) - StuckAtEof > MAXSTUCKATEOF) {
-                 if (playDir == pdForward)
-                    break; // automatically stop at end of recording
-                 SwitchToPlay = true;
---- a/recording.c
-+++ b/recording.c
-@@ -3044,11 +3044,13 @@ void cIndexFile::ConvertToPes(tIndexTs *IndexTs, int Count)
- bool cIndexFile::CatchUp(int Index)
- {
-   // returns true unless something really goes wrong, so that 'index' becomes NULL
-+  cMutexLock MutexLock(&mutex); // 'f' may be closed by another thread's CatchUp(), even while this one waits below
-   if (index && f >= 0) {
--     cMutexLock MutexLock(&mutex);
-      // Note that CatchUp() is triggered even if Index is 'last' (and thus valid).
-      // This is done to make absolutely sure we don't miss any data at the very end.
--     for (int i = 0; i <= MAXINDEXCATCHUP && (Index < 0 || Index >= last); i++) {
-+     for (int i = 0; f >= 0 && i <= MAXINDEXCATCHUP && (Index < 0 || Index >= last); i++) {
-+         // Checked before reading: the timer file is removed after the last index entry has been written.
-+         bool Ended = !StillRecording(*cString(*fileName, strrchr(*fileName, '/')));
-          struct stat buf;
-          if (fstat(f, &buf) == 0) {
-             int newLast = int(buf.st_size / sizeof(tIndexTs) - 1);
-@@ -3090,6 +3092,12 @@ bool cIndexFile::CatchUp(int Index)
-             LOG_ERROR_STR(*fileName);
-          if (Index < last)
-             break;
-+         if (Ended) {
-+            // nothing more will come, so don't wait for it on every read past the end
-+            close(f);
-+            f = -1;
-+            break;
-+            }
-          cCondVar CondVar;
-          CondVar.TimedWait(mutex, INDEXCATCHUPWAIT);
-          }
-@@ -3237,6 +3245,7 @@ int cIndexFile::Get(uint16_t FileNumber, off_t FileOffset)
- 
- bool cIndexFile::IsStillRecording(void)
- {
-+  cMutexLock MutexLock(&mutex); // CatchUp() closes 'f' once the recording has ended
-   return f >= 0;
- }
- 

diff --git a/vdr-22-plugins-html-draindevice.patch b/vdr-22-plugins-html-draindevice.patch
deleted file mode 100644
index 79de705..0000000
--- a/vdr-22-plugins-html-draindevice.patch
+++ /dev/null
@@ -1,37 +0,0 @@
-From: Dirk Nehring <dnehring@gmx.net>
-Subject: [PATCH] PLUGINS.html: describe the end of stream handling with DrainDevice()
-
-The contract of Drain() and DrainDevice() is only documented in device.h.
-Output plugin authors look for the functions a device implements in
-PLUGINS.html, where the replay section lists them.
-
----
---- a/PLUGINS.html
-+++ b/PLUGINS.html
-@@ -1962,6 +1962,26 @@ virtual void SetVideoFormat(bool VideoFormat16_9);
- virtual void SetVolumeDevice(int Volume);
- </pre></td></tr></table><p>
- 
-+<div class="modified">
-+<b>End of stream</b>
-+<p>
-+When a player has delivered the last data of a stream, it calls <tt>Drain()</tt>
-+repeatedly until it returns <tt>true</tt>. <tt>Drain()</tt> first plays out the PES
-+data that <tt>PlayTs()</tt> still holds back, and then calls
-+
-+<p><table><tr><td class="code"><pre>
-+virtual bool DrainDevice(void);
-+</pre></td></tr></table><p>
-+
-+which a device implements to play out all data it still holds in its buffers and
-+decoders, without repeating or discarding anything. It must not block, shall return
-+<tt>true</tt> once the last frame has actually been played out, and <tt>GetSTC()</tt>
-+must keep advancing until then. <tt>Clear()</tt> and <tt>SetPlayMode()</tt> cancel
-+the draining. A device that buffers data in its own <tt>PlayTsVideo()</tt>,
-+<tt>PlayTsAudio()</tt> or <tt>PlayTsSubtitle()</tt> plays out that data here, too.
-+The default implementation calls the deprecated <tt>Flush()</tt>.
-+</div>
-+
- <p>
- <b>Section Filtering</b>
- <p>

diff --git a/vdr-README.package b/vdr-README.package
index 5965d64..fb931e4 100644
--- a/vdr-README.package
+++ b/vdr-README.package
@@ -60,9 +60,47 @@ additional VDR specific scripts such as those needed by some plugins,
 or things executed from commands.conf or reccmds.conf can be dropped
 there instead of having to pollute the usual system $PATH with them.
 
+Hooks
+-----
+
+VDR calls a program when it wants to shut the machine down (--shutdown)
+and at each step of a recording's life (--record); see "Automatic
+shutdown" and "Executing commands before and after a recording" in
+INSTALL.  /etc/sysconfig/vdr enables both packaged hooks:
+
+vdr-shutdown.sh runs the executable files in /etc/vdr/shutdown-hooks.d
+with VDR's five arguments (next wakeup time, seconds until then, channel,
+recording or plugin name, 1 if the Power key was pressed).  One that exits
+non-zero cancels the shutdown and the first line it printed is shown on
+the OSD.  Then SHUTDOWN_ACTION from /etc/sysconfig/vdr runs: poweroff,
+suspend or hibernate, through sudo with the rules in /etc/sudoers.d/vdr.
+
+vdr-set-wakeup sets the RTC alarm WAKEUP_BEFORE_RECORDING minutes before
+the next timer or plugin wakeup, or clears it if there is none.  It runs
+whenever vdr.service stops, and before a suspend or hibernation.
+
+vdr-recording-hook.sh runs the executable files in
+/etc/vdr/recording-hooks.d with the state (before, started, after,
+editing, edited, deleted, copying, copied, renamed, moved), the
+recording's directory and, where there is one, the source directory.
+VDR waits for the hooks, so they have to return quickly; one that takes
+more than 10 seconds is killed.  For example, to write a .nfo file next
+to each new recording, /etc/vdr/recording-hooks.d/50-nfo could be:
+
+  #!/bin/sh
+  [ "$1" = after ] || exit 0
+  setsid -f /usr/local/bin/vdr2nfo "$2" >/dev/null 2>&1
+
+The hooks run as the vdr user.  Their output goes to the journal, each
+hook under its own name (journalctl -u vdr), also when a drop-in for
+vdr.service puts VDR's own stdout on a VT (StandardInput=tty).
+
 Organizing recordings
 ---------------------
 
-A simple sample script for organizing recordings into folders, vdr-moveto.sh,
-is shipped in the /usr/lib*/vdr/bin directory.  See commentary in it for
-usage information.
+vdr-moveto.sh moves a recording into a folder from the recording
+commands menu, through VDR, so the recording hook runs for it too.  Add
+entries like these to /etc/vdr/reccmds.conf:
+
+  Move to Movies: vdr-moveto.sh Movies
+  Move to Concerts: vdr-moveto.sh Music/Concerts

diff --git a/vdr-check-setup.sh b/vdr-check-setup.sh
index db982a5..1e94708 100644
--- a/vdr-check-setup.sh
+++ b/vdr-check-setup.sh
@@ -1,13 +1,21 @@
 #!/bin/sh
-
-# The packaged channels.conf contains only whitespace; VDR is not useful
-# before a real channel list exists, so refuse to start (exit 2 matches
-# RestartPreventExitStatus in vdr.service) until one has been created.
+# vdr-check-setup - ExecStartPre of vdr.service, runs as root.
+#
+# The packaged channels.conf contains only whitespace, and VDR is of no use
+# without channels: refuse to start (exit 2 matches RestartPreventExitStatus
+# in vdr.service) until a channel list exists.  A list written by root, by a
+# scanner or an editor, is handed over to VDR, which rewrites it.
 
 cfg=/etc/vdr/channels.conf
+
 if ! grep -q '[^[:space:]]' "$cfg" 2>/dev/null ; then
-    echo "$cfg is empty, use \"scandvb -o vdr\" from the dvb-apps package to create one." >&2
+    msg="$cfg has no channels; create it with a channel scanner, e.g. w_scan2 or \"dvbv5-scan -O VDR\" (dvb-tools)."
+    # stderr may be a VT (StandardInput=tty in a drop-in)
+    if [ -n "$INVOCATION_ID" ] ; then
+        logger -t "${0##*/}" -p user.err -- "$msg"
+    else
+        echo "$msg" >&2
+    fi
     exit 2
-else
-    chown VDR_USER:VDR_GROUP "$cfg" && chmod 644 "$cfg"
 fi
+chown VDR_USER:VDR_GROUP "$cfg" && chmod 644 "$cfg"

diff --git a/vdr-config.sh b/vdr-config.sh
index ef7be3b..12997e3 100644
--- a/vdr-config.sh
+++ b/vdr-config.sh
@@ -1,14 +1,32 @@
-#!/bin/bash
+#!/bin/sh
+# vdr-config - print VDR's build settings from vdr.pc
+#
+# vdr-config --version | --list | --VARIABLE...
+#
+#   --version   VDR's version
+#   --list      the names of the variables
+#   --VARIABLE  the value of one, e.g. --apiversion, --libdir, --cxxflags
+#
+# Prints one line per option, in the order given.
 
-case "$1" in
-    --version)
-        pkg-config vdr --modversion
-        ;;
-    --*dir|--apiversion|--user|--group)
-        pkg-config vdr --variable=${1#--}
-        ;;
-    *)
-        echo "Error: unknown option '$1'." >&2
-        exit 1
-        ;;
-esac
+usage() { sed -ne '4,10s/^# \{0,1\}//p' "$0" ; }
+
+[ $# -gt 0 ] || { usage >&2 ; exit 1 ; }
+vars=$(pkg-config vdr --print-variables) || exit 1
+
+for opt ; do
+    case $opt in
+        --help|-h) usage ;;
+        --version) pkg-config vdr --modversion ;;
+        --list)    printf '%s\n' "$vars" | sort ;;
+        --?*)
+            if printf '%s\n' "$vars" | grep -qxF -- "${opt#--}" ; then
+                pkg-config vdr --variable="${opt#--}"
+            else
+                echo "vdr-config: unknown option '$opt'" >&2
+                exit 1
+            fi
+            ;;
+        *) echo "vdr-config: unknown option '$opt'" >&2 ; exit 1 ;;
+    esac
+done

diff --git a/vdr-fsf-address.patch b/vdr-fsf-address.patch
deleted file mode 100644
index c0aaa6d..0000000
--- a/vdr-fsf-address.patch
+++ /dev/null
@@ -1,51 +0,0 @@
-From: Dirk Nehring <dnehring@gmx.net>
-Subject: [PATCH] COPYING: replace the FSF's former postal address with the license URLs
-
-The FSF no longer resides at 51 Franklin Street, and packaging checks
-reject license files with the old address. Refer to <https://fsf.org/>
-and <https://www.gnu.org/licenses/>, as the GPLv3 text does. The license
-terms are unchanged.
-
----
---- a/COPYING
-+++ b/COPYING
-@@ -2,7 +2,7 @@
- 		       Version 2, June 1991
- 
-  Copyright (C) 1989, 1991 Free Software Foundation, Inc.
-- 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
-+ <https://fsf.org/>
-  Everyone is permitted to copy and distribute verbatim copies
-  of this license document, but changing it is not allowed.
- 
-@@ -304,8 +304,7 @@ the "copyright" line and a pointer to where the full notice is found.
-     GNU General Public License for more details.
- 
-     You should have received a copy of the GNU General Public License
--    along with this program; if not, write to the Free Software
--    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
-+    along with this program; if not, see <https://www.gnu.org/licenses/>.
- 
- 
- Also add information on how to contact you by electronic and paper mail.
---- a/PLUGINS/src/skincurses/COPYING
-+++ b/PLUGINS/src/skincurses/COPYING
-@@ -2,7 +2,7 @@
- 		       Version 2, June 1991
- 
-  Copyright (C) 1989, 1991 Free Software Foundation, Inc.
-- 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
-+ <https://fsf.org/>
-  Everyone is permitted to copy and distribute verbatim copies
-  of this license document, but changing it is not allowed.
- 
-@@ -304,8 +304,7 @@ the "copyright" line and a pointer to where the full notice is found.
-     GNU General Public License for more details.
- 
-     You should have received a copy of the GNU General Public License
--    along with this program; if not, write to the Free Software
--    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
-+    along with this program; if not, see <https://www.gnu.org/licenses/>.
- 
- 
- Also add information on how to contact you by electronic and paper mail.

diff --git a/vdr-moveto.sh b/vdr-moveto.sh
index 6e00575..06999d1 100644
--- a/vdr-moveto.sh
+++ b/vdr-moveto.sh
@@ -1,32 +1,66 @@
-#!/bin/sh
-
-# vdr-moveto.sh -- simple script for moving recordings to folders
-# Ville Skyttä 2007, Public Domain
+#!/bin/bash
+# vdr-moveto.sh - move a recording into a folder, from VDR's recording
+# commands menu.  Add entries like these to /etc/vdr/reccmds.conf:
+#
+#   Move to Movies: vdr-moveto.sh Movies
+#   Move to Concerts: vdr-moveto.sh Music/Concerts
+#
+# VDR appends the recording's directory.  FOLDER is a folder as VDR's
+# menus show it, with '/' or '~' between the levels.  The recording keeps
+# its own name (the last part of its full name).
 #
-# The preferred way to use this script is through VDR's recording commands
-# menu.  To do that, add entries eg. like these to /etc/vdr/reccmds.conf:
+# The move goes through VDR (SVDRP MOVR), like "Edit recording" in the
+# menu: VDR refuses a recording that is being played, recorded or cut,
+# copies across file systems in the background and runs the recording hook
+# ("renamed"/"moved", or "copying", "copied", "moved").
 #
-# Move to movies: vdr-moveto.sh 00_Movies
-# Move to music: vdr-moveto.sh 00_Music
+# Ville Skyttä 2007, rewritten for VDR 2.8; Public Domain
 
-videodir="$(sed -ne 's/^\s*VDR_OPTIONS\s*=.*\(-v\s\+\|--video\(=\|\s\+\)\)\([^[:space:])]*\).*/\3/p' /etc/sysconfig/vdr)"
-[ -n "$videodir" ] || videodir="/var/lib/vdr/video"
+shopt -s extglob
 
-to="$videodir/$1"
-what="$2"
-if [ -z "$what" ] ; then
-    echo "Usage: $0 TO-DIR WHAT"
+# '_' is how a ' ' looks on disk, VDR reads it back as ' '
+folder=${1//_/ }
+folder=${folder//\//\~}
+folder=${folder##+(\~)}
+folder=${folder%%+(\~)}
+rec=${2%/}
+
+if [[ $# -ne 2 || -z $folder || $rec != /*.rec ]] ; then
+    echo "Usage: ${0##*/} FOLDER RECORDING-DIRECTORY"
     exit 1
 fi
 
-mkdir -p "$to"
-dir="$(dirname $what)"
-todir="$to/$(basename $dir)"
-if [ -d "$todir" ] ; then
-    mv -v "$what" "$todir"
-    rmdir -v "$dir"
+# LSTR lists "ID DD.MM.YY HH:MM LENGTH[*][!] NAME" with the start time the
+# directory name carries, LSTR ID path the directory of one of them.
+if [[ ${rec##*/} =~ ^[0-9]{2}([0-9]{2})-([0-9]{2})-([0-9]{2})\.([0-9]{2})\.([0-9]{2})\. ]] ; then
+    m=("${BASH_REMATCH[@]}")
+    start="${m[3]}.${m[2]}.${m[1]} ${m[4]}:${m[5]}"
 else
-    mv -v "$dir" "$to"
+    echo "Not a recording directory: $rec"
+    exit 1
+fi
+
+id='' name=''
+while read -r code cid date time _ rest ; do
+    [[ $code == 250 && "$date $time" == "$start" ]] || continue
+    path=$(svdrpsend LSTR "$cid" path | sed -ne 's/^250 //p' | tr -d '\r')
+    if [[ ${path%/} == "$rec" ]] ; then
+        id=$cid name=${rest%$'\r'}
+        break
+    fi
+done < <(svdrpsend LSTR 2>/dev/null | sed -Ee 's/^250[- ]/250 /')
+
+if [[ ! $id ]] ; then
+    echo "VDR does not know $rec"
+    exit 1
+fi
+
+title=${name##*~}
+if [[ ${name//_/ } == "$folder~${title//_/ }" ]] ; then
+    echo "\"$title\" is already in $folder"
+    exit 0
 fi
 
-touch "$videodir/.update"
+reply=$(svdrpsend MOVR "$id" "$folder~$title" | grep -Ev '^22[01] ' | tr -d '\r')
+echo "${reply#[0-9][0-9][0-9][ -]}"
+[[ $reply == 250\ * ]]

diff --git a/vdr-posix-inet-functions.patch b/vdr-posix-inet-functions.patch
deleted file mode 100644
index c475a6b..0000000
--- a/vdr-posix-inet-functions.patch
+++ /dev/null
@@ -1,56 +0,0 @@
-From: Dirk Nehring <dnehring@gmx.net>
-Subject: [PATCH] config, svdrp: use inet_pton()/inet_ntop() instead of the legacy inet_* calls
-
-inet_ntoa() returns a static buffer, but cIpAddress::Set() runs in
-concurrent SVDRP handler threads. inet_aton() and inet_addr() go as
-well: they are obsolete (distribution checks flag them), and VDR only
-passes dotted-decimal addresses, the one form inet_pton() accepts.
-Connect() fails on an invalid address instead of connecting to 0.0.0.0.
-
----
---- a/config.c
-+++ b/config.c
-@@ -49,7 +49,7 @@ bool cSVDRPhost::Parse(const char *s)
-         mask = htonl(mask);
-         }
-      }
--  int result = inet_aton(s, &addr);
-+  int result = inet_pton(AF_INET, s, &addr);
-   if (p)
-      *(char *)p = '/'; // there it is again
-   return result != 0 && (mask != 0 || addr.s_addr == 0);
---- a/svdrp.c
-+++ b/svdrp.c
-@@ -91,7 +91,8 @@ void cIpAddress::Set(const char *Address, int Port)
- void cIpAddress::Set(const sockaddr *SockAddr)
- {
-   const sockaddr_in *Addr = (sockaddr_in *)SockAddr;
--  Set(inet_ntoa(Addr->sin_addr), ntohs(Addr->sin_port));
-+  char buf[INET_ADDRSTRLEN];
-+  Set(inet_ntop(AF_INET, &Addr->sin_addr, buf, sizeof(buf)), ntohs(Addr->sin_port));
- }
- 
- // --- cSocket ---------------------------------------------------------------
-@@ -202,7 +203,11 @@ bool cSocket::Connect(const char *Address)
-      memset(&Addr, 0, sizeof(Addr));
-      Addr.sin_family = AF_INET;
-      Addr.sin_port = htons(port);
--     Addr.sin_addr.s_addr = inet_addr(Address);
-+     if (inet_pton(AF_INET, Address, &Addr.sin_addr) != 1) {
-+        esyslog("ERROR: invalid IP address '%s'", Address);
-+        Close();
-+        return false;
-+        }
-      if (connect(sock, (sockaddr *)&Addr, sizeof(Addr)) < 0) {
-         LOG_ERROR;
-         Close();
-@@ -250,7 +255,8 @@ bool cSocket::SendDgram(const char *Dgram, int Port)
-   Addr.sin_addr.s_addr = htonl(INADDR_BROADCAST);
-   Addr.sin_port = htons(Port);
-   // Send datagram:
--  dbgsvdrp("> %s:%d %s\n", inet_ntoa(Addr.sin_addr), Port, Dgram);
-+  char buf[INET_ADDRSTRLEN];
-+  dbgsvdrp("> %s:%d %s\n", inet_ntop(AF_INET, &Addr.sin_addr, buf, sizeof(buf)), Port, Dgram);
-   int Length = strlen(Dgram);
-   int Sent = sendto(Socket, Dgram, Length, 0, (sockaddr *)&Addr, sizeof(Addr));
-   if (Sent < 0)

diff --git a/vdr-reccmds.conf b/vdr-reccmds.conf
index 9e64e9e..3354be7 100644
--- a/vdr-reccmds.conf
+++ b/vdr-reccmds.conf
@@ -1,2 +1,4 @@
 # Recording commands for VDR.  See the vdr(5) manual page.
 
+# Move the recording into a folder, see README.package:
+#Move to Movies: vdr-moveto.sh Movies

diff --git a/vdr-recording-hook.sh b/vdr-recording-hook.sh
new file mode 100644
index 0000000..72a9863
--- /dev/null
+++ b/vdr-recording-hook.sh
@@ -0,0 +1,58 @@
+#!/bin/sh
+# vdr-recording-hook.sh - VDR's --record hook (INSTALL: "Executing commands
+# before and after a recording").  Runs the executable files in
+# /etc/vdr/recording-hooks.d in name order with VDR's arguments: the state,
+# the recording's directory and, where there is one, the source directory.
+#
+#   before  REC      a timer starts recording into REC (not created yet)
+#   started REC      the recorder knows the stream, REC/info is complete
+#   after   REC      the recording has ended
+#   editing REC SRC  cutting SRC into REC starts
+#   edited  REC SRC  the cut is complete
+#   deleted REC      REC has been renamed to *.del, VDR removes it later
+#   copying REC SRC  copying SRC to REC starts
+#   copied  REC SRC  the copy is complete
+#   renamed REC SRC  new name in the same folder
+#   moved   REC SRC  new folder; across file systems after copying/copied
+#
+# VDR waits for this script, in its main thread and for "started" in the
+# recorder thread, so a hook must return quickly and start longer work in
+# the background ("setsid -f CMD >/dev/null 2>&1").  A hook that takes more
+# than 10 seconds is killed.  Hooks run as the vdr user.  Under systemd
+# their output and this script's messages go to the journal, each hook
+# under its own name (VDR's stdout may be a VT there: StandardInput=tty).
+
+hookdir=/etc/vdr/recording-hooks.d
+
+log()
+{
+    if [ -n "$INVOCATION_ID" ] ; then
+        logger -t "${0##*/}" -p user.warning -- "$*"
+    else
+        echo "${0##*/}: $*" >&2
+    fi
+}
+
+case $1 in
+    before|started|after|editing|edited|deleted|copying|copied|renamed|moved) ;;
+    *) log "unknown state '$1', passing it on" ;;
+esac
+
+for hook in "$hookdir"/* ; do
+    case $hook in
+        *~|*.bak|*.orig|*.rpmnew|*.rpmorig|*.rpmsave) continue ;;
+    esac
+    [ -f "$hook" ] && [ -x "$hook" ] || continue
+    if [ -n "$INVOCATION_ID" ] ; then
+        timeout -k 2 10 systemd-cat -t "${hook##*/}" "$hook" "$@"
+    else
+        timeout -k 2 10 "$hook" "$@"
+    fi
+    rc=$?
+    case $rc in
+        0) ;;
+        124|137) log "${hook##*/} $1: killed after 10 seconds" ;;
+        *) log "${hook##*/} $1: exit status $rc" ;;
+    esac
+done
+exit 0

diff --git a/vdr-runvdr.sh b/vdr-runvdr.sh
index 7dd18bd..cc66438 100644
--- a/vdr-runvdr.sh
+++ b/vdr-runvdr.sh
@@ -1,57 +1,49 @@
 #!/bin/bash
-
-# runvdr - VDR launcher
+# runvdr - VDR launcher, ExecStart of vdr.service
 #
 # runvdr [VDROPTION]...
+#
+# Starts VDR with the given options, VDR_OPTIONS from /etc/sysconfig/vdr and
+# a --plugin option for each installed plugin of this VDR's API version:
+# the ones in VDR_PLUGIN_ORDER first, in that order, then the rest.  A
+# plugin's options come from PLUGIN_OPTIONS in
+# /etc/sysconfig/vdr-plugins.d/NAME.conf, PLUGIN_ENABLED=no there skips it.
 
-shopt -s nocasematch nullglob
+shopt -s nullglob
 
-VDR=/usr/sbin/vdr
+VDR=/usr/bin/vdr
 PLUGINDIR=/usr/lib/vdr
-PLUGINVER=VDR_PLUGIN_VERSION
-PLUGINSUF=${PLUGINVER:+.$PLUGINVER}
+PLUGINSUF=.so.VDR_PLUGIN_VERSION
+PLUGINCONF=/etc/sysconfig/vdr-plugins.d
 
-plugconf()
-{
-    local plugin=$1 PLUGIN_OPTIONS= PLUGIN_ENABLED=
-    if [[ -e /etc/sysconfig/vdr-plugins.d/$plugin.conf ]] ; then
-        . /etc/sysconfig/vdr-plugins.d/$plugin.conf
-        case $PLUGIN_ENABLED in no|false|0) return ;; esac
-    fi
-    if [[ $PLUGIN_OPTIONS ]] ; then
-        VDR_OPTIONS+=( --plugin="$plugin $PLUGIN_OPTIONS" )
-    else
-        VDR_OPTIONS+=( --plugin=$plugin )
-    fi
-}
+VDR_OPTIONS=()
+[[ -r /etc/sysconfig/vdr ]] && . /etc/sysconfig/vdr
 
-build_cmdline()
+if [[ $DAEMON_COREFILE_LIMIT ]] && ulimit -S -c "$DAEMON_COREFILE_LIMIT" 2>/dev/null ; then
+    VDR_OPTIONS+=( --userdump )
+fi
+
+declare -A seen
+
+add_plugin()
 {
-    local plugin= p=
-    # Add "priority" plugins.
-    for plugin in $VDR_PLUGIN_ORDER ; do
-        [[ -e $PLUGINDIR/libvdr-${plugin}.so$PLUGINSUF ]] && plugconf $plugin
-    done
-    # Add the rest available.
-    for plugin in $PLUGINDIR/libvdr-*.so$PLUGINSUF ; do
-        plugin=${plugin##*/libvdr-}
-        plugin=${plugin%.so$PLUGINSUF}
-        for p in $VDR_PLUGIN_ORDER ; do
-            if [[ $plugin == $p ]] ; then
-                # Already added.
-                continue 2
-            fi
-        done
-        plugconf $plugin
-    done
+    local plugin=$1 PLUGIN_OPTIONS='' PLUGIN_ENABLED=''
+    [[ ${seen[$plugin]} ]] && return
+    seen[$plugin]=1
+    if [[ -r $PLUGINCONF/$plugin.conf ]] ; then
+        # shellcheck source=/dev/null
+        . "$PLUGINCONF/$plugin.conf"
+        case ${PLUGIN_ENABLED,,} in no|false|0) return ;; esac
+    fi
+    VDR_OPTIONS+=( --plugin="$plugin${PLUGIN_OPTIONS:+ $PLUGIN_OPTIONS}" )
 }
 
-VDR_OPTIONS=()
-[[ -f /etc/sysconfig/vdr ]] && . /etc/sysconfig/vdr
-[[ $DAEMON_COREFILE_LIMIT ]] && \
-    ulimit -S -c $DAEMON_COREFILE_LIMIT &>/dev/null && \
-    VDR_OPTIONS+=( --userdump )
-
-build_cmdline
+for plugin in $VDR_PLUGIN_ORDER ; do
+    [[ -e $PLUGINDIR/libvdr-$plugin$PLUGINSUF ]] && add_plugin "$plugin"
+done
+for lib in "$PLUGINDIR"/libvdr-*"$PLUGINSUF" ; do
+    plugin=${lib##*/libvdr-}
+    add_plugin "${plugin%"$PLUGINSUF"}"
+done
 
-exec $VDR "$@" "${VDR_OPTIONS[@]}"
+exec "$VDR" "$@" "${VDR_OPTIONS[@]}"

diff --git a/vdr-set-wakeup.sh b/vdr-set-wakeup.sh
index 1efc13e..9824171 100644
--- a/vdr-set-wakeup.sh
+++ b/vdr-set-wakeup.sh
@@ -1,27 +1,55 @@
 #!/bin/bash
-
-# Set RTC wakeup for next VDR timer event
+# vdr-set-wakeup - set the RTC alarm for VDR's next timer or plugin wakeup.
+# Runs as root: as ExecStop of vdr.service, and through sudo from
+# vdr-shutdown.sh before a suspend or hibernation.
+#
+# The time comes from vdr-shutdown.sh in /run/vdr/next-timer, or from
+# SVDRP if VDR is stopped some other way (systemctl, reboot).  The box wakes
+# up WAKEUP_BEFORE_RECORDING minutes (/etc/sysconfig/vdr) before it.
+# Without a next event the alarm is cleared; if VDR cannot be asked, the
+# alarm stays as it is.  Under systemd the output goes to the journal (the
+# unit's stdout may be a VT: StandardInput=tty), when run by hand to the
+# terminal.
 
 shopt -s extglob
 
-# Check timestamp set by shutdown script.
-nexttimer=$( cat /var/run/vdr/next-timer 2>/dev/null )
-rm -f /var/run/vdr/next-timer
+[[ -r /etc/sysconfig/vdr ]] && . /etc/sysconfig/vdr
+[[ $INVOCATION_ID ]] && exec > >(logger -t "${0##*/}") 2>&1
+
+handoff=/run/vdr/next-timer
+now=$(date +%s)
+next=
 
-if [[ $nexttimer != +([0-9]) ]] ; then
-    # Next timer timestamp not set by shutdown script or bogus,
-    # try to get it via SVDRP.
-    nexttimer=$( svdrpsend NEXT abs 2>/dev/null | \
-        sed -rne 's/^250[[:space:]]+[0-9]+[[:space:]]+([0-9]+).*/\1/p' )
+if [[ -r $handoff ]] ; then
+    next=$(< "$handoff")
+    rm -f "$handoff"
 fi
 
-# TODO: nexttimer may be in the past if there's an ongoing recording
-# (see svdrpsend HELP NEXT). In that case we should set *something* or
-# the box won't autowakeup at all
-if [[ $nexttimer && $nexttimer -gt $( date +%s ) ]] ; then
-    [[ -f /etc/sysconfig/vdr ]] && . /etc/sysconfig/vdr
-    when=$(( $nexttimer - ${WAKEUP_BEFORE_RECORDING:-10} * 60 ))
-    hrwhen=$( date -d "1970-01-01 $when sec UTC" )
-    echo "Setting wakeup time for next recording: $hrwhen"
-    /usr/sbin/rtcwake -m no -t $when >/dev/null
+if [[ $next != +([0-9]) ]] ; then
+    reply=$(svdrpsend NEXT abs 2>/dev/null)
+    if [[ $reply =~ (^|$'\n')250\ +[0-9]+\ +([0-9]+) ]] ; then
+        next=${BASH_REMATCH[2]}
+        # A timer that is recording right now started in the past.  Like
+        # VDR's own forced shutdown, come back after MinEventTimeout.
+        if (( next <= now )) ; then
+            mins=$(sed -nEe 's/^MinEventTimeout *= *([0-9]+).*/\1/p' /etc/vdr/setup.conf 2>/dev/null)
+            next=$(( now + ${mins:-30} * 60 ))
+        fi
+    elif [[ $reply =~ (^|$'\n')550\  ]] ; then
+        next=0
+    else
+        echo "VDR does not answer on SVDRP, RTC alarm unchanged"
+        exit 0
+    fi
 fi
+
+if (( next == 0 )) ; then
+    echo "no timer or plugin wakeup, clearing the RTC alarm"
+    exec /usr/bin/rtcwake -m disable >/dev/null
+fi
+
+when=$(( next - ${WAKEUP_BEFORE_RECORDING:-10} * 60 ))
+# rtcwake refuses the past, and the machine has to be off before the alarm
+(( when < now + 120 )) && when=$(( now + 120 ))
+echo "next event $(date -d "@$next" '+%F %R'), RTC alarm $(date -d "@$when" '+%F %R')"
+exec /usr/bin/rtcwake -m no -t "$when" >/dev/null

diff --git a/vdr-shutdown.sh b/vdr-shutdown.sh
index b641a29..747c0be 100755
--- a/vdr-shutdown.sh
+++ b/vdr-shutdown.sh
@@ -1,17 +1,66 @@
-#!/bin/sh
-
-# To enable this script, pass it to vdr with the -s option, eg.
-# "-s vdr-shutdown.sh" (sans quotes) in VDR_OPTIONS in /etc/sysconfig/vdr.
+#!/bin/bash
+# vdr-shutdown.sh - VDR's --shutdown hook (INSTALL: "Automatic shutdown").
+# VDR runs it detached when it wants the machine off, with
+#
+#   $1  time of the next timer or plugin wakeup (time_t), 0 for none
+#   $2  seconds from now until then, 0 for none
+#   $3  channel number of that timer, 0 for a plugin wakeup or none
+#   $4  file name of that timer's recording, the plugin's name, or ""
+#   $5  1 if the user pressed Power, 0 after the user inactivity timeout
 #
-# The commands run through sudo; the rules they need are packaged in
-# /etc/sudoers.d/vdr.  To hibernate instead of powering off, replace the
-# last line with
+# VDR keeps running until systemd stops it, and calls this again after a
+# while if the machine stays on.
 #
-#   sudo /usr/lib/vdr/bin/vdr-set-wakeup
-#   exec sudo /usr/bin/systemctl hibernate
+# The executable files in /etc/vdr/shutdown-hooks.d run first, in name
+# order, with the same arguments.  One that exits non-zero cancels this
+# shutdown, the first line of its output is shown on the OSD (log lines
+# belong on stderr).
 #
-# (the service keeps running through hibernation, so the wakeup must be
-# set here instead of by the unit's ExecStop hook).
+# SHUTDOWN_ACTION in /etc/sysconfig/vdr is poweroff (default), suspend or
+# hibernate, run through sudo with the rules in /etc/sudoers.d/vdr.
+# vdr-set-wakeup sets the RTC alarm for $1: as ExecStop of vdr.service on
+# poweroff, and from here before a suspend or hibernation, which VDR
+# survives.
+#
+# Under systemd all output goes to the journal (VDR's stdout may be a VT
+# there: StandardInput=tty), when run by hand to the terminal.
+
+[[ -r /etc/sysconfig/vdr ]] && . /etc/sysconfig/vdr
+[[ $INVOCATION_ID ]] && exec > >(logger -t "${0##*/}") 2>&1
+
+hookdir=/etc/vdr/shutdown-hooks.d
+next=${1:-0} delta=${2:-0} channel=${3:-0} name=$4 user=${5:-0}
+action=${SHUTDOWN_ACTION:-poweroff}
+
+case $action in
+    poweroff|suspend|hibernate) ;;
+    *) echo "unknown SHUTDOWN_ACTION '$action', staying on" ; exit 1 ;;
+esac
+
+if (( next )) ; then
+    event="next event $(date -d "@$next" '+%F %R') in $(( delta / 60 )) min"
+    (( channel )) && event+=", channel $channel"
+    [[ $name ]] && event+=", \"$name\""
+else
+    event="no timer or plugin wakeup"
+fi
+echo "$action ($( (( user )) && echo "Power key" || echo "inactivity" )), $event"
+
+for hook in "$hookdir"/* ; do
+    case $hook in
+        *~|*.bak|*.orig|*.rpmnew|*.rpmorig|*.rpmsave) continue ;;
+    esac
+    [[ -f $hook && -x $hook ]] || continue
+    if ! msg=$("$hook" "$@") ; then
+        msg=${msg%%$'\n'*}
+        echo "cancelled by ${hook##*/}${msg:+: $msg}"
+        svdrpsend MESG "${msg:-Shutdown cancelled by ${hook##*/}}" >/dev/null 2>&1
+        exit 1
+    fi
+done
 
-echo ${1:-0} > /var/run/vdr/next-timer
-exec sudo /usr/bin/systemctl poweroff
+echo "$next" > /run/vdr/next-timer
+if [[ $action != poweroff ]] ; then
+    sudo -n /usr/lib/vdr/bin/vdr-set-wakeup
+fi
+exec sudo -n /usr/bin/systemctl "$action"

diff --git a/vdr.spec b/vdr.spec
index 2af9507..6b94f1a 100644
--- a/vdr.spec
+++ b/vdr.spec
@@ -1,20 +1,20 @@
-%global varbase   %{_var}/lib/vdr
+%global varbase   %{_sharedstatedir}/vdr
 %global videodir  %{varbase}/video
 %global vardir    %{varbase}/data
 %global plugindir %{_libdir}/vdr
 %global configdir %{_sysconfdir}/vdr
-%global cachedir  %{_var}/cache/vdr
-%global rundir    /run/vdr
+%global cachedir  %{_localstatedir}/cache/vdr
+%global rundir    %{_rundir}/vdr
 %global vdr_user  vdr
 %global vdr_group video
 
-%bcond_without    docs
+%bcond docs 1
 
 %global __provides_exclude_from ^%{plugindir}/.*\\.so.*$
 
 Name:           vdr
-Version:        2.8.3
-Release:        1%{?dist}
+Version:        2.8.4
+Release:        2%{?dist}
 Summary:        Video Disk Recorder
 
 License:        GPL-2.0-or-later
@@ -42,46 +42,45 @@ Source12:       %{name}-shutdown.sh
 Source13:       %{name}-moveto.sh
 Source14:       %{name}-check-setup.sh
 Source15:       %{name}-set-wakeup.sh
+Source16:       %{name}-recording-hook.sh
 
 # Fedora/FHS integration: export datadir/rundir/vardir/user/group from vdr.pc
 Patch0:         %{name}-fedora.patch
 # MainMenuHooks, reduced to the only hook any shipped plugin implements
 # (epgsearch's "Replace original schedule")
 Patch1:         %{name}-mainmenuhooks.patch
-# Sent upstream: replace the FSF's former postal address in COPYING with the
-# license URLs; rpmlint rejects the old address
-Patch2:         %{name}-fsf-address.patch
-# Sent upstream: thread-safe inet_pton()/inet_ntop() instead of inet_ntoa() & Co.
-Patch3:         %{name}-posix-inet-functions.patch
-
-# For upstream, Patch1NN is %%{name}-NN-*.patch, in dependency order:
-# data races found with ThreadSanitizer (01-12)
-Patch101:       %{name}-01-thread-atomics.patch
-Patch102:       %{name}-02-device-track-atomics.patch
-Patch103:       %{name}-03-device-player-atomics.patch
-Patch104:       %{name}-04-receiver-atomics.patch
-Patch105:       %{name}-05-transfer-atomics.patch
-Patch106:       %{name}-06-dvbplayer-atomics.patch
-Patch107:       %{name}-07-dvbtuner-atomics.patch
-Patch108:       %{name}-08-dvbtuner-channel-lock.patch
-Patch109:       %{name}-09-sections-sdt-atomics.patch
-Patch110:       %{name}-10-svdrp-ready-atomic.patch
-Patch111:       %{name}-11-dvbsubtitle-atomics.patch
-Patch112:       %{name}-12-device-camslot-atomic.patch
-# lock order inversions and object lifetime (13-17)
-Patch113:       %{name}-13-camslot-assign-lock-scope.patch
-Patch114:       %{name}-14-device-pid-notify-lock-scope.patch
-Patch115:       %{name}-15-control-mutex-null.patch
-Patch116:       %{name}-16-osd-deregister-before-delete.patch
-Patch117:       %{name}-17-skins-locked-track-copy.patch
-# live data reached the receivers in 100 ms steps, slowing down channel switches
-Patch118:       %{name}-18-tsbuffer-get-timeout.patch
-# the end of a replay: a pause in the tail, B-frame tails cut by the STC check,
-# recordings that are still being written, and DrainDevice() in PLUGINS.html
-Patch119:       %{name}-19-dvbplayer-pause-stuckateof.patch
-Patch120:       %{name}-20-dvbplayer-last-frame.patch
-Patch121:       %{name}-21-dvbplayer-growing-recording.patch
-Patch122:       %{name}-22-plugins-html-draindevice.patch
+
+# For upstream, Patch1NN is %%{name}-NN-*.patch, by priority in four groups.
+# Lifetime: the first key after a replay started without one ended the EPG
+# scan by switching channels, which deleted the control the main loop had
+# already fetched for that key; an OSD deleted in another thread got
+# SetActive() calls while being destroyed, player/receiver/CAM slot pointers
+# turned NULL between check and use, destructors ran before a thread's last
+# writes were visible, a recorder thread that saw no independent frame after
+# Stop() never ended and got pthread_cancel()ed inside cCondWait::Wait()
+Patch101:       %{name}-01-eitscan-activity-before-control.patch
+Patch102:       %{name}-02-osd-delete-before-destructor.patch
+Patch103:       %{name}-03-pointer-snapshots.patch
+Patch104:       %{name}-04-thread-atomics.patch
+Patch105:       %{name}-05-recorder-stop-timeout.patch
+# Lost updates and torn reads: timer flags changed without the timers
+# lock, track descriptions read while another thread rewrote them
+Patch106:       %{name}-06-timer-flags-atomic.patch
+Patch107:       %{name}-07-track-description-copy.patch
+# State read without a lock, by subsystem (ThreadSanitizer findings)
+Patch108:       %{name}-08-dvbplayer-atomics.patch
+Patch109:       %{name}-09-dvbdevice-atomics.patch
+Patch110:       %{name}-10-device-state-atomics.patch
+Patch111:       %{name}-11-receiver-pids-atomic.patch
+Patch112:       %{name}-12-section-filter-atomics.patch
+Patch113:       %{name}-13-shared-flags-atomic.patch
+# Globals switched for a local purpose: the CI TPDU dump switch per TPDU in
+# the CI adapter thread, Setup.ShowChannelNamesWithSource around a rename
+Patch114:       %{name}-14-ci-dump-thread-local.patch
+Patch115:       %{name}-15-channels-obsolete-name.patch
+# Found with ThreadSanitizer and the dvd plugin: the track menus counted the
+# tracks without the lock a player announces them under
+Patch116:       %{name}-16-numtracks-lock.patch
 
 BuildRequires:  gcc-c++
 BuildRequires:  make
@@ -104,7 +103,6 @@ BuildRequires:  graphviz
 Requires:       sudo
 Requires:       util-linux
 Requires:       vdrsymbol-fonts
-%{?systemd_requires}
 Provides:       vdr(abi)%{?_isa} = %{apiver}
 
 %description
@@ -168,8 +166,8 @@ done
 
 %build
 cat << EOF > Make.config
-CC           = %{__cc}
-CXX          = %{__cxx}
+CC           = %{build_cc}
+CXX          = %{build_cxx}
 
 CFLAGS       = \$(shell pkg-config vdr --variable=cflags)
 CXXFLAGS     = \$(shell pkg-config vdr --variable=cxxflags)
@@ -204,14 +202,13 @@ CFLAGS += -I$PWD/include
 CXXFLAGS += -I$PWD/include
 EOF
 
-cflags="%{build_cflags} -fPIC"
 
 make vdr.pc BINDIR=%{_bindir} MANDIR=%{_mandir} CONFDIR=%{configdir} \
     VIDEODIR=%{videodir} CACHEDIR=%{cachedir} RESDIR=%{_datadir}/vdr \
     LIBDIR=%{plugindir} LOCDIR=%{_datadir}/locale RUNDIR=%{rundir} \
     VARDIR=%{vardir} VDR_USER=%{vdr_user} VDR_GROUP=%{vdr_group} \
-    LDFLAGS="%{build_ldflags}" CFLAGS="$cflags" \
-    CXXFLAGS="$cflags -Werror=overloaded-virtual -Wno-parentheses"
+    LDFLAGS="%{build_ldflags}" CFLAGS="%{build_cflags} -fPIC" \
+    CXXFLAGS="%{build_cxxflags} -fPIC -Werror=overloaded-virtual -Wno-parentheses"
 
 PKG_CONFIG_PATH="$PWD:$PKG_CONFIG_PATH" \
 %make_build vdr include-dir i18n
@@ -240,6 +237,7 @@ install -dm 755 %{buildroot}%{vardir}
 install -dm 755 %{buildroot}%{configdir}/themes
 install -dm 755 %{buildroot}%{_datadir}/vdr/{logos,plugins}
 install -dm 755 %{buildroot}%{plugindir}/bin
+install -dm 755 %{buildroot}%{configdir}/{recording,shutdown}-hooks.d
 
 touch %{buildroot}%{configdir}/themes/{classic,sttng}-default.theme
 touch %{buildroot}%{videodir}/.update
@@ -247,7 +245,7 @@ touch %{buildroot}%{cachedir}/epg.data
 
 install -pm 755 %{SOURCE10} %{buildroot}%{_bindir}/runvdr
 sed -i \
-    -e 's|/usr/sbin/|%{_bindir}/|'                     \
+    -e 's|/usr/bin/vdr\b|%{_bindir}/vdr|'              \
     -e 's|/etc/sysconfig/|%{_sysconfdir}/sysconfig/|g' \
     -e 's|/usr/lib/vdr\b|%{plugindir}|'                \
     -e 's|VDR_PLUGIN_VERSION|%{apiver}|'               \
@@ -260,28 +258,31 @@ sed -i \
 
 install -pm 755 %{SOURCE12} %{buildroot}%{plugindir}/bin/%{name}-shutdown.sh
 sed -i \
-    -e 's|/etc/sysconfig/|%{_sysconfdir}/sysconfig/|' \
-    -e 's|/var/run/vdr/|%{rundir}/|'                  \
-    -e 's|/usr/lib/vdr/|%{plugindir}/|'               \
+    -e 's|/etc/sysconfig/|%{_sysconfdir}/sysconfig/|g' \
+    -e 's|/etc/vdr/|%{configdir}/|g'                   \
+    -e 's|/run/vdr/|%{rundir}/|g'                      \
+    -e 's|/usr/lib/vdr/|%{plugindir}/|g'               \
     %{buildroot}%{plugindir}/bin/%{name}-shutdown.sh
 
-install -pm 755 %{SOURCE13} %{buildroot}%{plugindir}/bin/%{name}-moveto.sh
+install -pm 755 %{SOURCE16} %{buildroot}%{plugindir}/bin/%{name}-recording-hook.sh
 sed -i \
-    -e 's|/var/lib/vdr/video|%{videodir}|' \
-    -e 's|/etc/vdr/|%{configdir}/|'        \
-    %{buildroot}%{plugindir}/bin/%{name}-moveto.sh
+    -e 's|/etc/vdr/|%{configdir}/|g' \
+    %{buildroot}%{plugindir}/bin/%{name}-recording-hook.sh
+
+install -pm 755 %{SOURCE13} %{buildroot}%{plugindir}/bin/%{name}-moveto.sh
 
 install -pm 755 %{SOURCE14} %{buildroot}%{plugindir}/bin/%{name}-check-setup
 sed -i \
-    -e 's|/etc/vdr/|%{configdir}/|' \
+    -e 's|/etc/vdr/|%{configdir}/|g' \
     -e 's|VDR_USER|%{vdr_user}|'    \
     -e 's|VDR_GROUP|%{vdr_group}|'  \
     %{buildroot}%{plugindir}/bin/%{name}-check-setup
 
 install -pm 755 %{SOURCE15} %{buildroot}%{plugindir}/bin/%{name}-set-wakeup
 sed -i \
-    -e 's|/usr/sbin/|%{_bindir}/|'   \
-    -e 's|/var/run/vdr/|%{rundir}/|' \
+    -e 's|/etc/sysconfig/|%{_sysconfdir}/sysconfig/|g' \
+    -e 's|/etc/vdr/|%{configdir}/|g'                   \
+    -e 's|/run/vdr/|%{rundir}/|g'                      \
     %{buildroot}%{plugindir}/bin/%{name}-set-wakeup
 
 install -Dpm 644 %{SOURCE1} %{buildroot}%{_unitdir}/%{name}.service
@@ -332,13 +333,19 @@ test "$(pkg-config vdr --variable=user)" = "%{vdr_user}"
 test "$(pkg-config vdr --variable=vardir)" = "%{vardir}"
 # The MainMenuHooks patch must have taken effect
 grep -q 'MainMenuHooksPatch-v1.0::osSchedule' vdr
-# The FSF address patch must have taken effect (rpmlint rejects the old address)
-! grep -qr 'Franklin' COPYING PLUGINS/src/skincurses/COPYING
+# rpmlint rejects the FSF's former postal address
+if grep -qr 'Franklin' COPYING PLUGINS/src/skincurses/COPYING ; then exit 1 ; fi
 # vdr resolves VDRPluginCreator after dlopen; a plugin without that export
 # is broken even if it links cleanly
 nm -D --defined-only %{buildroot}%{plugindir}/libvdr-skincurses.so.%{apiver} | grep -q ' VDRPluginCreator$'
 # The sudoers drop-in must parse
 visudo -cf %{buildroot}%{_sysconfdir}/sudoers.d/vdr
+# The scripts must parse, with every build-time placeholder replaced
+scripts="%{buildroot}%{_bindir}/runvdr %{buildroot}%{_bindir}/vdr-config $(ls -d %{buildroot}%{plugindir}/bin/*)"
+for f in $scripts ; do
+    $(sed -ne '1s/^#!//p' $f) -n $f
+done
+if grep -n 'VDR_USER\|VDR_GROUP\|VDR_PLUGIN_VERSION\|/var/run/' $scripts ; then exit 1 ; fi
 
 
 %post
@@ -371,6 +378,7 @@ visudo -cf %{buildroot}%{_sysconfdir}/sudoers.d/vdr
 %dir %{plugindir}/bin/
 %{plugindir}/bin/%{name}-check-setup
 %{plugindir}/bin/%{name}-moveto.sh
+%{plugindir}/bin/%{name}-recording-hook.sh
 %{plugindir}/bin/%{name}-set-wakeup
 %{plugindir}/bin/%{name}-shutdown.sh
 %{_datadir}/vdr/
@@ -385,6 +393,8 @@ visudo -cf %{buildroot}%{_sysconfdir}/sudoers.d/vdr
 %ghost %attr(-,%{vdr_user},%{vdr_group}) %{cachedir}/epg.data
 %dir %attr(-,%{vdr_user},root) %{configdir}/
 %dir %attr(-,%{vdr_user},root) %{configdir}/plugins/
+%dir %{configdir}/recording-hooks.d/
+%dir %{configdir}/shutdown-hooks.d/
 %dir %attr(-,%{vdr_user},root) %{vardir}/
 %dir %attr(-,%{vdr_user},root) %{configdir}/themes/
 %dir %attr(-,%{vdr_user},root) %{cachedir}/
@@ -416,6 +426,117 @@ visudo -cf %{buildroot}%{_sysconfdir}/sudoers.d/vdr
 
 
 %changelog
+* Thu Oct 29 2026 Dirk Nehring  <dnehring@gmx.net> - 2.8.4-2
+- Add 16-numtracks-lock (for upstream), found with ThreadSanitizer and the
+  dvd plugin: count the available tracks under mutexCurrentAudioTrack,
+  under which a player announces them
+
+* Wed Oct 28 2026 Dirk Nehring  <dnehring@gmx.net> - 2.8.4-1
+- Update to 2.8.4 (API version 14)
+- Drop the patches merged into 2.8.4: fsf-address, posix-inet-functions,
+  08, 14, 15, 18-23, 30, 33, 35, 37-44 and 47; 24, 28, 29 and 31 went in as
+  header-free variants (static mutex/pointer/vector in the .c file)
+- Drop 13-camslot-assign-lock-scope: cCamSlot::Process() calls Assign()
+  under the slot mutex when the module is removed, so the new assignMutex
+  inverted the lock order against Assign() itself
+- Rework the rest for upstream as 01-15, by priority in four groups:
+  lifetime (01-05): new 01, 16 -> 02 (only the subtitle converter and the
+  SPU decoder, which delete their OSDs outside the main thread, use the new
+  cOsd::Delete(); ~cOsd() activates Osds[0] only if the active OSD was
+  deleted, so the skins stay as they are), 03+12+the device part of
+  04 -> 03, 01 -> 04, new 05; lost updates and torn reads (06-07):
+  36 -> 06 without the header change, 17+45 -> 07; state read without a
+  lock, by subsystem (08-13): 06 -> 08, 07+32 -> 09,
+  02+26+cTransferControl::receiverDevice -> 10, the PID part of 04 -> 11,
+  09+34 -> 12, 10+11+25+27 -> 13; globals switched for a local purpose
+  (14-15);
+  cTransfer::activated is under the transfer mutex in 2.8.4 now
+- New 01: after the EPG scan had taken the primary device, the first key
+  after a replay started without a key press (SVDRP PLAY, a plugin's SVDRP
+  command, the live plugin) switched back to the live channel, which
+  deleted the control, and then passed the key to it (SIGSEGV); the switch
+  now happens before the control is fetched
+- From the TSan runs of 2.8.4: 04 also re-reads 'active' in
+  cThread::Active() when pthread_kill() finds the thread gone; new 05:
+  the recorder thread gives the stream two seconds for the independent
+  frame it wants to end on and then ends by itself (without video, e.g.
+  when ChannelDataModified() restarts a recording with wrong PIDs, it
+  never ended and Cancel(3) killed it inside cCondWait::Wait() with the
+  mutex held); new 14: the CI TPDU dump switch is thread-local (Poll()
+  toggles it in the CI adapter thread while cCamSlot::Write() reads it
+  from an SVDRP CHAN); new 15: MarkObsoleteChannels() no longer switches
+  Setup.ShowChannelNamesWithSource off and on (cChannel::Name() reads it
+  in every thread)
+- Add vdr-recording-hook.sh, VDR's --record hook, enabled in the default
+  sysconfig: runs the drop-ins in /etc/vdr/recording-hooks.d for all ten
+  states of VDR 2.8 (before, started, after, editing, edited, deleted,
+  copying, copied, renamed, moved), each with a 10 second limit
+- vdr-shutdown.sh: use all five arguments for the log line, run the drop-ins
+  in /etc/vdr/shutdown-hooks.d first (a failing one cancels the shutdown
+  with an OSD message), SHUTDOWN_ACTION=poweroff|suspend|hibernate in
+  sysconfig instead of editing the script; sudoers allows suspend
+- vdr-set-wakeup: clear the RTC alarm when there is no timer, wake up
+  MinEventTimeout minutes after a forced stop during a recording (as VDR
+  itself does), keep the alarm at least two minutes in the future, leave it
+  alone when VDR cannot be asked
+- vdr-moveto.sh: move through VDR (SVDRP MOVR) instead of mv behind its
+  back, so VDR refuses recordings in use, copies across file systems and
+  runs the recording hook; FOLDER as VDR shows it ('/' or '~' between
+  levels), no sysconfig parsing for the video directory
+- runvdr: one pass with an associative array, same command line as before;
+  vdr-config: any vdr.pc variable (--cflags, --cxxflags, ...), --list,
+  several options per call; vdr-check-setup: point at w_scan2 and
+  dvbv5-scan instead of the retired dvb-apps
+- The hooks, vdr-set-wakeup and vdr-check-setup log to the journal when
+  run under systemd (a drop-in with StandardInput=tty, as for vaapivideo's
+  console, puts the unit's stdout on the VT), to the terminal by hand
+- Document the hooks in README.package, add a vdr-moveto.sh example to
+  reccmds.conf, %%check parses the installed scripts; its negated grep
+  checks could never fail under set -e, now explicit
+- Modernize the spec: %%bcond, %%{build_cc}/%%{build_cxx}, C++ flags from
+  %%{build_cxxflags}, %%{_sharedstatedir}/%%{_localstatedir}/%%{_rundir}
+  for the state, cache and runtime directories, no %%{?systemd_requires}
+  (the systemd scriptlets need no dependency on systemd)
+
+* Fri Oct 23 2026 Dirk Nehring  <dnehring@gmx.net> - 2.8.3-7
+- Drop 46: dvbapi 2.2.8 keeps its CAM slots until VDR has deleted the
+  devices, so VDR no longer has to wait for the device threads before the
+  plugins stop
+
+* Wed Oct 14 2026 Dirk Nehring  <dnehring@gmx.net> - 2.8.3-6
+- Add 47: the DVD subpicture decoder read its highlight flag before it was
+  ever set (UndefinedBehaviorSanitizer)
+
+* Wed Oct 14 2026 Dirk Nehring  <dnehring@gmx.net> - 2.8.3-5
+- Add 45: the audio and subtitle track menus read the track table without
+  the lock a player writes it under (ThreadSanitizer, DVD replay)
+- Add 46: stop the device threads before the plugins stop; a CAM slot's
+  receiver kept a device thread using the slot while dvbapi deleted it
+
+* Wed Oct 14 2026 Dirk Nehring  <dnehring@gmx.net> - 2.8.3-4
+- Add 43-44 for the DVD subpicture decoder: its destructor freed the
+  subpicture with delete instead of delete[] (AddressSanitizer), and a
+  command time that crossed the 32-bit PTS wrap ran at once or never
+
+* Sun Oct 11 2026 Dirk Nehring  <dnehring@gmx.net> - 2.8.3-3
+- Add 24-32 from a ThreadSanitizer run of vdr, vaapivideo, dvbapi,
+  skinflatplus and libdvbcsa on nuc and stone: the status monitor list is
+  walked without its mutex (skin display objects are cStatus monitors), index
+  file entries are read while CatchUp() reallocates them, SVDRP PLAY opened
+  the progress display on the SVDRP thread, cTransfer could still play a
+  packet while Detach() reset the parsers, the audio track mutex and the
+  player's thread lock could deadlock on a track selection during PMT
+  parsing, and plain flags were written by two threads (recordings
+  lastUpdate, volume/mute, recorder working, bonded receivers)
+- 02 also covers autoSelectPreferredSubtitleLanguage, 06 also the player's eof
+
+* Tue Oct 06 2026 Dirk Nehring  <dnehring@gmx.net> - 2.8.3-2
+- Split the StuckAtEof reset for every played frame out of
+  21-dvbplayer-growing-recording into 20-dvbplayer-stale-stuckateof: it fixes
+  stock 2.8.3 ending fast forward in short recordings early (vdr-portal
+  report), not only growing recordings; renumber 20-22 to 21-23. The built
+  code is unchanged apart from a comment
+
 * Sun Sep 27 2026 Dirk Nehring  <dnehring@gmx.net> - 2.8.3-1
 - Update to 2.8.3 (API version 14)
 - Drop the patches merged into 2.8.3: cache-threadid, hoist-receiver-lock,

diff --git a/vdr.sudoers b/vdr.sudoers
index 53b2b98..2b5567c 100644
--- a/vdr.sudoers
+++ b/vdr.sudoers
@@ -1,5 +1,5 @@
-# Privileged commands for VDR's timer-driven shutdown.  vdr-shutdown.sh
-# powers the machine off, and a hibernating setup must also set the RTC
-# wakeup itself: the service keeps running through hibernation, so the
-# unit's ExecStop hook does not fire in that case.
-vdr ALL = (root) NOPASSWD: /usr/bin/systemctl poweroff, /usr/bin/systemctl hibernate, /usr/lib/vdr/bin/vdr-set-wakeup
+# Privileged commands for VDR's shutdown hook vdr-shutdown.sh: the
+# SHUTDOWN_ACTION from /etc/sysconfig/vdr, and before a suspend or
+# hibernation the RTC wakeup (VDR keeps running then, so the unit's
+# ExecStop hook does not fire).
+vdr ALL = (root) NOPASSWD: /usr/bin/systemctl poweroff, /usr/bin/systemctl suspend, /usr/bin/systemctl hibernate, /usr/lib/vdr/bin/vdr-set-wakeup

diff --git a/vdr.sysconfig b/vdr.sysconfig
index 628be6c..735b0e0 100644
--- a/vdr.sysconfig
+++ b/vdr.sysconfig
@@ -2,10 +2,12 @@
 
 # The "master" options.  See the vdr(1) man page for the available ones.
 #
-# The default shutdown script (/usr/lib*/vdr/bin/vdr-shutdown.sh) powers
-# off through sudo; the rules it needs are packaged in /etc/sudoers.d/vdr.
+# The packaged hooks are in /usr/lib/vdr/bin, see README.package:
+# vdr-shutdown.sh runs the drop-ins in /etc/vdr/shutdown-hooks.d and then
+# SHUTDOWN_ACTION, vdr-recording-hook.sh the drop-ins in
+# /etc/vdr/recording-hooks.d for each recording event.
 #
-VDR_OPTIONS=(--lirc --vfat --shutdown=vdr-shutdown.sh)
+VDR_OPTIONS=(--lirc --vfat --shutdown=vdr-shutdown.sh --record=vdr-recording-hook.sh)
 
 # VDR_PLUGIN_ORDER is a space separated list of plugins that should be
 # loaded in a specific order.  The plugins in this list don't need to be
@@ -31,6 +33,12 @@ streamdev-client
 #
 PATH="/usr/lib/vdr/bin:$PATH"
 
+# What vdr-shutdown.sh does: poweroff, suspend or hibernate.  VDR keeps
+# running through suspend and hibernation, which some DVB drivers do not
+# survive.  The commands run through sudo, see /etc/sudoers.d/vdr.
+#
+SHUTDOWN_ACTION=poweroff
+
 # How many minutes before a recording should the VDR box wake up?
 # Some CI/CAM combinations can take quite a long time to initialize, so
 # we default to a pretty generous value here.

                 reply	other threads:[~2026-10-29  9:49 UTC|newest]

Thread overview: [no followups] expand[flat|nested]  mbox.gz  Atom feed

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=179326738028.1.15507406684894207493.rpms-vdr-039db5a79bea@fedoraproject.org \
    --to=mgansser@netcom-mail.de \
    --cc=git-commits@fedoraproject.org \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox