GCC Code Coverage Report


Directory: ./
File: Sequence.h
Date: 2026-12-01 12:27:28
Exec Total Coverage
Lines: 5 5 100.0%
Functions: 4 4 100.0%
Branches: 0 0 -%

Line Branch Exec Source
1 #pragma once
2 /*
3 * This file is part of the Falcon Player (FPP) and is Copyright (C)
4 * 2013-2022 by the Falcon Player Developers.
5 *
6 * The Falcon Player (FPP) is free software, and is covered under
7 * multiple Open Source licenses. Please see the included 'LICENSES'
8 * file for descriptions of what files are covered by each license.
9 *
10 * This source file is covered under the LGPL v2.1 as described in the
11 * included LICENSE.LGPL file.
12 */
13
14 // PLUGIN API: native plugins compile against this header and are loaded with
15 // dlopen().
16 // - Plugins use the global `sequence` and call its methods by symbol
17 // (SendBlankingData, ...), and rely on FPPD_MAX_CHANNELS.
18 // Data layout here is NOT plugin ABI, so members can change freely. Changing
19 // or removing a signature a plugin calls is: keep the old one as an overload
20 // (as Timers::addPeriodicTimer does) or bump FPP_PLUGIN_API_VERSION in
21 // Plugin.h. See .claude/PLUGIN-ABI.md for which plugins use what.
22
23 #include <stdio.h>
24 #include <string>
25
26 #include <atomic>
27 #include <condition_variable>
28 #include <list>
29 #include <map>
30 #include <memory>
31 #include <mutex>
32 #include <thread>
33 #include <vector>
34
35 #include "AtomicSharedPtr.h"
36 #include "fseq/FSEQFile.h"
37
38 #define FPPD_MAX_CHANNELS (8192 * 1024)
39 #define DATA_DUMP_SIZE 28
40
41 // reserve 4 channels of 0 and 4 channels of 0xFF for indexes
42 // that require one or the other
43 #define FPPD_OFF_CHANNEL FPPD_MAX_CHANNELS
44 #define FPPD_WHITE_CHANNEL (FPPD_MAX_CHANNELS + 4)
45 #define FPPD_MAX_CHANNEL_NUM (FPPD_WHITE_CHANNEL + 4)
46
47 class Sequence {
48 public:
49 Sequence();
50 ~Sequence();
51
52 int IsSequenceRunning(void);
53 int IsSequenceRunning(const std::string& filename);
54 int OpenSequenceFile(const std::string& filename, int startFrame = 0, int startSecond = -1);
55 void StartSequence(const std::string& filename, int startFrame);
56 void StartSequence();
57 void ProcessSequenceData(int ms);
58 void SeekSequenceFile(int frameNumber);
59 // Takes the channel output thread's pending frame skip and seeks that
60 // many frames on from the frame being output. Under m_sequenceLock, which
61 // every open holds while it cancels the pending skip, so a skip counted
62 // from one open's position is never applied to the next: a remote's stale
63 // sync packet from the last play-through of the same file used to jump the
64 // next one to its end.
65 void SkipFrames(std::atomic_int& skip);
66 void ReadSequenceData(bool forceFirstFrame = false);
67 void SendSequenceData(void);
68 void SendBlankingData(void);
69 void CloseIfOpen(const std::string& filename);
70 void CloseSequenceFile(void);
71 // Every OpenSequenceFile() starts a new generation. Closing by
72 // generation closes the file only if no other has been opened since:
73 // a sequence left to play out the end of its song's sound
74 // (PlaylistEntrySequence::StopAfter()) must not close the next one.
75 uint64_t OpenGeneration();
76 void CloseSequenceFileIfStill(uint64_t generation);
77 void ToggleSequencePause(void);
78 void SingleStepSequence(void);
79 void SingleStepSequenceBack(void);
80 int SequenceIsPaused(void);
81
82 bool hasBridgeData();
83 186766 bool isDataProcessed() const { return m_dataProcessed.load(std::memory_order_acquire); }
84 18912 void setDataNotProcessed() { m_dataProcessed = false; }
85
86 // Advanced by the output thread every frame and read by status, the
87 // playlist and the crash handler from other threads.
88 std::atomic_int m_seqMSDuration;
89 std::atomic_int m_seqMSElapsed;
90 std::atomic_int m_seqMSRemaining;
91 char* m_seqData;
92 std::string m_seqFilename;
93
94 // Every read of m_seqFilename from a thread that is not holding
95 // m_sequenceLock must go through this. The open/close paths reassign the
96 // string, and a reallocating assignment hands a concurrent raw reader a
97 // freed buffer; copying under m_seqFilenameLock is the only safe read.
98 std::string GetSeqFilenameCopy() const;
99
100 // Run every queued sequence preset now, on the calling thread. Normally
101 // driven by the main-loop timer queuePreset() arms; called directly once
102 // during shutdown, because a preset queued in the last loop iteration
103 // (a sequence that ended, or a stop command, right as the loop exits) has
104 // no later tick to fire on and would otherwise be dropped. MUST be called
105 // with no sequence lock held -- presets run arbitrary commands.
106 void drainPendingPresets();
107
108 173062 int GetSeqStepTime() const { return m_seqStepTime; }
109 void BlankSequenceData(bool clearBridge = false);
110
111 // expireMS is on the GetMonotonicTimeMS() clock.
112 void SetBridgeData(uint8_t* data, int startChannel, int len, uint64_t expireMS);
113
114 // Bridge data arrives in bursts (one recvmmsg drain can be hundreds of
115 // packets). WriteBridgeData copies one packet's channels into the bridge
116 // buffer without touching the range bookkeeping; CommitBridgeRanges then
117 // records all of a burst's ranges under a single lock acquisition.
118 // SetBridgeData above is the two combined, for single-packet callers.
119 bool WriteBridgeData(uint8_t* data, int startChannel, int len);
120 void CommitBridgeRanges(const std::vector<std::pair<uint32_t, uint32_t>>& ranges, uint64_t expireMS);
121
122 private:
123 void ProcessVariableHeaders();
124 void SetLastFrameData(FSEQFile::FrameData* data);
125
126 // A sequence file we are asked to play that isn't present here. The
127 // "does not exist" warning carries a timeout so it clears itself once the
128 // player moves on, but a remote gets no second open attempt after the
129 // first failure (m_seqFilename is left set, so StartSequence short-circuits),
130 // so the warning has to be re-armed from the sync path or it expires while
131 // the sequence is still playing on the player.
132 void SetMissingSequenceWarning(const std::string& filename, const std::string& warning);
133 void RefreshMissingSequenceWarning();
134 void ClearMissingSequenceWarning();
135
136 void setBridgePrioritySetting(const std::string& value);
137 bool m_prioritize_sequence_over_bridge;
138 bool m_warn_if_bridging = false;
139
140 class BridgeRangeData {
141 public:
142 3066 BridgeRangeData() :
143 3066 startChannel(0) {}
144
145 uint32_t startChannel;
146 // map of len -> ms when it expires, in MOST cases, this will be a single len (like 512 for e1.31)
147 std::map<uint32_t, uint64_t> expires;
148 };
149 std::map<uint64_t, BridgeRangeData> m_bridgeRanges;
150 std::mutex m_bridgeRangesLock;
151 uint8_t* m_bridgeData;
152 // Mirrors !m_bridgeRanges.empty(); updated wherever the map is modified
153 // (under m_bridgeRangesLock) so hasBridgeData() - called several times a
154 // frame from both the main loop and the output thread - needs no lock.
155 std::atomic<bool> m_hasBridgeRanges{ false };
156 // Per-frame scratch for the merge in ProcessSequenceData, kept as a
157 // member so its allocation is reused frame to frame.
158 std::vector<std::pair<uint32_t, uint32_t>> m_bridgeRangeScratch;
159
160 AtomicSharedPtr<FSEQFile> m_seqFile;
161
162 // 2 while a file opens, 1 once its header is read, 0 when it plays. Set
163 // by whichever thread opens or starts the sequence; read by the
164 // read-ahead thread, the output thread and status.
165 std::atomic_int m_seqStarting;
166 int m_seqPaused;
167 int m_seqStepTime;
168 int m_seqSingleStep;
169 int m_seqSingleStepBack;
170 float m_seqRefreshRate;
171 int m_remoteBlankCount;
172 // Set by whichever thread processed the frame (normally the output
173 // thread) and cleared by the bridge receive path and sequence loads.
174 std::atomic<bool> m_dataProcessed;
175 int m_numSeek;
176
177 int m_blankBetweenSequences;
178
179 // A sequence that played to its end, until the next open. Guarded by
180 // m_sequenceLock. A remote whose copy is shorter than the master's
181 // finishes first, and every later sync packet for it used to reopen the
182 // file at a frame past its end -- several reopens a second, each firing
183 // SEQUENCE_STARTED/STOPPED, until the master stopped.
184 std::string m_endedSeqFilename;
185 // Sync packets for the ended sequence are ignored only from this frame
186 // on: the last two seconds of our copy, or past its end. One asking for
187 // an earlier frame means we ended early (a stale sync packet from the
188 // previous play-through of the same file jumped us to the end), and it
189 // reopens the file there, as remotes did before m_endedSeqFilename.
190 int m_endedSeqIgnoreFrom = 0;
191
192 // The name the sequence was opened as -- the master's name for it -- even
193 // when a remote is playing fallback.fseq in its place. m_seqFilename names
194 // the file actually playing; sync packets and stop packets carry this one.
195 // Matching sync against m_seqFilename alone meant a fallback never took the
196 // master's position (so the output thread gave up after two seconds) and
197 // was never stopped by the master's stop. Guarded by m_sequenceLock.
198 std::string m_seqSyncName;
199
200 // Bumped by every OpenSequenceFile() under m_sequenceLock. The open drops
201 // that lock while it sends the MultiSync open packet; if another open ran
202 // in that window, the older one stands down instead of replacing the newer
203 // file with its own (leaving the newer one's caches and triggers behind).
204 uint64_t m_openGeneration = 0;
205
206 // Both guarded by m_sequenceLock.
207 std::string m_missingSeqFilename;
208 std::string m_missingSeqWarning;
209
210 std::recursive_mutex m_sequenceLock;
211 // Covers m_seqFilename only, and is always the innermost lock taken. The
212 // three assignments to m_seqFilename all happen under m_sequenceLock, so
213 // readers that hold m_sequenceLock need nothing more; this exists for the
214 // readers that don't (the status producers, the output thread, MultiSync).
215 mutable std::mutex m_seqFilenameLock;
216
217 std::atomic_int m_lastFrameRead;
218 // Read by the read-ahead thread outside frameCacheLock (under readFileLock
219 // only), written by CloseSequenceFile() under frameCacheLock.
220 std::atomic<bool> m_doneRead;
221 // Set by the destructor while the read-ahead thread is still checking it.
222 std::atomic<bool> m_shuttingDown;
223 std::thread* m_readThread;
224 std::list<FSEQFile::FrameData*> frameCache;
225 std::list<FSEQFile::FrameData*> pastFrameCache;
226 FSEQFile::FrameData* m_lastFrameData;
227 void clearCaches();
228 std::mutex frameCacheLock;
229 std::mutex readFileLock; // lock for just the stuff needed to read from the file (m_seqFile variable)
230 std::condition_variable frameLoadSignal;
231 std::condition_variable frameLoadedSignal;
232
233 // Frame-triggered presets and effects from the file's FC/FE variable
234 // headers. Built whole by ProcessVariableHeaders() and published with the
235 // file; the output thread reads a snapshot. They used to be plain maps
236 // that open/close cleared and refilled while the output thread was
237 // looking things up in them.
238 //
239 // Each command/effect name is stored once in `names` and the frame maps
240 // hold indexes into it. An FC/FE block gives a name followed by its frame
241 // ranges, and copying the name into every range let one long name with a
242 // few million ranges expand a small header into hundreds of MB.
243 struct Triggers {
244 std::vector<std::string> names;
245 std::map<uint32_t, std::vector<uint32_t>> commandPresets;
246 std::map<uint32_t, std::vector<uint32_t>> effectsOn;
247 std::map<uint32_t, std::vector<uint32_t>> effectsOff;
248 };
249 AtomicSharedPtr<Triggers> m_triggers;
250 // Frame number of m_lastFrameData (-1 for none), set with it under
251 // frameCacheLock, so the output thread can read it without the lock --
252 // and without touching a frame another thread may be freeing.
253 std::atomic<int64_t> m_lastFrameNumber{ -1 };
254 // Last frame whose triggers have fired; reset when a file opens.
255 std::atomic<int64_t> m_lastTriggeredFrame{ -1 };
256 // FE-started effects still running. They loop, so they are stopped when
257 // the sequence closes rather than left running after it.
258 std::mutex m_triggerEffectsLock;
259 std::vector<std::string> m_triggerEffects;
260 // The trigger table m_triggerEffects belongs to, or null once it has been
261 // forgotten (closed). Guarded by m_triggerEffectsLock. The output thread
262 // can be inside FireFrameTriggers() with a snapshot of the old table while
263 // the close swaps m_triggerEffects out; an effect it starts after that
264 // swap would be recorded in a list nobody stops. It checks this under the
265 // same lock and stops such an effect itself. Compared only against a
266 // table the caller still holds a reference to, so the address cannot have
267 // been reused.
268 const Triggers* m_triggerEffectsOwner = nullptr;
269 void FireFrameTriggers();
270 void ForgetTriggers();
271
272 // Sequence-fired presets (SEQUENCE_STARTED/SEQUENCE_STOPPED and the FSEQ
273 // frame-triggered commands) must never run at the call site: the open/close
274 // paths hold m_sequenceLock (often recursively, from callers that also hold
275 // it) and SendSequenceData runs on the channel output thread under
276 // outputThreadLock, so a preset that touches the playlist deadlocks against
277 // a playlist thread opening a sequence (m_playlistMutex -> m_sequenceLock
278 // vs m_sequenceLock -> m_playlistMutex). They are queued here and drained
279 // in FIFO order by a main-loop timer with no sequence locks held.
280 std::mutex m_pendingPresetsLock;
281 std::list<std::pair<std::string, std::map<std::string, std::string>>> m_pendingPresets;
282 // Effects to stop, drained with the presets for the same reason.
283 std::list<std::string> m_pendingEffectStops;
284
285 public:
286 // Also used by outputs that fire presets from the output thread (the
287 // control channel output), for the same reason.
288 void queuePreset(const std::string& preset, std::map<std::string, std::string>&& keywords);
289
290 void ReadFramesLoop();
291
292 private:
293 // Whether m_seqFile and m_triggers are set, so the per-frame checks
294 // (IsSequenceRunning(), FireFrameTriggers()) need no lock: an
295 // AtomicSharedPtr load is a mutex and a refcount round trip, about 0.5 us
296 // on an AM335x, and the output thread asks several times a frame. Both
297 // pointers are stored only through setSeqFile()/setTriggers(), which keep
298 // these in step. Declared last so no existing member moves.
299 std::atomic<bool> m_haveSeqFile{ false };
300 std::atomic<bool> m_haveTriggers{ false };
301 void setSeqFile(std::shared_ptr<FSEQFile> f);
302 void setTriggers(std::shared_ptr<Triggers> t);
303 };
304
305 extern Sequence* sequence;
306