MayaFlux 0.5.0
Digital-First Multimedia Processing Framework
Loading...
Searching...
No Matches
VideoStreamContainer.hpp
Go to the documentation of this file.
1#pragma once
2
4
7
9struct IOService;
10}
11
12namespace MayaFlux::Kakshya {
13
14/**
15 * @class VideoStreamContainer
16 * @brief Concrete base implementation for streaming video containers.
17 *
18 * VideoStreamContainer provides a complete, concrete implementation of all
19 * StreamContainer functionality for decoded video frame data. It serves as:
20 * 1. A standalone streaming container for real-time video processing
21 * 2. A base class for specialized containers like VideoFileContainer
22 *
23 * Data is stored as uint8_t pixels in RGBA interleaved layout (matching
24 * Vulkan VK_FORMAT_R8G8B8A8_UNORM and the TextureBuffer pipeline).
25 * Each frame is width * height * channels bytes. All frames are stored
26 * contiguously in a single DataVariant.
27 *
28 * Dimensions follow VIDEO_COLOR convention:
29 * dims[0] → TIME (frame count)
30 * dims[1] → SPATIAL_Y (height)
31 * dims[2] → SPATIAL_X (width)
32 * dims[3] → CHANNEL (colour channels, typically 4 for RGBA)
33 *
34 * Reader model follows WindowContainer's pattern: a simple atomic reader
35 * count rather than per-dimension/per-channel tracking. Video frames are
36 * atomic spatial units — channel-level access is a processor concern,
37 * not a container concern.
38 *
39 * Uses virtual inheritance to support diamond inheritance when used as a
40 * base for FileContainer-derived classes.
41 */
42class MAYAFLUX_API VideoStreamContainer : public virtual StreamContainer {
43public:
44 /**
45 * @brief Construct a VideoStreamContainer with specified parameters.
46 * @param width Frame width in pixels.
47 * @param height Frame height in pixels.
48 * @param channels Colour channels per pixel (default 4 for RGBA).
49 * @param frame_rate Temporal rate in frames per second.
50 */
51 VideoStreamContainer(uint32_t width = 0,
52 uint32_t height = 0,
53 uint32_t channels = 4,
54 double frame_rate = 0.0);
55
56 ~VideoStreamContainer() override = default;
57
58 // =========================================================================
59 // NDDimensionalContainer
60 // =========================================================================
61
62 [[nodiscard]] std::vector<DataDimension> get_dimensions() const override;
63 [[nodiscard]] uint64_t get_total_elements() const override;
64 [[nodiscard]] MemoryLayout get_memory_layout() const override { return m_structure.memory_layout; }
65 void set_memory_layout(MemoryLayout layout) override;
66
67 [[nodiscard]] uint64_t get_frame_size() const override;
68 [[nodiscard]] uint64_t get_num_frames() const override;
69
70 std::vector<DataVariant> get_region_data(const Region& region) const override;
71 void set_region_data(const Region& region, const std::vector<DataVariant>& data) override;
72
73 std::vector<DataVariant> get_region_group_data(const RegionGroup& group) const override;
74 std::vector<DataVariant> get_segments_data(const std::vector<RegionSegment>& segment) const override;
75
76 [[nodiscard]] std::type_index value_element_type() const override { return typeid(uint8_t); }
77
78 [[nodiscard]] uint64_t coordinates_to_linear_index(const std::vector<uint64_t>& coordinates) const override;
79 [[nodiscard]] std::vector<uint64_t> linear_index_to_coordinates(uint64_t linear_index) const override;
80
81 void clear() override;
82
83 [[nodiscard]] const void* get_raw_data() const override;
84 [[nodiscard]] bool has_data() const override;
85
86 ContainerDataStructure& get_structure() override { return m_structure; }
87 const ContainerDataStructure& get_structure() const override { return m_structure; }
88 void set_structure(ContainerDataStructure structure) override { m_structure = structure; }
89
90 // =========================================================================
91 // Ring buffer streaming API
92 // =========================================================================
93
94 /**
95 * @brief Allocate m_data[0] as a ring of ring_capacity frames.
96 *
97 * Switches the container from flat mode to ring mode. m_data[0] is
98 * resized to ring_capacity x frame_byte_size. m_num_frames is set to
99 * total_frames so processors see the full temporal extent. Pixel data
100 * is indexed by frame_index % ring_capacity.
101 *
102 * @param total_frames Total frames in the source (file, stream, etc).
103 * @param ring_capacity Number of frame slots (must be power of 2).
104 * @param width Frame width in pixels.
105 * @param height Frame height in pixels.
106 * @param channels Colour channels per pixel.
107 * @param frame_rate Frame rate in fps.
108 * @param refill_threshold Frames of look-ahead below which refill callback fires.
109 * @param reader_id The current class ID registered at the stream/file-read source
110 */
111 void setup_ring(uint64_t total_frames,
112 uint32_t ring_capacity,
113 uint32_t width,
114 uint32_t height,
115 uint32_t channels,
116 double frame_rate,
117 uint32_t refill_threshold,
118 uint64_t reader_id = 0);
119
120 /**
121 * @brief Mutable pointer into m_data[0] for the decode thread to write into.
122 * @param frame_index Absolute frame index; mapped to slot via modulo.
123 * @return Pointer into the pixel vector, or nullptr if not in ring mode.
124 */
125 [[nodiscard]] uint8_t* mutable_slot_ptr(uint64_t frame_index);
126
127 /**
128 * @brief Publish a decoded frame. Sets validity, pushes to ready queue,
129 * notifies any thread blocked in get_frame_pixels().
130 * @param frame_index Absolute frame index just written.
131 */
132 void commit_frame(uint64_t frame_index);
133
134 /**
135 * @brief Invalidate all ring slots. Called before seek.
136 */
137 void invalidate_ring();
138
139 /**
140 * @brief Check if a frame is currently valid in the ring.
141 * @param frame_index Absolute frame index.
142 */
143 [[nodiscard]] bool is_frame_available(uint64_t frame_index) const;
144
145 /**
146 * @brief True if the container is operating in ring mode.
147 */
148 [[nodiscard]] bool is_ring_mode() const { return m_ring_capacity > 0; }
149
150 [[nodiscard]] uint32_t get_ring_capacity() const { return m_ring_capacity; }
151 [[nodiscard]] uint64_t get_total_source_frames() const { return m_total_source_frames; }
152
153 /**
154 * @brief Set the number of frames below which the refill callback fires.
155 * Called by the reader before or immediately after setup_ring().
156 * @param threshold Frames of look-ahead below which notification fires.
157 */
159 {
160 m_refill_threshold = threshold;
161 }
162
163 /**
164 * @brief Advance the container's view of how many frames have been decoded.
165 * Called by the decode thread (via VideoFileReader) after commit_frame().
166 * Monotonically increasing; never decremented (seek resets via setup_ring).
167 * @param frame_index The highest frame index just committed.
168 */
169 void advance_cache_head(uint64_t frame_index)
170 {
171 uint64_t prev = m_cache_head.load(std::memory_order_relaxed);
172 while (frame_index > prev
173 && !m_cache_head.compare_exchange_weak(prev, frame_index,
174 std::memory_order_release, std::memory_order_relaxed)) { }
175 }
176
177 /**
178 * @brief Total frame count known at construction / setup_ring() time.
179 * Non-zero even before any frames are decoded.
180 */
181 [[nodiscard]] uint64_t get_cache_head() const
182 {
183 return m_cache_head.load(std::memory_order_acquire);
184 }
185
186 /**
187 * @brief Processed frame at @p frame_index as a normalised float span.
188 *
189 * Valid after FrameAccessProcessor has written processed_data.
190 * uint8_t source values are divided by 255.0f. float source is
191 * zero-copy. Returns empty span if frame_index is out of range or
192 * the variant holds a non-pixel type.
193 *
194 * The cache covers the last requested frame_index only. A call with
195 * a different index invalidates and recomputes.
196 *
197 * @param frame_index Zero-based index into processed_data. Defaults to 0.
198 * @return Normalised float span, w * h * channels elements.
199 */
200 [[nodiscard]] std::span<const float> processed_frame_as_float(
201 uint64_t frame_index = 0) const;
202
203 // =========================================================================
204 // RegionGroup management
205 // =========================================================================
206
207 void add_region_group(const RegionGroup& group) override;
208 RegionGroup get_region_group(const std::string& name) const override;
209 std::unordered_map<std::string, RegionGroup> get_all_region_groups() const override;
210 void remove_region_group(const std::string& name) override;
211
212 bool is_region_loaded(const Region& region) const override;
213 void load_region(const Region& region) override;
214 void unload_region(const Region& region) override;
215
216 // =========================================================================
217 // Read position and looping
218 // =========================================================================
219
220 void set_read_position(const std::vector<uint64_t>& position) override;
221 void update_read_position_for_channel(size_t channel, uint64_t frame) override;
222 [[nodiscard]] const std::vector<uint64_t>& get_read_position() const override;
223 void advance_read_position(const std::vector<uint64_t>& frames) override;
224 [[nodiscard]] bool is_at_end() const override;
225 void reset_read_position() override;
226
227 [[nodiscard]] uint64_t get_temporal_rate() const override;
228 [[nodiscard]] uint64_t time_to_position(double time) const override;
229 [[nodiscard]] double position_to_time(uint64_t position) const override;
230
231 void set_looping(bool enable) override;
232 [[nodiscard]] bool is_looping() const override { return m_looping_enabled; }
233 void set_loop_region(const Region& region) override;
234 [[nodiscard]] Region get_loop_region() const override;
235
236 [[nodiscard]] bool is_ready() const override;
237 [[nodiscard]] std::vector<uint64_t> get_remaining_frames() const override;
238 uint64_t read_sequential(std::span<double> output, uint64_t count) override;
239 uint64_t peek_sequential(std::span<double> output, uint64_t count, uint64_t offset) const override;
240
241 // =========================================================================
242 // Processing state
243 // =========================================================================
244
245 [[nodiscard]] ProcessingState get_processing_state() const override { return m_processing_state.load(); }
246 void update_processing_state(ProcessingState new_state) override;
247
248 void register_state_change_callback(
249 std::function<void(const std::shared_ptr<SignalSourceContainer>&, ProcessingState)> callback) override;
250 void unregister_state_change_callback() override;
251
252 [[nodiscard]] bool is_ready_for_processing() const override;
253 void mark_ready_for_processing(bool ready) override;
254
255 void create_default_processor() override;
256 void process_default() override;
257 void set_default_processor(const std::shared_ptr<DataProcessor>& processor) override;
258 [[nodiscard]] std::shared_ptr<DataProcessor> get_default_processor() const override;
259
260 std::shared_ptr<DataProcessingChain> get_processing_chain() override;
261 void set_processing_chain(const std::shared_ptr<DataProcessingChain>& chain) override { m_processing_chain = chain; }
262
263 // =========================================================================
264 // Reader tracking (WindowContainer-style atomic counting)
265 // =========================================================================
266
267 uint32_t register_dimension_reader(uint32_t dimension_index) override;
268 void unregister_dimension_reader(uint32_t dimension_index) override;
269 [[nodiscard]] bool has_active_readers() const override;
270 void mark_dimension_consumed(uint32_t dimension_index, uint32_t reader_id) override;
271 [[nodiscard]] bool all_dimensions_consumed() const override;
272
273 // =========================================================================
274 // Processing token
275 // =========================================================================
276
277 void reset_processing_token() override { m_processing_token_channel.store(-1); }
278
279 bool try_acquire_processing_token(int channel) override
280 {
281 int expected = -1;
282 return m_processing_token_channel.compare_exchange_strong(expected, channel);
283 }
284
285 [[nodiscard]] bool has_processing_token(int channel) const override
286 {
287 return m_processing_token_channel.load() == channel;
288 }
289
290 void invalidate_float_frame_cache(uint32_t slot_index = 0);
291
292 // =========================================================================
293 // Data access
294 // =========================================================================
295
296 const std::vector<DataVariant>& get_data() override { return m_data; }
297
298 DataAccess channel_data(size_t channel) override;
299 std::vector<DataAccess> all_channel_data() override;
300
301 std::vector<DataVariant>& get_processed_data() override { return m_processed_data; }
302 const std::vector<DataVariant>& get_processed_data() const override { return m_processed_data; }
303
304 void mark_buffers_for_processing(bool) override { }
305 void mark_buffers_for_removal() override { }
306
307 // =========================================================================
308 // Video-specific accessors
309 // =========================================================================
310
311 [[nodiscard]] uint32_t get_width() const { return m_width; }
312 [[nodiscard]] uint32_t get_height() const { return m_height; }
313 [[nodiscard]] uint32_t get_channels() const { return m_channels; }
314 [[nodiscard]] double get_frame_rate() const { return m_frame_rate; }
315
316 /**
317 * @brief Get raw pixel data for a single frame as uint8_t span.
318 * @param frame_index Zero-based frame index.
319 * @return Span of pixel bytes for the frame, empty if out of range.
320 */
321 [[nodiscard]] std::span<const uint8_t> get_frame_pixels(uint64_t frame_index) const;
322
323 /**
324 * @brief Get the total byte size of one frame (width * height * channels).
325 */
326 [[nodiscard]] size_t get_frame_byte_size() const;
327
328protected:
329 void setup_dimensions();
330 void notify_state_change(ProcessingState new_state);
331
332 uint32_t m_width = 0;
333 uint32_t m_height = 0;
334 uint32_t m_channels = 4;
335 double m_frame_rate = 0.0;
336 uint64_t m_num_frames = 0;
337
339
340 std::vector<DataVariant> m_data;
341 std::vector<DataVariant> m_processed_data;
342
346
347 std::atomic<ProcessingState> m_processing_state { ProcessingState::IDLE };
348 std::atomic<int> m_processing_token_channel { -1 };
349
350 std::function<void(const std::shared_ptr<SignalSourceContainer>&, ProcessingState)> m_state_callback;
351 std::shared_ptr<DataProcessor> m_default_processor;
352 std::shared_ptr<DataProcessingChain> m_processing_chain;
353
354 std::unordered_map<std::string, RegionGroup> m_region_groups;
355
356 std::atomic<uint64_t> m_read_position { 0 };
357 bool m_looping_enabled {};
359
360 std::atomic<uint32_t> m_registered_readers { 0 };
361 std::atomic<uint32_t> m_consumed_readers { 0 };
362
363 // =========================================================================
364 // Ring buffer state (inactive when m_ring_capacity == 0)
365 // =========================================================================
366
367 uint32_t m_ring_capacity { 0 };
368 uint64_t m_total_source_frames { 0 };
369
370 std::vector<std::atomic<uint64_t>> m_slot_frame;
371
372 static constexpr uint32_t READY_QUEUE_CAPACITY = 256;
374
375 /**
376 * @brief Highest frame index committed by the decode thread.
377 * Written by the decode thread via commit_frame(); read by
378 * update_read_position_for_channel() to compute buffered-ahead count.
379 */
380 std::atomic<uint64_t> m_cache_head { 0 };
381
382 /**
383 * @brief Trigger refill when (m_cache_head - read_position) drops below this.
384 * Set by the reader at load_into_container() time.
385 * A value of 0 disables threshold notification.
386 */
387 uint32_t m_refill_threshold { 0 };
388
389 Registry::Service::IOService* m_io_service { nullptr }; // non-owning; owned by registry
390 uint64_t m_io_reader_id { 0 };
391
392 [[nodiscard]] uint32_t slot_for(uint64_t frame_index) const
393 {
394 return static_cast<uint32_t>(frame_index % m_ring_capacity);
395 }
396
397 [[nodiscard]] DataSpanVariant get_frame_span_impl(uint64_t frame_index) const override
398 {
399 return { get_frame_typed(frame_index) };
400 }
401
402 void get_frames_impl(
403 void* output,
404 size_t count,
405 uint64_t start_frame,
406 uint64_t num_frames,
407 const std::type_info& type) const override;
408
409 void get_value_impl(const std::vector<uint64_t>& coords,
410 void* out, const std::type_info& type) const override;
411
412 void set_value_impl(const std::vector<uint64_t>& coords,
413 const void* in, const std::type_info& type) override;
414
415private:
416 [[nodiscard]] std::span<const uint8_t> get_frame_typed(uint64_t frame_index) const
417 {
418 return get_frame_pixels(frame_index);
419 }
420
421 void get_frames_typed(std::span<uint8_t> output, uint64_t start_frame, uint64_t num_frames) const;
422
423 mutable std::vector<std::vector<float>> m_float_frame_cache;
424 mutable std::vector<std::atomic<bool>> m_float_frame_dirty;
425
426 void reset_float_frame_cache();
427};
428
429} // namespace MayaFlux::Kakshya
uint32_t width
Definition Decoder.cpp:66
size_t count
std::shared_ptr< Core::VKImage > output
float threshold
float offset
uint32_t height
Type-erased accessor for NDData with semantic view construction.
Data-driven interface for temporal stream containers with navigable read position.
std::shared_ptr< DataProcessor > m_default_processor
const ContainerDataStructure & get_structure() const override
uint64_t get_cache_head() const
Total frame count known at construction / setup_ring() time.
ContainerDataStructure & get_structure() override
Get the data structure defining this container's layout.
void set_refill_threshold(uint32_t threshold)
Set the number of frames below which the refill callback fires.
std::shared_ptr< DataProcessingChain > m_processing_chain
std::function< void(const std::shared_ptr< SignalSourceContainer > &, ProcessingState)> m_state_callback
std::vector< DataVariant > & get_processed_data() override
Get a mutable reference to the processed data buffer.
std::vector< std::atomic< uint64_t > > m_slot_frame
ProcessingState get_processing_state() const override
Get the current processing state of the container.
MemoryLayout get_memory_layout() const override
Get the memory layout used by this container.
DataSpanVariant get_frame_span_impl(uint64_t frame_index) const override
Implementation-specific method to retrieve a frame span.
Memory::LockFreeQueue< uint64_t, READY_QUEUE_CAPACITY > m_ready_queue
std::type_index value_element_type() const override
Runtime query for the native scalar element type of this container.
bool is_ring_mode() const
True if the container is operating in ring mode.
std::vector< std::atomic< bool > > m_float_frame_dirty
bool try_acquire_processing_token(int channel) override
std::vector< std::vector< float > > m_float_frame_cache
const std::vector< DataVariant > & get_data() override
Get a reference to the raw data stored in the container.
void mark_buffers_for_removal() override
Mark associated buffers for removal from the system.
std::unordered_map< std::string, RegionGroup > m_region_groups
void advance_cache_head(uint64_t frame_index)
Advance the container's view of how many frames have been decoded.
bool has_processing_token(int channel) const override
void set_processing_chain(const std::shared_ptr< DataProcessingChain > &chain) override
Set the processing chain for this container.
const std::vector< DataVariant > & get_processed_data() const override
Get a const reference to the processed data buffer.
void mark_buffers_for_processing(bool) override
Mark associated buffers for processing in the next cycle.
uint32_t slot_for(uint64_t frame_index) const
void set_structure(ContainerDataStructure structure) override
Set the data structure for this container.
bool is_looping() const override
Check if looping is enabled for the stream.
std::span< const uint8_t > get_frame_typed(uint64_t frame_index) const
Concrete base implementation for streaming video containers.
Policy-driven unified circular buffer implementation.
Single-writer multiple-reader sequence lock for fixed-size data regions.
Definition SeqLock.hpp:44
ProcessingState
Represents the current processing lifecycle state of a container.
typename detail::span_const_from_vector_variant< DataVariant >::type DataSpanVariant
Definition NDData.hpp:592
std::optional< RegionGroup > get_region_group(const std::unordered_map< std::string, RegionGroup > &groups, const std::string &name)
Get a RegionGroup by name from a group map.
void add_region_group(std::unordered_map< std::string, RegionGroup > &groups, const RegionGroup &group)
Add a RegionGroup to a group map.
MemoryLayout
Memory layout for multi-dimensional data.
Definition NDData.hpp:65
double position_to_time(uint64_t position, double sample_rate)
Convert position (samples/frames) to time (seconds) given a sample rate.
void remove_region_group(std::unordered_map< std::string, RegionGroup > &groups, const std::string &name)
Remove a RegionGroup by name from a group map.
uint64_t time_to_position(double time, double sample_rate)
Convert time (seconds) to position (samples/frames) given a sample rate.
Container structure for consistent dimension ordering.
Organizes related signal regions into a categorized collection.
Represents a point or span in N-dimensional space.
Definition Region.hpp:73
Backend IO streaming service interface.
Definition IOService.hpp:18