GCC Code Coverage Report


Directory: ./
File: playlist/Playlist.h
Date: 2026-12-01 12:27:28
Exec Total Coverage
Lines: 5 5 100.0%
Functions: 5 5 100.0%
Branches: 2 2 100.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 #include <atomic>
15 #include "AtomicSharedPtr.h"
16 #include "fpp-json.h"
17 #include <list>
18 #include <memory>
19 #include <mutex>
20 #include <string>
21 #include <vector>
22
23 #include "PlaylistEntryBase.h"
24
25 enum PlaylistStatus {
26 FPP_STATUS_IDLE = 0,
27 FPP_STATUS_PLAYLIST_PLAYING,
28 FPP_STATUS_STOPPING_GRACEFULLY,
29 FPP_STATUS_STOPPING_GRACEFULLY_AFTER_LOOP,
30 FPP_STATUS_STOPPING_NOW,
31 FPP_STATUS_PLAYLIST_PAUSED
32 };
33
34 // True while a PLAYLIST_STOPPED preset runs for an inserted playlist that has
35 // handed the player back to the one it interrupted (see Playlist.cpp).
36 bool InHandedBackStoppedPreset();
37
38 // Owned through Player::CreatePlaylist(); weak_from_this() hands an inserted
39 // child an owning reference to the level it interrupted.
40 class Playlist : public std::enable_shared_from_this<Playlist> {
41 public:
42 Playlist(std::shared_ptr<Playlist> parent = nullptr);
43 ~Playlist();
44
45 PlaylistStatus getPlaylistStatus();
46
47 // New methods
48 Json::Value LoadJSON(const std::string& filename);
49 int Load(Json::Value& config);
50 int Load(const std::string& filename);
51 PlaylistEntryBase* LoadPlaylistEntry(Json::Value entry);
52 int LoadJSONIntoPlaylist(std::vector<PlaylistEntryBase*>& playlistPart, const Json::Value& entries, int startPos, int& maxEntries);
53
54 int Start(void);
55 int StopNow(int forceStop = 0);
56 // Stops the current playlist and every playlist it was inserted into,
57 // without resuming any of them on the way out.
58 static void StopNowAllLevels(int forceStop = 0);
59 int StopGracefully(int forceStop = 0, int afterCurrentLoop = 0);
60 void SetIdle(bool exit = true);
61
62 void Pause();
63 void Resume();
64
65 int IsPlaying(void);
66
67 int Process(void);
68 // Free retired playlists and entries. Main thread only; see Playlist.cpp.
69 static void ReleaseRetired(void);
70 void ProcessMedia(void);
71 int Cleanup(void);
72 // Cleanup(), but only if the playlist is idle when checked under
73 // m_playlistMutex. For callers outside a transition that decided to
74 // clean up from an unlocked status read: another thread may have started
75 // a new playlist in between, and Cleanup() would wipe it mid-play.
76 int CleanupIfIdle(void);
77
78 // Refresh the lock-free snapshot the crash handler reads (see
79 // PlaylistDumpCrashState). Called at the points where the section or
80 // position can change; cheap enough to not need gating.
81 void UpdateCrashSnapshot(void);
82
83 int Play(const std::string& filename, const int position = -1, const int repeat = -1, const int scheduleEntry = -1, const int endPosition = -1);
84
85 void InsertPlaylistAsNext(const std::string& filename, const int startPosition = -1, const int endPos = -1);
86 void InsertPlaylistImmediate(const std::string& filename, const int startPosition = -1, const int endPos = -1);
87
88 void SetPosition(int position);
89 void SetRepeat(int repeat);
90
91 void RandomizeMainPlaylist();
92 int ShuffleMainPlaylistFrom(int position);
93
94 void Dump(void);
95
96 // Helper method for global pause between sequences
97 void StartPlayingWithGlobalPause(PlaylistEntryBase* entry);
98
99 void NextItem(void);
100 void RestartItem(void);
101 void PrevItem(void);
102
103 void GetCurrentStatus(Json::Value& result);
104 Json::Value GetCurrentEntry(void);
105 Json::Value GetInfo(void);
106 void GetInfo(Json::Value& v);
107 std::string GetPlaylistName(void);
108 // These getters are called from the scheduler, status, MQTT and API
109 // threads without m_playlistMutex, so the members behind them are atomic.
110 765444 int GetRepeat(void) { return m_repeat.load(std::memory_order_relaxed); }
111 int GetPosition(void);
112 int GetResumePosition(void);
113 int GetSize(void);
114 34 int GetLoopNumber(void) { return (m_loop.load(std::memory_order_relaxed) + 1); }
115 std::string GetConfigStr(void);
116 Json::Value GetConfig(void);
117 39232 uint64_t GetFileTime(void) { return (Json::UInt64)m_fileTime.load(std::memory_order_relaxed); }
118 int GetForceStop(void) { return m_forceStop.load(std::memory_order_relaxed); }
119
2/2
✓ Branch 0 taken 43785 times.
✓ Branch 1 taken 546149 times.
589934 int WasScheduled(void) { return (GetScheduleEntry() != -1) ? 1 : 0; }
120 1185308 int GetScheduleEntry(void) { return m_scheduleEntry.load(std::memory_order_relaxed); }
121
122 // these Positions are 0 based and includes the leadIn entries
123 uint64_t GetCurrentPosInMS();
124 uint64_t GetCurrentPosInMS(int& pos, uint64_t& posms, bool itemDefinedOnly = false);
125 uint64_t GetPosStartInMS(int pos);
126 int FindPosForMS(uint64_t& ms, bool itemDefinedOnly = false); // ms will be updated with how far into Pos it would be
127 void GetFilenamesForPos(int pos, std::string& seq, std::string& med);
128
129 int MQTTHandler(std::string topic, std::string msg);
130
131 int FileHasBeenModified(void);
132 std::string ReplaceMatches(std::string in);
133 Json::Value GetMqttStatusJSON(); // Returns Status as JSON
134
135 // Single source of truth for the human-facing status string. Derived from
136 // m_status so the string and the enum can never disagree: a paused playlist
137 // used to report "playing" because Pause() moved only the enum while the
138 // old m_currentState string mirror had no paused value.
139 static const char* PlaylistStatusToString(PlaylistStatus status);
140
141 // Number of playlists on the chain: 1 plus each one an insertion
142 // interrupted (the m_parent chain).
143 int GetLevelCount();
144
145 private:
146 void GetParentPlaylistNames(std::list<std::string>& names);
147 int ReloadPlaylist(void);
148 void ReloadIfNeeded(void);
149 void SwitchToMainPlaylist(void);
150 void SwitchToLeadOut(void);
151
152 bool WillStopAfterCurrent();
153
154 // Ready the media of the entry that plays next while the current one is
155 // in its last second (PrepareMediaOutput()), so the next video starts
156 // without building its pipeline. Only a guess: what really plays next
157 // is decided as before, and claims or discards what was prepared.
158 void PrepareNextIfDue();
159 // The entry that plays when the current one ends, or nullptr where that
160 // isn't certain yet (an insert, a branch, a pause between items, a stop).
161 // *ends is set where the playlist itself ends with the current entry.
162 PlaylistEntryBase* PeekNextEntry(bool* ends = nullptr);
163 void PrepareInsertedPlaylist();
164 // An inserted playlist ending hands back to the playlist it interrupted,
165 // which goes on with its next entry: prepare that one.
166 void PrepareParentsNext();
167 void PrepareNextOnResume();
168 PlaylistEntryBase* m_preparedAfter = nullptr; // entry whose successor was prepared this pass
169 // The order the main playlist takes at its next pass, when it is
170 // reshuffled each pass and that pass's first entry was prepared: the
171 // shuffle is drawn then and kept. Cleared with the entries it points at.
172 std::vector<PlaylistEntryBase*> m_nextShuffle;
173 std::vector<PlaylistEntryBase*> ShuffledMainPlaylist() const;
174
175 // LoadJSONIntoPlaylist(), recording where each of the section's rows (as
176 // the playlist file and editor number them) starts in the loaded entries.
177 int LoadSection(std::vector<PlaylistEntryBase*>& part, const Json::Value& entries, int startPos,
178 int& maxEntries, std::vector<int>* rowStart);
179 const std::vector<int>& CurrentSectionRows() const;
180 static int RowToSectionPosition(const std::vector<int>& rows, int row, int sectionSize);
181 static int SectionPositionToRow(const std::vector<int>& rows, int pos);
182 int FileRowToPosition(int row);
183
184 // A command reaches a playlist through a snapshot of the current one taken
185 // before it gets this playlist's lock. If the player switched playlists in
186 // between -- an inserted playlist started or finished -- the command is for
187 // whichever playlist is current now: a stop landing on the parent that was
188 // just paused, or a Next Item starting the parent's next entry alongside
189 // the inserted one. Returns that playlist, or null if it is this one.
190 // The current playlist only changes while the outgoing playlist's lock is
191 // held, so called under m_playlistMutex the answer can't go stale. Every
192 // public command method checks it first and forwards.
193 std::shared_ptr<Playlist> CurrentIfNotThis(void);
194 int StopGracefullyImpl(int forceStop, int afterCurrentLoop);
195 Playlist* SwitchToInsertedPlaylist(bool isStopping = false);
196
197 // The entry at the current section position, or nullptr if there is none.
198 // "None" is a normal state, not an error: m_sectionPosition is allowed to
199 // sit at exactly m_currentSection->size() while the playlist is between
200 // items, and m_currentSection is null until a playlist is loaded. Every
201 // access to the current entry goes through here so that single guard has
202 // one home. Caller must hold m_playlistMutex.
203 PlaylistEntryBase* CurrentEntry();
204
205 // Written under m_playlistMutex, but read by unlocked getters from other
206 // threads (status paths, the scheduler) -- atomic so those reads are
207 // well-defined; volatile never made them so.
208 std::atomic<PlaylistStatus> m_status;
209
210 // The level this one interrupted, owned: a thread holding a snapshot of a
211 // level can walk to every parent it still links to (status breadcrumbs,
212 // SetIdle's hand-back, a graceful stop) while the main loop releases
213 // levels, and each parent stays alive until the last level linking to it
214 // lets go. A level is cut loose (nulled) when it is retired, so a retired
215 // level doesn't keep its parent alive either.
216 AtomicSharedPtr<Playlist> m_parent;
217 std::string m_filename;
218 std::string m_name;
219 std::string m_desc;
220 // True when this playlist was synthesized on the fly from a bare media
221 // file -- Playlist::Load(filename) with a .fseq/.mp3/... name builds a
222 // one-entry playlist NAMED after the file. Set under m_playlistMutex in
223 // Load(filename) and Cleanup(), alongside m_name; read under the same
224 // lock in GetCurrentStatus(), which publishes it as
225 // current_playlist.generated so the UI can tell "user pressed Play on a
226 // file" apart from "a saved playlist is playing". Never true for a
227 // playlist loaded from a .json file.
228 bool m_generatedOnTheFly = false;
229 // Atomic, read lock-free by the inline getters above. Each is the same
230 // size and in the same place as the plain field it replaces, so a plugin
231 // built against the old header still reads the right value.
232 std::atomic<int> m_repeat;
233 std::atomic<int> m_loop;
234 int m_loopCount;
235 int m_random;
236 int m_blankAtEnd;
237 long long m_startTime;
238 int m_subPlaylistDepth;
239 std::atomic<int> m_scheduleEntry;
240 std::atomic<int> m_forceStop;
241 int m_stopAtPos;
242 int m_loadStartPos;
243 int m_loadEndPos;
244
245 std::atomic<time_t> m_fileTime;
246 Json::Value m_config;
247 time_t m_configTime;
248 Json::Value m_playlistInfo;
249
250 std::string m_currentSectionStr;
251 int m_sectionPosition;
252 int m_startPosition;
253
254 // Global pause between sequences feature
255 int m_globalPauseBetweenSequencesMS;
256 bool m_isInGlobalPause;
257 bool m_shouldStartGlobalPause;
258 long long m_globalPauseStartTime;
259
260 // A repeating main playlist whose every entry finishes at once (command
261 // entries only) used to restart on every main loop pass, about a
262 // thousand times a second. A pass shorter than MIN_INSTANT_PASS_MS holds
263 // the next one until m_loopHoldUntilMS (see the repeat in Process()).
264 // A command entry that navigates its own playlist (Next Playlist Item
265 // alone in a repeating list) restarts through Start() instead, which this
266 // does not cover; the notification cascade limit bounds that one.
267 long long m_loopStartMS = 0;
268 long long m_loopHoldUntilMS = 0;
269 bool m_warnedInstantLoop = false;
270
271 std::string m_insertedPlaylist;
272 int m_insertedPlaylistPosition;
273 int m_insertedPlaylistEndPosition;
274
275 // NOTE: the old startNewPlaylist* members (deferred re-entrant start
276 // requests) moved to file-scope state in Playlist.cpp — the request
277 // belongs to the player, not to one Playlist instance, since the active
278 // instance can be swapped/queued for cleanup between defer and replay.
279
280 // The body of Play(); public Play() defers re-entrant calls, PlayImpl
281 // executes. Also called directly by SwitchToInsertedPlaylist(), which
282 // must start the inserted child inline within the parent's transition.
283 int PlayImpl(const std::string& filename, const int position, const int repeat, const int scheduleEntry, const int endPosition);
284 // The body of StopNow(); same public-defers / Impl-executes split.
285 int StopNowImpl(int forceStop = 0);
286 static void StopNowAllLevelsImpl(int forceStop);
287
288 std::recursive_mutex m_playlistMutex;
289
290 std::vector<PlaylistEntryBase*> m_leadIn;
291 std::vector<PlaylistEntryBase*> m_mainPlaylist;
292 std::vector<PlaylistEntryBase*> m_leadOut;
293 std::vector<PlaylistEntryBase*>* m_currentSection;
294
295 // Members below are appended rather than grouped with their relatives so
296 // that the offsets of everything above stay put for already-built plugins.
297
298 // The status Pause() replaced, restored by Resume(). A playlist paused
299 // while stopping gracefully must keep stopping once resumed.
300 PlaylistStatus m_statusBeforePause = FPP_STATUS_PLAYLIST_PLAYING;
301
302 // m_name is written under m_playlistMutex (Load, Cleanup) but read by the
303 // scheduler and status threads through GetPlaylistName() without it --
304 // a copy racing the assignment read a freed buffer. Writers hold both;
305 // GetPlaylistName() takes only this one, so it never waits on a playlist
306 // transition and never orders this lock against the scheduler's.
307 mutable std::mutex m_nameLock;
308
309 // For each section, the index in m_leadIn / m_mainPlaylist / m_leadOut
310 // where each row of the playlist file starts (-1 for rows not loaded).
311 // A sub-playlist row expands to several entries, so file rows -- what a
312 // Branch's item number, a resume position and Start At Item count -- and
313 // loaded positions differ once one appears.
314 std::vector<int> m_leadInRows;
315 std::vector<int> m_mainRows;
316 std::vector<int> m_leadOutRows;
317 };
318
319 // Source-compatibility façade for the old `extern Playlist* playlist;` global.
320 //
321 // The player now owns its playlists through shared_ptr (see Player.h), so
322 // nothing in-tree touches this: FPP's own code calls Player::INSTANCE, which
323 // snapshots the current playlist per call. External plugins, however, were
324 // written against a raw global and dereference it as `playlist->Method(...)`.
325 //
326 // That expression still compiles, through two chained operator->s: PlaylistRef
327 // hands back a PlaylistHandle holding a snapshot, and the handle's operator->
328 // yields the raw pointer. The handle is a temporary of the full expression, so
329 // the snapshot — and therefore the instance — outlives the call even if the
330 // main loop retires that playlist mid-call. That makes the old plugin
331 // expression lifetime-safe rather than merely still-compiling.
332 //
333 // ABI is NOT preserved (this used to be a pointer object). That was safe only
334 // because it landed before 10.0 shipped, inside the plugin API 6 development
335 // window, so no released API-6 plugin saw the old form. Plugins are not
336 // rebuilt after an FPPOS reflash, and prebuilt ones never are, so
337 // PlaylistHandle's layout (one shared_ptr, used inline by plugin code) is
338 // plugin ABI now: changing it needs an FPP_PLUGIN_API_VERSION bump
339 // (Plugin.h). See .claude/PLUGIN-ABI.md.
340 //
341 // Before Player::Init() the snapshot is empty and `playlist->` dereferences
342 // null, exactly as the old NULL-initialized global did. It is deliberately not
343 // papered over with a dummy instance: constructing a Playlist needs Events,
344 // PluginManager and CommandManager, so a plugin calling this from its own
345 // static initialization has a startup-order bug that a stand-in would hide.
346 class PlaylistHandle {
347 public:
348 Playlist* operator->() const { return p.get(); }
349 std::shared_ptr<Playlist> p;
350 };
351
352 class PlaylistRef {
353 public:
354 PlaylistHandle operator->() const;
355 // So `if (playlist)` in external code still compiles and still means
356 // "is there a playlist to talk to".
357 explicit operator bool() const;
358 };
359
360 extern PlaylistRef playlist;
361
362 // Write the last-known playing state to fd for a crash report.
363 //
364 // Reads a snapshot of plain scalars rather than the live Playlist, on purpose:
365 // the crash handler cannot take m_playlistMutex (the faulting thread may hold
366 // it, and blocking there hangs the process instead of producing a report), and
367 // it cannot walk a std::string or vector that another thread is mid-update.
368 // A field may be one update stale or torn; that is worth far more than nothing.
369 void PlaylistDumpCrashState(int fd);
370