MXL : Media eXchange Layer
MXL
Loading...
Searching...
No Matches
FlowParser.cpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2025 Contributors to the Media eXchange Layer project.
2// SPDX-License-Identifier: Apache-2.0
3
5#include <concepts>
6#include <cstddef>
7#include <cstdint>
8#include <ranges>
9#include <stdexcept>
10#include <string>
11#include <string_view>
12#include <utility>
13#include <uuid.h>
14#include <fmt/format.h>
15#include <picojson/picojson.h>
16#include <mxl/dataformat.h>
17#include <mxl/mxl.h>
22
23namespace mxl::lib
24{
25
26 namespace
27 {
28
29 // this are arbitrary limits, but we need to put a cap somewhere to prevent a bad json document
30 // from allocating all the RAM on the system.
31 constexpr auto MAX_WIDTH = std::uint32_t{7680};
32 constexpr auto MAX_HEIGHT = std::uint32_t{4320};
33
42 constexpr mxlDataFormat translateFlowFormat(std::string_view format) noexcept
43 {
44 using namespace std::literals;
45
46 constexpr auto const FORMAT_PREFIX = "urn:x-nmos:format:"sv;
47 if (format.starts_with(FORMAT_PREFIX))
48 {
49 auto const tail = format.substr(FORMAT_PREFIX.length());
50 if (tail == "video"sv)
51 {
53 }
54 if (tail == "audio"sv)
55 {
57 }
58 if ((tail == "event"sv) || (tail == "data.event"sv))
59 {
61 }
62 if (tail == "data"sv)
63 {
65 }
66 }
67
69 }
70
78 picojson::object::const_iterator testField(picojson::object const& in_obj, std::string const& in_field)
79 {
80 auto const it = in_obj.find(in_field);
81 if (it == in_obj.end())
82 {
83 auto msg = std::string{"Required '"} + in_field + "' not found.";
84 throw std::invalid_argument{std::move(msg)};
85 }
86 return it;
87 }
88
98 template<typename T>
99 T fetchAs(picojson::object const& in_object, std::string const& in_field)
100 {
101 auto const it = testField(in_object, in_field);
102 return it->second.get<T>();
103 }
104
113 template<std::integral T>
114 T fetchInteger(picojson::object const& in_object, std::string const& in_field)
115 {
116 return jsonToInteger<T>(testField(in_object, in_field)->second, in_field);
117 }
118
119 mxlRational extractRational(picojson::object const& in_object)
120 {
121 auto result = mxlRational{0, 1};
122
123 result.numerator = fetchInteger<std::int64_t>(in_object, "numerator");
124 if (auto const it = in_object.find("denominator"); it != in_object.end())
125 {
126 result.denominator = jsonToInteger<std::int64_t>(it->second, "denominator");
127 }
128
129 // Normalize the rational. We should realistically only see x/1 or x/1001 here.
130 auto g = std::gcd(result.numerator, result.denominator);
131 if (g != 0)
132 {
133 result.numerator /= g;
134 result.denominator /= g;
135 }
136
137 return result;
138 }
139
146 bool validateGroupHintValue(picojson::value const& value)
147 {
148 if (!value.is<std::string>())
149 {
150 MXL_ERROR("Invalid group hint value. Not a string.");
151 return false;
152 }
153
154 auto const& hint = value.get<std::string>();
155 auto parts = std::vector<std::string_view>{};
156 for (auto part : hint | std::views::split(':'))
157 {
158 parts.emplace_back(std::ranges::data(part), std::ranges::size(part));
159 }
160 if ((parts.size() < 2) || (parts.size() > 3))
161 {
162 MXL_ERROR("Invalid group hint value '{}'. Expected format '<group-name>:<role-in-group>[:<group-scope>]'", hint);
163 return false;
164 }
165 if (parts[0].empty() || parts[1].empty())
166 {
167 MXL_ERROR("Invalid group hint value '{}'. Group name and role must not be empty.", hint);
168 return false;
169 }
170 if ((parts.size() == 3) && (parts[2] != "device") && (parts[2] != "node"))
171 {
172 MXL_ERROR("Invalid group hint value '{}'. Group scope must be either 'device' or 'node'.", hint);
173 return false;
174 }
175 return true;
176 }
177
183 bool validateGroupHint(picojson::object const& in_object)
184 {
185 try
186 {
187 auto const tags = fetchAs<picojson::object>(in_object, "tags");
188 auto const groupHints = fetchAs<picojson::array>(tags, "urn:x-nmos:tag:grouphint/v1.0");
189 if (groupHints.empty())
190 {
191 MXL_ERROR("Group hint tag found but empty.");
192 return false;
193 }
194 for (auto const& value : groupHints)
195 {
196 if (!validateGroupHintValue(value))
197 {
198 return false;
199 }
200 }
201 return true;
202 }
203 catch (std::exception const& e)
204 {
205 MXL_ERROR("Invalid group hint tag. {}", e.what());
206 return false;
207 }
208 }
209
210 } // namespace
211
212 FlowParser::FlowParser(std::string const& in_flowDef)
213 : _id{}
215 , _interlaced{false}
216 , _grainRate{0, 1}
217 , _root{}
218 {
219 //
220 // Parse the json flow
221 //
222 auto jsonValue = picojson::value{};
223 auto const err = parseJson(jsonValue, in_flowDef);
224 if (!err.empty())
225 {
226 throw std::invalid_argument{"Invalid JSON flow definition. " + err};
227 }
228
229 // Confirm that the root is a json object
230 if (!jsonValue.is<picojson::object>())
231 {
232 throw std::invalid_argument{"Expected a JSON Object"};
233 }
234 _root = jsonValue.get<picojson::object>();
235
236 auto id = uuids::uuid::from_string(fetchAs<std::string>(_root, "id"));
237 if (!id.has_value())
238 {
239 throw std::invalid_argument{"Invalid flow 'id'."};
240 }
241
242 _id = *id;
243
244 // Read the media format
245 _format = translateFlowFormat(fetchAs<std::string>(_root, "format"));
246
247 // Read the grain rate if this is not an audio flow.
249 {
250 _grainRate = extractRational(fetchAs<picojson::object>(_root, "grain_rate"));
251 }
252 else if (_format == MXL_DATA_FORMAT_AUDIO)
253 {
254 _grainRate = extractRational(fetchAs<picojson::object>(_root, "sample_rate"));
255 }
256 else
257 {
258 throw std::domain_error{"Unsupported flow format."};
259 }
260
261 // A rate of zero or below gives a ring buffer with no entries.
262 if ((_grainRate.numerator <= 0) || (_grainRate.denominator <= 0))
263 {
264 throw std::invalid_argument{(_format == MXL_DATA_FORMAT_AUDIO) ? "sample_rate must be positive." : "grain_rate must be positive."};
265 }
266
267 // Validate that we have a non empty label
268 auto const label = fetchAs<std::string>(_root, "label");
269 if (label.empty())
270 {
271 throw std::domain_error{"Empty flow label."};
272 }
273
274 // Validate that we have a valid group hint tag
275 if (!validateGroupHint(_root))
276 {
277 throw std::domain_error{"Invalid or missing group hint tag."};
278 }
279
280 // Validate that grain_rate if we are interlaced video
281 // Grain rate must be either 30000/1001 or 25/1
283 {
284 auto const width = fetchInteger<std::size_t>(_root, "frame_width");
285 auto const height = fetchInteger<std::size_t>(_root, "frame_height");
286
287 if ((width < 2) || (width > MAX_WIDTH) || (height < 1) || (height > MAX_HEIGHT))
288 {
289 auto msg = fmt::format("Invalid video dimensions: {}x{}. range is 2x1 to {}x{}", width, height, MAX_WIDTH, MAX_HEIGHT);
290 throw std::invalid_argument{std::move(msg)};
291 }
292
293 auto interlaceMode = std::string{};
294 if (auto const it = _root.find("interlace_mode"); it != _root.end())
295 {
296 interlaceMode = it->second.get<std::string>();
297 }
298 else
299 {
300 // the interlace_mode field is absent. This means that the flow is progressive. No need to validate the grain rate.
301 // We will use the grain rate as is.
302 interlaceMode = "progressive";
303 }
304
305 constexpr auto validValues = std::array{"progressive", "interlaced_tff", "interlaced_bff"};
306 auto const match = std::ranges::any_of(validValues, [&](auto v) noexcept { return interlaceMode == v; });
307 if (!match)
308 {
309 auto msg = fmt::format("Invalid interlace_mode: {}", interlaceMode);
310 throw std::invalid_argument{std::move(msg)};
311 }
312
313 if ((interlaceMode == "interlaced_tff") || (interlaceMode == "interlaced_bff"))
314 {
315 // This is an interlaced video flow. confirm that the grain rate is defined to 30000/1001 or 25/1
316 if ((_grainRate != mxlRational{30000, 1001}) && (_grainRate != mxlRational{25, 1}))
317 {
318 auto msg = std::string{"Invalid grain_rate for interlaced video. Expected 30000/1001 or 25/1."};
319 throw std::invalid_argument{std::move(msg)};
320 }
321
322 // The grain rate is valid and we are in interlaced mode. Double the grain rate to express a field rate.
323 _grainRate.numerator *= 2;
324 _interlaced = true;
325 }
326 }
327 }
328
329 uuids::uuid const& FlowParser::getId() const
330 {
331 return _id;
332 }
333
335 {
336 return _grainRate;
337 }
338
340 {
341 return _format;
342 }
343
344 std::size_t FlowParser::getPayloadSize() const
345 {
346 auto payloadSize = std::size_t{0};
347
349 {
350 auto const width = fetchInteger<std::size_t>(_root, "frame_width");
351 auto const height = fetchInteger<std::size_t>(_root, "frame_height");
352 auto const mediaType = fetchAs<std::string>(_root, "media_type");
353
354 if (mediaType == "video/v210")
355 {
356 if (!_interlaced || ((height % 2) == 0))
357 {
358 // Interlaced media is handled as separate fields.
359 auto const h = _interlaced ? height / 2 : height;
360 payloadSize = getV210LineLength(width) * h;
361 }
362 else
363 {
364 auto msg = std::string{"Invalid video height for interlaced v210. Must be even."};
365 throw std::invalid_argument{std::move(msg)};
366 }
367 }
368 else if (mediaType == "video/v210a")
369 {
370 if (!_interlaced || ((height % 2) == 0))
371 {
372 // Interlaced media is handled as separate fields.
373 auto const h = _interlaced ? height / 2 : height;
374
375 // Fill size
376 auto fillPayloadSize = getV210LineLength(width) * h;
377
378 // Key is stored as 10 bits per pixel, 3x10 bit words in a 32 bit word, little-endian.
379 // the last 2 bits of the 32 bit group of 3 pixels are unused.
381
382 // Total payload size is the sum of the fill and key sizes
383 payloadSize = fillPayloadSize + keyPayloadSize;
384 }
385 else
386 {
387 auto msg = std::string{"Invalid video height for interlaced v210a. Must be even."};
388 throw std::invalid_argument{std::move(msg)};
389 }
390 }
391 else
392 {
393 auto msg = std::string{"Unsupported video media_type: "} + mediaType;
394 throw std::invalid_argument{std::move(msg)};
395 }
396 }
397 else if (_format == MXL_DATA_FORMAT_DATA)
398 {
399 auto const mediaType = fetchAs<std::string>(_root, "media_type");
400 if (mediaType == "video/smpte291")
401 {
402 payloadSize = MXL_DATA_FORMAT_GRAIN_SIZE;
403 }
404 else
405 {
406 auto msg = std::string{"Unsupported data media_type: "} + mediaType;
407 throw std::invalid_argument{std::move(msg)};
408 }
409 }
410 else if (_format == MXL_DATA_FORMAT_EVENT)
411 {
412 payloadSize = MXL_DATA_FORMAT_GRAIN_SIZE;
413 }
414 else if (_format == MXL_DATA_FORMAT_AUDIO)
415 {
416 // TODO: Also check the media type once we agreed on how to encode
417 // single precision IEEE floats.
418 auto const bitDepth = fetchAs<double>(_root, "bit_depth");
419 if ((bitDepth != 32.0) && (bitDepth != 64.0))
420 {
421 auto msg = fmt::format("Unsupported bit depth: {}", bitDepth);
422 throw std::invalid_argument{std::move(msg)};
423 }
424
425 payloadSize = static_cast<std::size_t>(bitDepth) / 8U;
426 }
427 else
428 {
430 throw std::invalid_argument{"Format not implemented."};
431 }
432
433 return payloadSize;
434 }
435
436 std::array<std::uint32_t, MXL_MAX_PLANES_PER_GRAIN> FlowParser::getPayloadSliceLengths() const
437 {
438 auto sliceLengths = std::array<std::uint32_t, MXL_MAX_PLANES_PER_GRAIN>{0, 0, 0, 0};
439
440 switch (_format)
441 {
443 {
444 // For "data" flows, the slice length is 1 byte
445 sliceLengths[0] = 1;
446 return sliceLengths;
447 }
448
450 {
451 // For video flows the slice length is the byte-length of a single
452 // line of v210 video.
453 auto const width = fetchInteger<std::size_t>(_root, "frame_width");
454 auto const mediaType = fetchAs<std::string>(_root, "media_type");
455 auto const v210fillSize = getV210LineLength(width);
456
457 if (mediaType == "video/v210")
458 {
459 sliceLengths[0] = v210fillSize;
460 }
461 else if (mediaType == "video/v210a")
462 {
463 sliceLengths[0] = v210fillSize;
464 sliceLengths[1] = get10BitAlphaLineLength(width);
465 }
466 else
467 {
468 auto msg = std::string{"Unsupported video media_type: "} + mediaType;
469 throw std::invalid_argument{std::move(msg)};
470 }
471
472 return sliceLengths;
473 }
474
475 default:
476 {
477 throw std::invalid_argument{"Cannot compute slice length for this data format."};
478 }
479 }
480 }
481
483 {
484 switch (_format)
485 {
487 {
488 // Since the slice length for data flows is 1 byte, the number of slices must be the
489 // grain size.
491 }
492
494 {
495 if (auto const mediaType = fetchAs<std::string>(_root, "media_type"); mediaType != "video/v210" && mediaType != "video/v210a")
496 {
497 auto msg = std::string{"Unsupported video media_type: "} + mediaType;
498 throw std::invalid_argument{std::move(msg)};
499 }
500
501 // For v210, the number of slices is always the number of video lines
502 auto h = fetchInteger<std::size_t>(_root, "frame_height");
503 if (_interlaced)
504 {
505 return h / 2;
506 }
507
508 return h;
509 }
510 default:
511 {
512 throw std::invalid_argument{"Cannot compute slice length for this data format."};
513 }
514 }
515 }
516
517 std::size_t FlowParser::getChannelCount() const
518 {
519 if (auto const it = _root.find("channel_count"); it != _root.end())
520 {
521 if (auto const value = jsonToInteger<std::size_t>(it->second, "channel_count"); value > 0U)
522 {
523 return value;
524 }
525 throw std::invalid_argument{"Unsupported channel count: 0"};
526 }
527 return 1U;
528 }
529} // namespace mxl::lib
#define MXL_ERROR(...)
Definition Logging.hpp:67
std::array< std::uint32_t, MXL_MAX_PLANES_PER_GRAIN > getPayloadSliceLengths() const
mxlDataFormat getFormat() const
FlowParser(std::string const &in_flowDef)
std::size_t getTotalPayloadSlices() const
picojson::object _root
mxlRational getGrainRate() const
std::size_t getChannelCount() const
mxlDataFormat _format
std::size_t getPayloadSize() const
uuids::uuid const & getId() const
Public flow format identifiers and format classification helpers.
int mxlIsEventDataFormat(int format)
Test whether a format uses the event queue API.
Definition dataformat.h:91
int mxlIsDiscreteDataFormat(int format)
Definition dataformat.h:75
mxlDataFormat
Definition dataformat.h:25
@ MXL_DATA_FORMAT_EVENT
Asynchronous queue of complete events or event fragments.
Definition dataformat.h:30
@ MXL_DATA_FORMAT_AUDIO
Definition dataformat.h:28
@ MXL_DATA_FORMAT_UNSPECIFIED
Definition dataformat.h:26
@ MXL_DATA_FORMAT_DATA
Definition dataformat.h:29
@ MXL_DATA_FORMAT_VIDEO
Definition dataformat.h:27
#define MXL_DATA_FORMAT_GRAIN_SIZE
Definition dataformat.h:15
std::uint32_t get10BitAlphaLineLength(std::size_t width)
T jsonToInteger(picojson::value const &value, std::string_view name)
std::string parseJson(picojson::value &out, std::string_view text, JsonLimits const &limits={})
std::uint32_t getV210LineLength(std::size_t width)
Definition MediaUtils.cpp:8
struct mxlRational_t mxlRational
int64_t numerator
Definition rational.h:21
constexpr auto h
auto keyPayloadSize
auto fillPayloadSize