GCC Code Coverage Report


Directory: ./
File: non-gpl/BBShiftPanel/BBShiftPanel.h
Date: 2026-12-01 12:27:28
Exec Total Coverage
Lines: 5 7 71.4%
Functions: 4 6 66.7%
Branches: 1 2 50.0%

Line Branch Exec Source
1 #pragma once
2 /*
3 * This file is part of the Falcon Player (FPP) and is Copyright (C)
4 * 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 CC-BY-ND as described in the
11 * included LICENSE.CC-BY-ND file. This file may be modified for
12 * personal use, but modified copies MAY NOT be redistributed in any form.
13 */
14
15 #include <atomic>
16 #include <queue>
17 #include "fpp-json-fwd.h"
18 #include <string>
19 #include <thread>
20 #include <utility>
21 #include <vector>
22
23 #include "channeloutput/ChannelOutput.h"
24 #include "util/BBBPruUtils.h"
25
26 #include "../../channeloutput/Matrix.h"
27 #include "../../channeloutput/PanelMatrix.h"
28
29 // structure of the data at the start of the PRU ram
30 // that the pru program expects to see
31 typedef struct {
32 // in the DDR shared with the PRU
33 uint32_t address_dma;
34
35 union {
36 struct {
37 volatile uint16_t command;
38 volatile uint16_t result;
39 } __attribute__((__packed__));
40 struct {
41 // Standard shift register based panels where the data is shifted out row by row and the PWM
42 // is handled by the PRU code via the OE pin
43 // write data length to start, 0xFFFF to abort. will be cleared when started
44 uint16_t pixelsPerStride;
45 uint16_t numStrides;
46
47 // 2 uint32_t for each stride
48 // first uint32_t is the brightness, number of clock ticks for on
49 // second uint32_t - bit 32 is flag to output black after this row, bits 25-31 is the address, lower 24 is extra "off" time
50 // (24 slots x 32 rows: enough split-pulse budget for 12 bit
51 // color on 1/32 scan panels; ends at 0x1808 in the PRU data
52 // RAM, clear of the config areas at 0x1DF8+)
53 uint32_t brightness[24 * 32 * 2];
54 } __attribute__((__packed__));
55 struct {
56 // Panels that handle the PWM themselves, all data is shifted out and the panel displays it automatically
57 uint16_t cmd;
58 uint8_t numBlocks;
59 uint8_t numRows;
60 uint16_t buffer[4]; // buffer to get registers aligned on boundary
61 // up to 6 registers (SM16380SH takes a sixth slot; the rest use
62 // five), up to 12 bytes per clock (16 outputs), 16 clocks each.
63 // Ends at 0x490 in the PRU data RAM, clear of the chip config at
64 // PWM_CHIP_CONFIG_OFFSET (0x1DF8).
65 uint8_t registers[6 * 12 * 16];
66 } __attribute__((__packed__));
67 } __attribute__((__packed__));
68 } __attribute__((__packed__)) BBShiftPanelData;
69
70 class BBShiftPanelOutput;
71
72 // One captured register profile for a PWM driver chip: the per-colour word
73 // lists plus the grammar needed to upload them. The built-in tables live in
74 // BBShiftPanel.cpp; an imported profile (see BBShiftPanelManager::
75 // buildRegisterProfile) fills the same shape so nothing downstream has to
76 // know where the words came from.
77 struct PWMChipSeqVariant {
78 int scan;
79 const uint16_t* r;
80 const uint16_t* g;
81 const uint16_t* b;
82 };
83
84 struct PWMChipSeq {
85 const uint16_t* r;
86 const uint16_t* g;
87 const uint16_t* b;
88 int len;
89 int slots; // 5, or 6 for a chip with an extra pre-commit word
90 uint16_t extraWord; // that word; only read when slots == 6
91 bool midLatch; // send the 11 clock LAT burst
92 uint8_t scanReg; // register address holding the scan row count
93 int defaultScan; // scan rate the tables above were captured at
94 const PWMChipSeqVariant* variants;
95 int variantCount;
96 };
97
98 // The PRUSS drives every panel output on the cape as ONE frame: a single
99 // buffer whose byte lanes are the cape's data pins, one stride schedule, one
100 // shared memory ring, one pair of PRU cores. So several LED Panel Matrix
101 // outputs on the same cape (a two sided display, a column either side of a
102 // door) cannot each own that hardware - they share it here and own only their
103 // own pixel mapping into the shared frame. Since the lane for a given output
104 // is fixed by the cape pinout (see BBShiftPanelOutput::buildScatterMap),
105 // members driving different outputs scatter into disjoint bytes of the shared
106 // buffer and one bit-plane pass converts the combined result.
107 class BBShiftPanelManager {
108 public:
109 static BBShiftPanelManager INSTANCE;
110
111 // Registers a configured output. The first member fixes the frame
112 // geometry; later ones must match it and must not re-use an output that
113 // is already driven. Returns false (having warned) if they do not.
114 bool addMember(BBShiftPanelOutput* m, const Json::Value& config, const Json::Value& capeConfig);
115 void removeMember(BBShiftPanelOutput* m);
116
117 // One frame: every member scatters into the shared intermediate, then the
118 // last one to arrive triggers the single bit-plane pass, and the first
119 // SendData of the frame hands the result to the pump.
120 void prepMember(BBShiftPanelOutput* m, unsigned char* channelData);
121 void publishFrame();
122
123 void startingOutput();
124 void stoppingOutput();
125 void closeMember();
126
127 void dumpConfig();
128
129 bool isPWMPanel() const;
130 uint32_t numOutputSlots() const { return m_numOutputSlots; }
131 uint32_t numOutputRows() const { return numRows; }
132 uint32_t outputRowLen() const { return rowLen; }
133 int longestChain() const { return m_longestChain; }
134 ✗ int numOutputs() const { return m_numOutputs; }
135 int colorDepth() const { return m_colorDepth; }
136 int brightness() const { return m_brightness; }
137 uint8_t outputPinFor(int o) const { return outputPin[o]; }
138 uint8_t outputBankFor(int o) const { return outputBank[o]; }
139 uint16_t* intermediate() const { return currentChannelData; }
140 1 uint32_t intermediateSize() const { return rowLen * m_numOutputSlots * 6 * numRows; }
141
142 // the shared worker pool; members use it for their scatter pass
143 void processTasks(std::atomic<int>& counter);
144
145 private:
146 // the frame-shape settings every matrix on the cape has to agree on
147 struct PanelParams {
148 int panelWidth = 0;
149 int panelHeight = 0;
150 int panelScan = 0;
151 int colorDepth = 12;
152 int addressingMode = 0;
153 int panelType = 0;
154 int dataLayout = 0;
155 bool pwmDirectRow = false;
156 bool pwmShiftRow = false;
157 bool outputByRow = false;
158 bool outputBlankData = false;
159 bool sharedPRUSS = false;
160 std::string panelInterleave;
161 // An imported PWM register profile, replacing the chip's built-in
162 // table. regProfile[0..2] are the R/G/B word lists (equal length,
163 // empty when nothing was imported) and regProfileName identifies it
164 // in the log. See BBShiftPanel::buildRegisterProfile().
165 std::vector<uint16_t> regProfile[3];
166 std::string regProfileName;
167 // FM6373 family OE timing, in DCLK periods (the reference
168 // implementation's units) except the row period, which is in us
169 int oeClkLength = 0; // 0 = keep the historical 600ns pulse
170 int oeFirstClkLength = 0; // 0 = keep the historical 2us opener
171 int oeRowPeriodUs = 20;
172 // FM6373 family register upload grammar, in DCLK clocks
173 int regVsyncClocks = 3;
174 int regMidClocks = 11; // 0 skips the middle burst
175 int regPreClocks = 14;
176 int regSpacerClocks = 8; // 0 is valid: emit no gap at all
177 // FM6353 / ICND2153 GCLK packet lengths: pulses in the first packet
178 // after a restart and in every packet after that. 0 = the built-in
179 // 138 for both.
180 int gclkFirstPulses = 0;
181 int gclkPulses = 0;
182 };
183 static PanelParams parsePanelParams(const Json::Value& config, const Json::Value& capeConfig);
184
185 bool parseCapeConfig(const Json::Value& capeConfig);
186 bool adoptPanelParams(const PanelParams& p);
187 bool checkCompatible(const PanelParams& p) const;
188 bool rebuild();
189 void teardownHardware();
190 void teardown();
191 void computeGeometry();
192
193 void PrepDataShift();
194 bool PrepDataPWM();
195 bool waitForPWMCommandTaken();
196
197 void StopPRU(bool wait = true);
198 int StartPRU();
199
200 void buildStrideSchedule();
201 void sendPanelInitPackets();
202 uint32_t computeMaxBrightnessCycles();
203 void setupBrightnessValues();
204 bool setupPWMRegisters();
205 void setupGCLKConfig();
206 void writeFM6373SeqWord(int idx);
207 void writeDP3364SeqWord(int idx);
208
209 std::vector<BBShiftPanelOutput*> m_members;
210 // members that have arrived in this frame's PrepData; the shared bit-plane
211 // pass runs when the count reaches the member count
212 int m_preppedThisFrame = 0;
213 // set by the bit-plane pass, cleared by the frame publish, so exactly one
214 // member's SendData hands the frame over
215 bool m_framePrepped = false;
216 // balanced Starting/StoppingOutput calls across the members
217 int m_activeMembers = 0;
218 int m_openMembers = 0;
219
220 BBBPru* pru = nullptr;
221 BBBPru* pwmPru = nullptr;
222 BBShiftPanelData* pruData = nullptr;
223
224 int m_panelWidth = 0;
225 int m_panelHeight = 0;
226 int m_panelScan = 0;
227 std::string m_panelInterleave = "";
228
229 int m_addressingMode = 0;
230 // 0 = standard, 1 = FM6126A, 2 = FM6127 - panels that need their config
231 // registers clocked out before they display (see sendPanelInitPackets)
232 int m_panelType = 0;
233 // How the framebuffer is routed onto the two RGB lanes. 0 is the normal
234 // HUB75 arrangement: the lanes carry the top and bottom halves of the
235 // panel and each addressed row lights two physical rows. A full height
236 // panel (scan == height) addresses every row on its own instead, so its
237 // lanes carry the LEFT and RIGHT halves of one row - 1 and 2 select which
238 // way round. See buildScatterMap.
239 int m_dataLayout = 0;
240 // PWM panels: drive the row lines with a direct binary row number
241 // instead of the DP32020A style row shift register
242 bool m_pwmDirectRow = false;
243 // FM6373 family only: the opposite opt-in. That family shipped with the
244 // direct binary row number as its only transport, so it stays the default
245 // there and the shift register has to be asked for explicitly - see
246 // sendPWMConfig().
247 bool m_pwmShiftRow = false;
248 // FM6373: next config sequence word for the per-frame rotating refresh
249 int m_pwmSeqIdx = 0;
250 // An imported register profile replacing the chip's built-in table. The
251 // word lists are owned here because m_profSeq points into them, so the
252 // two must not be copied apart. activePWMSeq() hands out &m_profSeq once
253 // m_haveProfile is set, and the built-in table otherwise.
254 std::vector<uint16_t> m_profWords[3];
255 PWMChipSeq m_profSeq{};
256 bool m_haveProfile = false;
257 std::string m_profName;
258 int m_oeClkLength = 0;
259 int m_oeFirstClkLength = 0;
260 int m_oeRowPeriodUs = 20;
261 int m_regVsyncClocks = 3;
262 int m_regMidClocks = 11;
263 int m_regPreClocks = 14;
264 int m_regSpacerClocks = 8;
265 int m_gclkFirstPulses = 0;
266 int m_gclkPulses = 0;
267 // FM6353 / ICND2153: an imported replacement for the five fixed register
268 // words (latch lengths 4, 6, 8, 10, 2 in that order), per color. These
269 // chips have no PWMChipSeq, so this is kept apart from m_profSeq -
270 // setting m_haveProfile would route them onto the FM6373 upload.
271 uint16_t m_fixedRegs[3][5] = {};
272 bool m_haveFixedRegs = false;
273 void buildRegisterProfile(const PanelParams& p);
274 const PWMChipSeq* activePWMSeq() const;
275 // the pins this cape muxed to the PRU (only these are released on
276 // Close - a combo cape may leave pins for another driver to own)
277 std::vector<std::string> m_configuredPins;
278 std::string m_oePin = "P1-36";
279 // sharing the PRUSS with a string driver on the other PRU: single PRU,
280 // SPLIT1 ring, and never clear the shared RAM or the other PRU's memory
281 bool m_sharedPRUSS = false;
282 int m_longestChain = 0;
283 // the OE on-time is a property of the cape, not of one matrix, so the
284 // hardware brightness is the highest any member asked for; a member that
285 // wanted less scales its own gamma table down to reach it (see
286 // BBShiftPanelOutput::setupGamma)
287 int m_brightness = 10;
288 int m_colorDepth = 12;
289
290 bool m_outputByRow = false;
291 bool m_outputBlankData = false;
292
293 int m_numOutputs = 8; // number of configured outputs (from cape config)
294 int m_numOutputSlots = 8; // 8 or 16 - determines data width per pixel (6 or 12 bytes)
295 uint8_t outputPin[16] = { 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7 }; // PRU pin (0-7) per output
296 uint8_t outputBank[16] = { 0 }; // 0=first bank, 1=second bank per output
297
298 // the shared 16 bit intermediate every member scatters into
299 uint16_t* currentChannelData = nullptr;
300
301 // Four output buffers allows for double buffering and extras for the PRU to read from while the next frame is being built
302 // With 4MB of memory reserved for transfer to PRU, 12 P5 panels per output with 12bit color depth (total 3.5MB)
303 constexpr static int NUM_OUTPUT_BUFFERS = 4;
304 std::array<uint8_t*, NUM_OUTPUT_BUFFERS> outputBuffers = { nullptr, nullptr, nullptr, nullptr };
305 uint8_t currOutputBuffer = 0;
306 // scan rows in the frame: the scan for split panels, the panel height
307 // for full height ones. PrepDataShift's per-row table is this big.
308 static constexpr uint32_t MAX_SCAN_ROWS = 64;
309 uint32_t numRows = 0;
310 uint32_t rowLen = 0;
311 uint32_t maxRowLen = 0;
312
313 // Schedule of strides within one pass of all rows. Bits whose on-time is
314 // a multiple of the stride shift-out time are split into multiple shorter
315 // pulses spread across the frame which multiplies the perceived refresh
316 // rate without changing the total light output (same total on-time).
317 struct StrideSlot {
318 uint8_t bit; // color depth bit this slot displays
319 bool primary; // first slot for this bit; the pixel mapping writes here
320 uint32_t onTime; // PRU cycles the display is on for this slot
321 };
322 std::vector<StrideSlot> m_strideSchedule;
323 // per row: (dstOffset, srcOffset) frame buffer copies for the duplicated
324 // strides of split bits
325 std::vector<std::vector<std::pair<uint32_t, uint32_t>>> m_dupCopies;
326
327 // Real-time thread that streams the current frame buffer into a ring in
328 // the 32KB PRU shared memory. The PRU cannot read DDR fast enough to
329 // keep 16 outputs fed (~1.1-1.8us per 64 byte read) but reads shared
330 // memory in 18 predictable cycles. See runPumpThread() and
331 // pru/SMEMRing.hp for the layout.
332 std::thread m_pumpThread;
333 std::atomic<bool> m_pumpRunning{ false };
334 // Set while the channel output thread is idle. Shift panels only hold an
335 // image for as long as the pump keeps re-shifting it, so a panel that is
336 // not being output to is simply dark - there is nothing to refresh and no
337 // reason to spend a core streaming a blank frame. The pump acts on this
338 // only at a frame boundary; see runPumpThread.
339 std::atomic<bool> m_pumpPaused{ false };
340 // owned by the pump thread, read by StoppingOutput to wait for the park
341 std::atomic<bool> m_pumpParked{ false };
342 // set once both cores have been halted, so the park is not attempted or
343 // undone twice
344 bool m_prusPaused = false;
345 void ParkPRUs();
346 void UnparkPRUs();
347 std::atomic<uint8_t*> m_frontBuffer{ nullptr };
348 // PWM panels send one frame per DATA command; the pump streams once per
349 // sequence bump so the byte flow stays in step with the commands
350 std::atomic<uint32_t> m_pumpSeq{ 0 };
351 uint32_t m_pumpedSeq = 0;
352 // A self-PWM panel refreshes from its own engine while its row scan free
353 // runs, so a gap in the shift out shows up as the image drifting
354 // vertically rather than as a glitch. The frame is therefore not handed
355 // to the PRU until the pump has the ring as full as it will go, and the
356 // pump is woken directly rather than found by polling.
357 std::mutex m_pumpMutex;
358 std::condition_variable m_pumpCV;
359 std::atomic<uint32_t> m_pumpPrimed{ 0 };
360 uint32_t m_frameBytes = 0;
361 BBBPruSMEMRing m_ring;
362 bool m_heapBuffers = false;
363 void runPumpThread();
364
365 bool singlePRU = false;
366 std::string m_refreshWarning;
367 // set while a PWM PRU has stopped taking commands (see
368 // waitForPWMCommandTaken); the warning comes down when it answers again
369 // or the hardware is torn down
370 bool m_pwmPruStalled = false;
371 std::string m_pwmStallWarning;
372
373 std::queue<std::function<void()>> bgTasks;
374 volatile bool bgThreadsRunning = false;
375 std::mutex bgTaskMutex;
376
377 // Serializes the output thread's per-frame calls (prepMember,
378 // publishFrame, starting/stoppingOutput) against membership changes. A
379 // config reload Init()s each replacement matrix outside outputThreadLock,
380 // after the earlier ones are already live, and adding a member rebuilds
381 // the shared PRU, frame buffers and every member's scatter map.
382 std::mutex m_memberLock;
383 std::condition_variable bgTaskCondVar;
384 std::atomic<int> bgThreadCount;
385 void runBackgroundTasks();
386 void startBackgroundThreads();
387 void stopBackgroundThreads();
388
389 friend class BBShiftPanelOutput;
390 };
391
392 class BBShiftPanelOutput : public ChannelOutput {
393 public:
394 BBShiftPanelOutput(unsigned int startChannel, unsigned int channelCount);
395 virtual ~BBShiftPanelOutput();
396
397 1 virtual std::string GetOutputType() const {
398
1/2
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
2 return "BB64 Panels";
399 }
400
401 virtual int Init(Json::Value config) override;
402 virtual int Close(void) override;
403
404 virtual int SendData(unsigned char* channelData) override;
405 virtual void PrepData(unsigned char* channelData) override;
406 virtual void DumpConfig(void) override;
407
408 virtual void GetRequiredChannelRanges(const std::function<void(int, int)>& addRange) override;
409
410 virtual void OverlayTestData(unsigned char* channelData, int cycleNum, float percentOfCycle, int testType, const Json::Value& config) override;
411 ✗ virtual bool SupportsTesting() const { return true; }
412
413 virtual void StartingOutput() override;
414 virtual void StoppingOutput() override;
415
416 // called by the manager
417 2 int longestChain() const { return m_longestChain; }
418 const PanelMatrix* panelMatrix() const { return m_panelMatrix; }
419 bool usesOutput(int o) const;
420 2 int configuredBrightness() const { return m_brightness; }
421 // (re)builds this member's map into the shared frame; the manager calls
422 // this whenever the shared geometry changes
423 bool buildScatterMap();
424 void setupGamma();
425 void scatterFrame(unsigned char* channelData);
426
427 private:
428 void releaseToManager();
429
430 Matrix* m_matrix = nullptr;
431 PanelMatrix* m_panelMatrix = nullptr;
432
433 int m_longestChain = 0;
434 int m_invertedData = 0;
435 int m_brightness = 10;
436 float m_gamma = 2.2;
437
438 FPPColorOrder m_colorOrder;
439
440 int m_panels = 0;
441 int m_width = 0;
442 int m_height = 0;
443
444 uint16_t gammaCurve[256];
445
446 // The gamma scatter map sorted by destination offset so the prep loop
447 // writes sequentially (streaming writes with random byte reads are much
448 // faster than random writes at panel counts where the data far exceeds
449 // the cache). Unmapped channels are excluded entirely.
450 std::vector<uint32_t> m_scatterOffsets;
451 std::vector<uint32_t> m_scatterSrc;
452
453 std::string m_autoCreatedModelName;
454
455 // set once the manager has accepted this matrix; an output whose Init
456 // failed must never reach the manager's per-frame accounting
457 bool m_registered = false;
458 // the manager releases the cape's pins when its last open member closes,
459 // so each member has to hand its share back exactly once - Close() may be
460 // called without a destructor following, or the object may be destroyed
461 // without Close() ever having run
462 bool m_closed = false;
463
464 // guards against the output being torn down (config reload) while the
465 // channel output thread is still inside PrepData/SendData
466 std::atomic<bool> m_stopping{ false };
467 std::atomic<int> m_inFlight{ 0 };
468
469 friend class BBShiftPanelManager;
470 };
471