QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
RecordingBranch.cc
Go to the documentation of this file.
1#include "RecordingBranch.h"
2
3#include <cerrno>
4#include <cstring>
5#include <gst/gst.h>
6#include <utility>
7
8#include <QtCore/QCoreApplication>
9#include <QtCore/QFile>
10
11#include "GStreamerHelpers.h"
12#include "GstVideoReceiver.h"
13#include "PipelineDotDumper.h"
14#include "RecordingPlan.h"
15
16namespace {
17
18// MP4/MOV robust muxing: qtmux reserves header space at the start of the file and rewrites the moov
19// there every update period, so a crash or power loss leaves a file playable up to the last update.
20// The reservation (550 B/s per track by default, ~8 MB here) outlasts the nominal duration since the
21// index grows ~140 B/s at 30 fps and ~260 B/s at 60 fps; overrunning it makes qtmux post an ERROR.
22// No file is meant to get that far: its recording continues in a new part after half the nominal duration. The
23// index grows faster at higher frame rates, and when no two frames last the same, as without a jitter buffer, so
24// the muxer's own estimate of the room left is watched too (RecordingBranch::kHeaderSpaceMargin).
25// The period bounds crash data loss without rewriting the growing moov too often.
26constexpr guint64 kRecordingReservedMaxDurationNs = 2 * 3600 * GST_SECOND;
27constexpr guint64 kRecordingMoovUpdatePeriodNs = 5 * GST_SECOND;
28constexpr std::chrono::seconds kRecordingWatchInterval{1};
29// matroskamux never has its file synced, as qtmux has with each header update. Storage that takes writes into a cache
30// (an Android SD card, a network share) reports a full disk only to a sync: a recording there would lose everything
31// without an error. A sync as often as the MP4's also bounds what a power loss takes.
32constexpr gint64 kRecordingSyncPeriodUs = static_cast<gint64>(kRecordingMoovUpdatePeriodNs / GST_USECOND);
33static_assert(std::chrono::nanoseconds(RecordingBranch::kHeaderEstimateDelay).count() >=
34 static_cast<qint64>(2 * kRecordingMoovUpdatePeriodNs),
35 "The muxer's estimate of its header space counts from its second header update");
36static_assert((2 * std::chrono::nanoseconds(RecordingPlan::kMaxPartDuration).count()) <=
37 static_cast<qint64>(kRecordingReservedMaxDurationNs),
38 "A recording's part must end well within the header space its muxer reserves");
39
40const char* muxerFactory(VideoReceiver::FileFormat format)
41{
42 switch (format) {
44 return "matroskamux";
46 return "qtmux";
48 return "mp4mux";
49 }
50 return nullptr;
51}
52
53const char* recordingParserFactory(const GstCaps* caps)
54{
55 if (!caps || gst_caps_is_any(caps) || gst_caps_is_empty(caps)) {
56 return nullptr;
57 }
58
59 for (guint i = 0; i < gst_caps_get_size(caps); ++i) {
60 const GstStructure* structure = gst_caps_get_structure(caps, i);
61 if (gst_structure_has_name(structure, "video/x-h264")) {
62 return "h264parse";
63 }
64 if (gst_structure_has_name(structure, "video/x-h265")) {
65 return "h265parse";
66 }
67 }
68
69 return nullptr;
70}
71
75GstPadProbeReturn timestampForMuxer([[maybe_unused]] GstPad* pad, GstPadProbeInfo* info, [[maybe_unused]] gpointer data)
76{
77 GstBuffer* buffer = GST_PAD_PROBE_INFO_BUFFER(info);
78 if (!buffer || GST_BUFFER_PTS_IS_VALID(buffer)) {
79 return GST_PAD_PROBE_OK;
80 }
81 if (!GST_BUFFER_DTS_IS_VALID(buffer)) {
82 return GST_PAD_PROBE_DROP;
83 }
84 buffer = gst_buffer_make_writable(buffer);
85 GST_BUFFER_PTS(buffer) = GST_BUFFER_DTS(buffer);
86 GST_PAD_PROBE_INFO_DATA(info) = buffer;
87 return GST_PAD_PROBE_OK;
88}
89
92GstPadProbeReturn syncPeriodically([[maybe_unused]] GstPad* pad, GstPadProbeInfo* info, gpointer data)
93{
94 auto* const markedAt = static_cast<gint64*>(data);
95 const gint64 now = g_get_monotonic_time();
96 GstBuffer* buffer = GST_PAD_PROBE_INFO_BUFFER(info);
97 if (!buffer || ((*markedAt != 0) && ((now - *markedAt) < kRecordingSyncPeriodUs))) {
98 return GST_PAD_PROBE_OK;
99 }
100 *markedAt = now;
101 buffer = gst_buffer_make_writable(buffer);
102 GST_BUFFER_FLAG_SET(buffer, GST_BUFFER_FLAG_SYNC_AFTER);
103 GST_PAD_PROBE_INFO_DATA(info) = buffer;
104 return GST_PAD_PROBE_OK;
105}
106
112GstPadProbeReturn syncAtEnd(GstPad* pad, GstPadProbeInfo* info, [[maybe_unused]] gpointer data)
113{
114 const GstEvent* const event = gst_pad_probe_info_get_event(info);
115 if (!event || (GST_EVENT_TYPE(event) != GST_EVENT_EOS)) {
116 return GST_PAD_PROBE_OK;
117 }
118 GstBuffer* const buffer = gst_buffer_new();
119 gst_buffer_append_memory(buffer, gst_allocator_alloc(nullptr, 0, nullptr));
120 GST_BUFFER_FLAG_SET(buffer, GST_BUFFER_FLAG_SYNC_AFTER);
121 // From the thread that brings the EOS, which holds the pad's stream lock for it: the lock is recursive.
122 (void) gst_pad_chain(pad, buffer);
123 return GST_PAD_PROBE_OK;
124}
125
127struct RecordingWatch
128{
129 RecordingBranch* branch = nullptr;
130 quint64 recording = 0;
131};
132
134GstPadProbeReturn holdCapsEvent([[maybe_unused]] GstPad* pad, GstPadProbeInfo* info, gpointer data)
135{
136 GstEvent* const event = gst_pad_probe_info_get_event(info);
137 GstCaps* caps = nullptr;
138 if (event && (GST_EVENT_TYPE(event) == GST_EVENT_CAPS)) {
139 gst_event_parse_caps(event, &caps);
140 }
141 return (caps && gst_caps_is_equal(caps, static_cast<const GstCaps*>(data))) ? GST_PAD_PROBE_OK : GST_PAD_PROBE_PASS;
142}
143
145struct SwitchWatch
146{
147 RecordingBranch* branch = nullptr;
148 quint64 hold = 0;
149};
150
153bool reportsFullStorage(const GError* error, const char* debug)
154{
155 if (!error) {
156 return false;
157 }
158 if (g_error_matches(error, GST_RESOURCE_ERROR, GST_RESOURCE_ERROR_NO_SPACE_LEFT)) {
159 return true;
160 }
161 return g_error_matches(error, GST_RESOURCE_ERROR, GST_RESOURCE_ERROR_WRITE) && debug &&
162 (std::strstr(debug, g_strerror(ENOSPC)) != nullptr);
163}
164
165QString notFinalizedError()
166{
167 return QCoreApplication::translate("RecordingBranch",
168 "The recording was not finalized in time and may be incomplete.");
169}
170
171void warnNotFinalized()
172{
173 qCWarning(GstVideoReceiverLog) << "Recording not finalized within"
174 << std::chrono::milliseconds(RecordingBranch::kFinalizeTimeout).count()
175 << "ms; closing it (MP4/MOV stay playable up to the last moov update)";
176}
177
178} // namespace
179
181 const GstCaps* inputCaps)
182{
183 const char* const muxerName = muxerFactory(format);
184 if (!muxerName) {
185 qCCritical(GstVideoReceiverLog) << "Unsupported file format" << static_cast<int>(format);
186 return nullptr;
187 }
188
189 GStreamer::GstElementPtr bin = GStreamer::adoptFloating(gst_bin_new("sinkbin"));
190 if (!bin) {
191 qCWarning(GstVideoReceiverLog) << "gst_bin_new('sinkbin') failed";
192 return nullptr;
193 }
194
195 GstElement* parser = nullptr;
196 if (const char* parserFactory = recordingParserFactory(inputCaps)) {
197 GStreamer::GstElementPtr parserOwner = GStreamer::makeElement(parserFactory, "parser");
198 if (!parserOwner) {
199 qCWarning(GstVideoReceiverLog) << "gst_element_factory_make() failed for" << parserFactory;
200 return nullptr;
201 }
202 g_object_set(parserOwner.get(), "config-interval", -1, nullptr);
203 parser = GStreamer::addToBin(bin.get(), std::move(parserOwner), "parser");
204 if (!parser) {
205 return nullptr;
206 }
207 }
208
209 GStreamer::GstElementPtr muxerOwner = GStreamer::makeElement(muxerName, "muxer");
210 GStreamer::GstElementPtr fileSinkOwner = GStreamer::makeElement("filesink", "filesink");
211 if (!muxerOwner || !fileSinkOwner) {
212 qCWarning(GstVideoReceiverLog) << "gst_element_factory_make() failed for" << muxerName << "or filesink";
213 return nullptr;
214 }
215
216 // Tagged with the time it starts and the application, as a USB camera's recordings are (UVCCameraController).
217 if (GST_IS_TAG_SETTER(muxerOwner.get())) {
218 GstDateTime* const started = gst_date_time_new_from_g_date_time(g_date_time_new_now_utc());
219 gst_tag_setter_add_tags(GST_TAG_SETTER(muxerOwner.get()), GST_TAG_MERGE_REPLACE, GST_TAG_DATE_TIME, started,
220 GST_TAG_COMMENT, VideoReceiver::recordingComment().toUtf8().constData(), nullptr);
221 gst_date_time_unref(started);
222 }
223 // faststart stays off: it would spool the recording to a temp file and write the real file only at EOS.
224 if ((format == VideoReceiver::FileFormat::Mp4) || (format == VideoReceiver::FileFormat::Mov)) {
225 g_object_set(muxerOwner.get(), "reserved-max-duration", kRecordingReservedMaxDurationNs,
226 "reserved-moov-update-period", kRecordingMoovUpdatePeriodNs, nullptr);
227 }
228 // Not async: a sink that waits to preroll would take the live pipeline out of PLAYING until the first keyframe.
229 g_object_set(fileSinkOwner.get(), "location", GStreamer::glibFileName(file).constData(), "async", FALSE, nullptr);
230
231 GstElement* const muxer = GStreamer::addToBin(bin.get(), std::move(muxerOwner), "muxer");
232 GstElement* const fileSink = GStreamer::addToBin(bin.get(), std::move(fileSinkOwner), "filesink");
233 if (!muxer || !fileSink || !gst_element_link(muxer, fileSink)) {
234 qCWarning(GstVideoReceiverLog) << "Failed to link the muxer and filesink";
235 return nullptr;
236 }
237 if (format == VideoReceiver::FileFormat::Mkv) {
238 const GStreamer::GstPadPtr fileSinkPad = GStreamer::adoptPad(gst_element_get_static_pad(fileSink, "sink"));
239 (void) gst_pad_add_probe(fileSinkPad.get(), GST_PAD_PROBE_TYPE_BUFFER, syncPeriodically, g_new0(gint64, 1),
240 g_free);
241 (void) gst_pad_add_probe(fileSinkPad.get(), GST_PAD_PROBE_TYPE_EVENT_DOWNSTREAM, syncAtEnd, nullptr, nullptr);
242 }
243
244 // No release_request_pad on failure: disposing the bin reclaims the pad.
245 const GStreamer::GstPadPtr muxerPad = GStreamer::adoptPad(gst_element_request_pad_simple(muxer, "video_%u"));
246 if (!muxerPad) {
247 qCWarning(GstVideoReceiverLog) << "gst_element_request_pad_simple(" << muxerName << ", video_%u) failed";
248 return nullptr;
249 }
250 (void) gst_pad_add_probe(muxerPad.get(), GST_PAD_PROBE_TYPE_BUFFER, timestampForMuxer, nullptr, nullptr);
251
252 GStreamer::GstPadPtr parserSinkPad;
253 if (parser) {
254 const GStreamer::GstPadPtr parserSrcPad = GStreamer::adoptPad(gst_element_get_static_pad(parser, "src"));
255 parserSinkPad = GStreamer::adoptPad(gst_element_get_static_pad(parser, "sink"));
256 if (!parserSrcPad || !parserSinkPad) {
257 qCCritical(GstVideoReceiverLog) << "gst_element_get_static_pad(parser) failed";
258 return nullptr;
259 }
260
261 const GstPadLinkReturn linkResult = gst_pad_link(parserSrcPad.get(), muxerPad.get());
262 if (linkResult != GST_PAD_LINK_OK) {
263 qCWarning(GstVideoReceiverLog) << "Failed to link parser and muxer:" << gst_pad_link_get_name(linkResult);
264 return nullptr;
265 }
266 }
267
268 // Each element, not just the bin: a message can outlive the bin that held its source.
269 for (GstElement* const element : {bin.get(), parser, muxer, fileSink}) {
270 if (element) {
272 }
273 }
274
275 GstPad* const ghostpad = gst_ghost_pad_new("sink", parserSinkPad ? parserSinkPad.get() : muxerPad.get());
276 if (!ghostpad || !gst_element_add_pad(bin.get(), ghostpad)) {
277 qCWarning(GstVideoReceiverLog) << "Failed to add the recording sink's ghost pad";
278 return nullptr;
279 }
280
281 return bin;
282}
283
285 : _context(context)
286 , _listener(listener)
287{
288 _finalizeTimer.setSingleShot(true);
289 _finalizeTimer.setInterval(kFinalizeTimeout);
290 (void) QObject::connect(&_finalizeTimer, &QTimer::timeout, &_finalizeTimer, [this]() {
291 if (_state == State::Finalizing) {
292 warnNotFinalized();
293 _finish(notFinalizedError());
294 }
295 });
296 _watchTimer.setInterval(kRecordingWatchInterval);
297 (void) QObject::connect(&_watchTimer, &QTimer::timeout, &_watchTimer, [this]() {
298 _checkStarted();
299 _checkHeaderSpace();
300 });
301}
302
307
309{
310 if (!_head.build(_context.pipeline, _context.tee, GStreamer::PipelineBranch::Recording, "recording")) {
311 return false;
312 }
313
314 // Every frame must reach the muxer, so no time or buffer limit; storage that falls this far behind ends the
315 // recording (_onQueueOverrun) instead of holding up the tee.
316 g_object_set(_head.queue(), "max-size-time", G_GUINT64_CONSTANT(0), "max-size-buffers", 0, "max-size-bytes",
317 static_cast<guint>(kQueueMaxBytes), nullptr);
318 _head.onOverrun(G_CALLBACK(_onQueueOverrun), this);
319
320 // Preserve stream-start/caps/segment events while buffers are dropped. When recording
321 // starts later, the newly linked parser receives the negotiated codec configuration.
322 // drop-mode exists since GStreamer 1.20, the oldest version QGC supports.
323 gst_util_set_object_arg(G_OBJECT(_head.valve()), "drop-mode", "forward-sticky-events");
324 return true;
325}
326
328{
329 _finalizeTimer.stop();
330 _watchTimer.stop();
331 _keyframeWatch.remove();
332 _startWatch.remove();
333 _capsWatch.remove();
334 _releaseSwitchHold();
335 if (_fileSink) {
336 GStreamer::flushAndDisposeChild(_fileSink.get());
337 _fileSink.reset();
338 }
339 _state = State::Idle;
340 _head.reset();
341}
342
343void RecordingBranch::setRequest(const std::optional<Request>& request)
344{
345 _requested = request;
346 _reconcile();
347}
348
350{
351 _streaming = true;
352 _reconcile();
353}
354
355void RecordingBranch::_reconcile()
356{
357 switch (_state) {
358 case State::Idle:
359 if (_requested && _streaming) {
360 _start(*_requested);
361 }
362 break;
363 case State::Recording:
364 if (_requested && (*_requested == _current)) {
365 _releaseSwitchHold();
366 } else if (_requested && _fileStarted.load(std::memory_order_acquire)) {
367 // A file with frames ends where the next one can begin, so the frames in between aren't lost: at the
368 // change of caps the stream is held at, or else at its next keyframe.
369 if (_capsHold.load(std::memory_order_acquire) != 0) {
370 _end();
371 } else {
372 _switchAtKeyframe();
373 }
374 } else {
375 _end();
376 }
377 break;
378 case State::Finalizing:
379 break;
380 }
381}
382
383void RecordingBranch::_start(const Request& request)
384{
385 _current = request;
386 (void) _recording.fetch_add(1, std::memory_order_relaxed);
387 _failure.clear();
388 _fileStarted.store(false, std::memory_order_relaxed);
389 _fedAt.store(0, std::memory_order_relaxed);
390 _openedReported = false;
391 _state = State::Recording;
392
393 qCDebug(GstVideoReceiverLog) << "Starting recording" << request.file << _context.redactedUri;
394
395 // forward-sticky-events keeps the negotiated caps on the closed valve; the query covers the moment before.
396 const GStreamer::GstPadPtr valveSrc = GStreamer::adoptPad(gst_element_get_static_pad(_head.valve(), "src"));
397 GStreamer::GstCapsPtr inputCaps = GStreamer::adoptCaps(gst_pad_get_current_caps(valveSrc.get()));
398 if (!inputCaps) {
399 inputCaps = GStreamer::adoptCaps(gst_pad_query_caps(valveSrc.get(), nullptr));
400 }
401
402 _fileSink = makeFileSink(request.file, request.format, inputCaps.get());
403 if (!_fileSink) {
404 _failure = QCoreApplication::translate("RecordingBranch", "Unable to create the recording sink.");
405 _finish(QString());
406 return;
407 }
408 TeeBranchHead::absorbFlowErrors(_fileSink.get());
409
410 gst_util_set_object_arg(G_OBJECT(_head.queue()), "leaky", "no");
411 if (!gst_bin_add(GST_BIN(_context.pipeline), _fileSink.get()) ||
412 !gst_element_link(_head.valve(), _fileSink.get())) {
413 qCWarning(GstVideoReceiverLog) << "Failed to add the recording sink" << _context.redactedUri;
414 _failure = QCoreApplication::translate("RecordingBranch", "Unable to add the recording sink.");
415 _finish(QString());
416 return;
417 }
418
419 if (!gst_element_sync_state_with_parent(_fileSink.get())) {
420 // The sink posted why (usually a file that can't be opened); that ERROR ends the recording.
421 GStreamer::flushAndDisposeChild(_fileSink.get());
422 _failure = QCoreApplication::translate("RecordingBranch", "Unable to start recording to %1.").arg(request.file);
423 _state = State::Finalizing;
424 _finalizeTimer.start();
425 return;
426 }
427
428 // The file starts with a keyframe at t=0, so playback can decode from its first frame. The stream's first keyframe
429 // lets it into the recorder, whose parser passes on nothing before a keyframe that comes with its parameter sets:
430 // the first frame the file can hold.
431 const GStreamer::GstElementPtr parser =
432 GStreamer::adoptElement(gst_bin_get_by_name(GST_BIN(_fileSink.get()), "parser"));
433 const GStreamer::GstPadPtr parserSrc =
434 GStreamer::adoptPad(parser ? gst_element_get_static_pad(parser.get(), "src") : nullptr);
435 const GStreamer::GstPadPtr valveSink = GStreamer::adoptPad(gst_element_get_static_pad(_head.valve(), "sink"));
436 const auto newWatch = [this]() {
437 return new RecordingWatch{.branch = this, .recording = _recording.load(std::memory_order_relaxed)};
438 };
439 const GDestroyNotify deleteWatch = [](gpointer watch) { delete static_cast<RecordingWatch*>(watch); };
440 if (!_keyframeWatch.add(valveSrc.get(), GST_PAD_PROBE_TYPE_BUFFER, _keyframeProbe, this) ||
441 !_startWatch.add(parserSrc ? parserSrc.get() : valveSrc.get(), GST_PAD_PROBE_TYPE_BUFFER, _startProbe,
442 newWatch(), deleteWatch) ||
443 !_capsWatch.add(valveSink.get(), GST_PAD_PROBE_TYPE_EVENT_DOWNSTREAM, _capsProbe, newWatch(), deleteWatch)) {
444 qCCritical(GstVideoReceiverLog) << "Failed to add the recording's probes" << _context.redactedUri;
445 _failure = QCoreApplication::translate("RecordingBranch", "Unable to start recording.");
446 _finish(QString());
447 return;
448 }
449
450 if (_switching || (_capsHold.load(std::memory_order_acquire) != 0)) {
451 // The switch asked for the keyframe this file starts with, and holds it or still waits for it; the one that
452 // comes with new caps follows them.
453 g_object_set(_head.valve(), "drop", FALSE, nullptr);
454 } else {
455 _head.open();
456 }
457 _watchTimer.start();
458 _context.dotDumper->dump(_context.pipeline, "pipeline-with-filesink");
459}
460
461void RecordingBranch::_switchAtKeyframe()
462{
463 if (_switching) {
464 return;
465 }
466 const GStreamer::GstPadPtr valveSrc = GStreamer::adoptPad(gst_element_get_static_pad(_head.valve(), "src"));
467 if (!_switchHold.add(valveSrc.get(),
468 static_cast<GstPadProbeType>(GST_PAD_PROBE_TYPE_BLOCK | GST_PAD_PROBE_TYPE_BUFFER),
469 _switchProbe, new SwitchWatch{.branch = this, .hold = ++_switchHoldId},
470 [](gpointer watch) { delete static_cast<SwitchWatch*>(watch); })) {
471 qCWarning(GstVideoReceiverLog) << "Unable to hold the next keyframe; frames up to it are not recorded";
472 _end();
473 return;
474 }
475 _switching = true;
476 // Not left to the stream: with a long GOP, or a camera that sends keyframes on request only, the current file
477 // would go on growing meanwhile.
478 _head.requestKeyframe();
479}
480
481void RecordingBranch::_onSwitchKeyframe(quint64 hold)
482{
483 if (!_switching || (hold != _switchHoldId) || (_state != State::Recording)) {
484 return;
485 }
486 // Its _finish() starts the requested file and lets the keyframe go.
487 _end();
488}
489
490void RecordingBranch::_releaseSwitchHold()
491{
492 _switchHold.remove();
493 _switching = false;
494 // Both at once: a pad lets go of what it holds only once its last blocking probe is gone.
495 if (const gulong capsHold = _capsHold.exchange(0, std::memory_order_acq_rel); (capsHold != 0) && _head.valve()) {
496 const GStreamer::GstPadPtr valveSrc = GStreamer::adoptPad(gst_element_get_static_pad(_head.valve(), "src"));
497 gst_pad_remove_probe(valveSrc.get(), capsHold);
498 }
499}
500
501void RecordingBranch::_end(const QString& failure)
502{
503 if (_state != State::Recording) {
504 return;
505 }
506 if (!failure.isEmpty()) {
507 _failure = failure;
508 }
509
510 _head.close();
511 _keyframeWatch.remove();
512 _watchTimer.stop();
513
514 if (!_fileStarted.load(std::memory_order_acquire)) {
515 _finish(QString());
516 return;
517 }
518
519 // Unlinked, so the next recording can take the valve while this one drains parser -> muxer -> file. Not sent from
520 // here: the EOS waits for the recorder's streaming thread, which slow storage can hold up.
521 const GStreamer::GstPadPtr valveSrc = GStreamer::adoptPad(gst_element_get_static_pad(_head.valve(), "src"));
522 const GStreamer::GstPadPtr recorderSink = GStreamer::adoptPad(gst_pad_get_peer(valveSrc.get()));
523 if (!recorderSink || !gst_pad_unlink(valveSrc.get(), recorderSink.get())) {
524 qCWarning(GstVideoReceiverLog) << "Unable to unlink the recording sink";
525 _finish(notFinalizedError());
526 return;
527 }
528 GStreamer::sendEventAsync(recorderSink.get(), gst_event_new_eos());
529 _state = State::Finalizing;
530 _finalizeTimer.start();
531}
532
533void RecordingBranch::_finish(const QString& error, bool fileClosed)
534{
535 _finalizeTimer.stop();
536 _watchTimer.stop();
537 _keyframeWatch.remove();
538 _startWatch.remove();
539 _capsWatch.remove();
540 _head.close();
541
542 if (_fileSink) {
543 // Removed before going NULL, so nothing it posts while stopping reaches the bus. Flushed unless it closed its
544 // file: going NULL would otherwise wait for a streaming thread stuck inside it.
545 if (fileClosed) {
546 GStreamer::disposeChild(_fileSink.get());
547 } else {
548 GStreamer::flushAndDisposeChild(_fileSink.get());
549 }
550 _fileSink.reset();
551 }
552 _state = State::Idle;
553 _context.dotDumper->dump(_context.pipeline, "pipeline-recording-stopped");
554
555 const QString file = _current.file;
556 const bool fileOpened = _fileStarted.load(std::memory_order_acquire);
557 if (fileOpened) {
558 _reportOpened();
559 const QString fileError = error.isEmpty() ? _failure : error;
560 qCDebug(GstVideoReceiverLog) << "Recording closed" << file << fileError;
561 _listener.onRecordingFileClosed(file, fileError);
562 } else if (QFile::exists(file) && !QFile::remove(file)) {
563 // The filesink created the file, but it never got a frame.
564 qCDebug(GstVideoReceiverLog) << "Unable to remove the empty recording" << file;
565 }
566
567 if (!_failure.isEmpty()) {
568 if (_requested && (_requested->file == file)) {
569 _requested.reset();
570 }
571 const QString failure = std::exchange(_failure, QString());
572 _listener.onRecordingFailed(file, failure, fileOpened);
573 }
574
575 _reconcile();
576
577 // A keyframe or a change of caps held for a switch goes into the file _reconcile() started. Without one it finds
578 // the valve closed, which hides that nothing is linked behind it.
579 _releaseSwitchHold();
580}
581
583{
584 _requested.reset();
585 // What is held for a switch that won't happen goes into the current file, ahead of the EOS that drains it, and
586 // nothing more is held: no file follows.
587 _capsWatch.remove();
588 _releaseSwitchHold();
589 if (_state != State::Recording) {
590 return finalizing();
591 }
592
593 if (!_fileStarted.load(std::memory_order_acquire)) {
594 _end();
595 return finalizing();
596 }
597
598 // EOS at the tee drains the recorder queue into the file. Not sent to the pipeline: a source handles that EOS under
599 // its streaming thread's stream lock, which a thread held downstream would never release.
600 const GStreamer::GstPadPtr teeSink = GStreamer::adoptPad(gst_element_get_static_pad(_context.tee, "sink"));
601 GStreamer::sendEventAsync(teeSink.get(), gst_event_new_eos());
602 _state = State::Finalizing;
603 return true;
604}
605
607{
608 if (_state != State::Finalizing) {
609 return;
610 }
611
612 // Before the flush, which a recorder stuck in the kernel can hold up.
613 warnNotFinalized();
614 // Not serialized, so it doesn't wait for the stream lock: wakes the tee's thread if the full queue holds it, and
615 // has the queue stop pushing into the recorder.
616 const GStreamer::GstPadPtr queueSink = GStreamer::adoptPad(gst_element_get_static_pad(_head.queue(), "sink"));
617 (void) gst_pad_send_event(queueSink.get(), gst_event_new_flush_start());
618 _finish(notFinalizedError());
619}
620
621bool RecordingBranch::_fromRecorder(GstObject* source) const
622{
623 return _fileSink && source && gst_object_has_as_ancestor(source, GST_OBJECT_CAST(_fileSink.get()));
624}
625
626void RecordingBranch::onBusError(GstMessage* message, const GError* error, const QString& text, const char* debug)
627{
628 if (!_fromRecorder(GST_MESSAGE_SRC(message))) {
629 qCDebug(GstVideoReceiverLog) << "Ignoring an error from an earlier recording:" << text;
630 return;
631 }
632
633 // The detail names the cause behind a generic text such as "Could not multiplex stream."
634 if (debug) {
635 qCWarning(GstVideoReceiverLog) << "Recording error:" << text << "-" << debug;
636 } else {
637 qCWarning(GstVideoReceiverLog) << "Recording error:" << text;
638 }
639 // GStreamer's text for it names the file, not the cause.
640 _failure = reportsFullStorage(error, debug) ? QCoreApplication::translate("RecordingBranch", "The storage is full.")
641 : text;
642 // The bus handler closed the valve already: a failing recorder ends the recording, not the stream.
643 _finish(QString());
644}
645
646void RecordingBranch::onBusElement(GstMessage* message)
647{
648 // The recorder's EOS as the pipeline forwards it (message-forward), ahead of the pipeline's own EOS. That one is
649 // ignored: without a display sink it follows every recorder's EOS, and may arrive once the next recording started.
650 const GstStructure* structure = gst_message_get_structure(message);
651 if (!structure || !gst_structure_has_name(structure, "GstBinForwarded")) {
652 return;
653 }
654 GstMessage* forwardedMessage = nullptr;
655 (void) gst_structure_get(structure, "message", GST_TYPE_MESSAGE, &forwardedMessage, nullptr);
656 const GStreamer::GstMessagePtr forwarded = GStreamer::adoptMessage(forwardedMessage);
657 if (!forwarded || (GST_MESSAGE_TYPE(forwarded.get()) != GST_MESSAGE_EOS)) {
658 return;
659 }
660 if (!_fromRecorder(GST_MESSAGE_SRC(forwarded.get()))) {
661 return;
662 }
663 if (_state == State::Recording) {
664 // The stream's own EOS came through the open valve. Nothing more will stream through this pipeline, so the
665 // request waits for the next one rather than start over in the file just closed.
666 _streaming = false;
667 }
668 qCDebug(GstVideoReceiverLog) << "Recording finalized" << _current.file;
669 _finish(QString(), /*fileClosed=*/true);
670}
671
672void RecordingBranch::_onFileOpened(quint64 recording)
673{
674 if ((recording != _recording.load(std::memory_order_relaxed)) || (_state != State::Recording)) {
675 return;
676 }
677 _reportOpened();
678}
679
680void RecordingBranch::_onOverrun(quint64 recording)
681{
682 if ((recording != _recording.load(std::memory_order_relaxed)) || (_state != State::Recording)) {
683 return;
684 }
685 qCWarning(GstVideoReceiverLog) << "Recording storage too slow, its backlog is full; ending the recording"
686 << _current.file;
687 _end(QCoreApplication::translate("RecordingBranch", "The storage is too slow to keep up with the video."));
688}
689
690void RecordingBranch::_onCapsChanged(quint64 recording)
691{
692 if ((_capsHold.load(std::memory_order_acquire) == 0) || (_state == State::Finalizing)) {
693 // Let go already, or held until _finish() has started what follows the file that is finishing.
694 return;
695 }
696 if ((_state != State::Recording) || (recording != _recording.load(std::memory_order_relaxed))) {
697 // The file the change was held for is gone: it goes on to what is linked by now.
698 _releaseSwitchHold();
699 _reconcile();
700 return;
701 }
702
703 qCDebug(GstVideoReceiverLog) << "The stream's caps changed while recording" << _current.file;
704 if (_requested && (*_requested == _current)) {
705 // The listener counts a file from this report on.
706 _reportOpened();
707 _listener.onRecordingNeedsNewFile(_current.file);
708 }
709 // Ends the file where the stream is held, for the one requested by now. Without one the change goes on into the
710 // file, whose muxer decides whether it can take it.
711 _reconcile();
712}
713
714void RecordingBranch::_checkStarted()
715{
716 if ((_state != State::Recording) || _fileStarted.load(std::memory_order_acquire)) {
717 return;
718 }
719 const gint64 fedAt = _fedAt.load(std::memory_order_relaxed);
720 if ((fedAt == 0) || ((g_get_monotonic_time() - fedAt) < std::chrono::microseconds(kStartTimeout).count())) {
721 return;
722 }
723 qCWarning(GstVideoReceiverLog) << "No keyframe to start the recording with within"
724 << std::chrono::seconds(kStartTimeout).count()
725 << "s of the stream's first one, as when keyframes come without their parameter"
726 << "sets; ending the recording" << _current.file;
727 _end(
728 QCoreApplication::translate("RecordingBranch", "The video stream has no keyframe a recording can start from."));
729}
730
731void RecordingBranch::_checkHeaderSpace()
732{
733 // A switch under way leaves the file soon enough. Until its second header update the muxer has its estimate from
734 // the file's first frame alone: seconds, when that frame and the next arrived together.
735 if ((_state != State::Recording) || _switching || !_fileSink || !_openedReported ||
736 !_openedFor.hasExpired(std::chrono::milliseconds(kHeaderEstimateDelay).count())) {
737 return;
738 }
739 const GStreamer::GstElementPtr muxer =
740 GStreamer::adoptElement(gst_bin_get_by_name(GST_BIN(_fileSink.get()), "muxer"));
741 if (!muxer || !g_object_class_find_property(G_OBJECT_GET_CLASS(muxer.get()), "reserved-duration-remaining")) {
742 return;
743 }
744 // The muxer's estimate from the space the recording used so far.
745 guint64 remainingNs = 0;
746 g_object_get(muxer.get(), "reserved-duration-remaining", &remainingNs, nullptr);
747 if (remainingNs >= static_cast<guint64>(std::chrono::nanoseconds(kHeaderSpaceMargin).count())) {
748 return;
749 }
750 qCDebug(GstVideoReceiverLog) << "Header space left for about" << (remainingNs / GST_SECOND) << "s in"
751 << _current.file;
752 _listener.onRecordingNeedsNewFile(_current.file);
753}
754
755void RecordingBranch::_reportOpened()
756{
757 if (_openedReported) {
758 return;
759 }
760 _openedReported = true;
761 _openedFor.start();
762 qCDebug(GstVideoReceiverLog) << "Recording started" << _current.file;
763 _listener.onRecordingFileOpened(_current.file);
764}
765
766GstPadProbeReturn RecordingBranch::_keyframeProbe([[maybe_unused]] GstPad* pad, GstPadProbeInfo* info, gpointer data)
767{
768 auto* const self = static_cast<RecordingBranch*>(data);
769 if (self->_fedAt.load(std::memory_order_relaxed) != 0) {
770 return GST_PAD_PROBE_OK;
771 }
772
773 // Upstream of the tee is always a parser (GstBaseParse), which pushes single buffers, never lists.
774 const GstBuffer* const buffer = gst_pad_probe_info_get_buffer(info);
775 if (!buffer || GST_BUFFER_FLAG_IS_SET(buffer, GST_BUFFER_FLAG_DELTA_UNIT)) {
776 return GST_PAD_PROBE_DROP;
777 }
778 self->_fedAt.store(g_get_monotonic_time(), std::memory_order_relaxed);
779 return GST_PAD_PROBE_OK;
780}
781
782GstPadProbeReturn RecordingBranch::_startProbe(GstPad* pad, GstPadProbeInfo* info, gpointer data)
783{
784 const auto* const watch = static_cast<const RecordingWatch*>(data);
785 RecordingBranch* const self = watch->branch;
786 if (self->_fileStarted.load(std::memory_order_relaxed)) {
787 return GST_PAD_PROBE_OK;
788 }
789
790 // As the one upstream of the tee, the recorder's parser pushes single buffers.
791 GstBuffer* buf = gst_pad_probe_info_get_buffer(info);
792 if (!buf || GST_BUFFER_FLAG_IS_SET(buf, GST_BUFFER_FLAG_DELTA_UNIT) || !GST_BUFFER_PTS_IS_VALID(buf)) {
793 return GST_PAD_PROBE_DROP;
794 }
795
796 // The offset applies to running time, which differs from the PTS when the segment doesn't start at 0.
797 GstClockTime runningTime = GST_CLOCK_TIME_NONE;
798 if (const GStreamer::GstEventPtr segmentEvent =
799 GStreamer::adoptEvent(gst_pad_get_sticky_event(pad, GST_EVENT_SEGMENT, 0))) {
800 const GstSegment* segment = nullptr;
801 gst_event_parse_segment(segmentEvent.get(), &segment);
802 if (segment && (segment->format == GST_FORMAT_TIME)) {
803 runningTime = gst_segment_to_running_time(segment, GST_FORMAT_TIME, GST_BUFFER_PTS(buf));
804 }
805 }
806 if (!GST_CLOCK_TIME_IS_VALID(runningTime)) {
807 return GST_PAD_PROBE_DROP;
808 }
809
810 // Starts the file at 0; only the elements downstream of this pad see the offset.
811 gst_pad_set_offset(pad, -static_cast<gint64>(runningTime));
812
813 self->_fileStarted.store(true, std::memory_order_release);
814 // Reported from the worker, which knows whether this recording is still the current one.
815 const quint64 recording = watch->recording;
816 self->_context.post([self, recording]() { self->_onFileOpened(recording); });
817 return GST_PAD_PROBE_OK;
818}
819
820GstPadProbeReturn RecordingBranch::_capsProbe(GstPad* pad, GstPadProbeInfo* info, gpointer data)
821{
822 const auto* const watch = static_cast<const RecordingWatch*>(data);
823 RecordingBranch* const self = watch->branch;
824 GstEvent* const event = gst_pad_probe_info_get_event(info);
825 // Until its file starts the recorder takes the caps as they come, and one change is held at a time.
826 if (!event || (GST_EVENT_TYPE(event) != GST_EVENT_CAPS) || !self->_fileStarted.load(std::memory_order_acquire) ||
827 (self->_capsHold.load(std::memory_order_acquire) != 0)) {
828 return GST_PAD_PROBE_OK;
829 }
830
831 // A sink pad takes up an event after its probes, so it still has the caps the file records.
832 GstCaps* caps = nullptr;
833 gst_event_parse_caps(event, &caps);
834 const GStreamer::GstCapsPtr recorded = GStreamer::adoptCaps(gst_pad_get_current_caps(pad));
835 const GStreamer::GstElementPtr valve = GStreamer::adoptElement(gst_pad_get_parent_element(pad));
836 if (!valve || (recorded && gst_caps_is_equal(recorded.get(), caps))) {
837 return GST_PAD_PROBE_OK;
838 }
839
840 // matroskamux takes no other caps in a file it has begun, and qtmux only some (a resolution, not a pixel aspect
841 // ratio), which not every player follows. The event is held where the valve passes it on next, so the file ends
842 // before it and the next one begins with it. Not held by a probe that stays on that pad: one blocking probe left
843 // on a pad keeps it from letting go of what another one held.
844 const GStreamer::GstPadPtr valveSrc = GStreamer::adoptPad(gst_element_get_static_pad(valve.get(), "src"));
845 self->_capsHold.store(
846 gst_pad_add_probe(valveSrc.get(),
847 static_cast<GstPadProbeType>(GST_PAD_PROBE_TYPE_BLOCK | GST_PAD_PROBE_TYPE_EVENT_DOWNSTREAM),
848 holdCapsEvent, gst_caps_ref(caps),
849 [](gpointer held) { gst_caps_unref(static_cast<GstCaps*>(held)); }),
850 std::memory_order_release);
851 const quint64 recording = watch->recording;
852 self->_context.post([self, recording]() { self->_onCapsChanged(recording); });
853 return GST_PAD_PROBE_OK;
854}
855
856GstPadProbeReturn RecordingBranch::_switchProbe([[maybe_unused]] GstPad* pad, GstPadProbeInfo* info, gpointer data)
857{
858 const GstBuffer* const buffer = gst_pad_probe_info_get_buffer(info);
859 if (!buffer || GST_BUFFER_FLAG_IS_SET(buffer, GST_BUFFER_FLAG_DELTA_UNIT) || !GST_BUFFER_PTS_IS_VALID(buffer)) {
860 // Passes, and the probe is asked again for the next buffer.
861 return GST_PAD_PROBE_PASS;
862 }
863
864 const auto* const watch = static_cast<const SwitchWatch*>(data);
865 RecordingBranch* const self = watch->branch;
866 const quint64 hold = watch->hold;
867 self->_context.post([self, hold]() { self->_onSwitchKeyframe(hold); });
868 // Blocks, with the keyframe, until the probe is removed.
869 return GST_PAD_PROBE_OK;
870}
871
872void RecordingBranch::_onQueueOverrun(GstElement* queue, gpointer data)
873{
874 auto* const self = static_cast<RecordingBranch*>(data);
875 // Read back by the queue right after this handler: it now drops the frame instead of waiting for room, so the tee
876 // (and the display behind it) never waits for slow storage.
877 gst_util_set_object_arg(G_OBJECT(queue), "leaky", "upstream");
878 const quint64 recording = self->_recording.load(std::memory_order_relaxed);
879 self->_context.post([self, recording]() { self->_onOverrun(recording); });
880}
struct _GstElement GstElement
static constexpr std::chrono::seconds kFinalizeTimeout
static constexpr std::chrono::seconds kHeaderEstimateDelay
static constexpr guint64 kQueueMaxBytes
Backlog the recording queue holds for slow storage before the recording gives up.
void completeTeardown()
Closes a file whose finalization is still outstanding by flushing the recorder, and reports it.
void onBusError(GstMessage *message, const GError *error, const QString &text, const char *debug)
RecordingBranch(const BranchContext &context, Listener &listener)
void setRequest(const std::optional< Request > &request)
GstElement * valve() const
static constexpr std::chrono::seconds kHeaderSpaceMargin
void onBusElement(GstMessage *message)
A bus ELEMENT message: the current recorder's EOS, as the pipeline forwards it, means its file is clo...
bool finalizing() const
bool build()
Adds the branch's queue and closed valve behind the tee.
void onSourceStreaming()
The first frame reached the tee, so the input caps are known: a waiting request starts.
void reset()
Drops the recording, if any, without reports; the pipeline must be in NULL.
static GStreamer::GstElementPtr makeFileSink(const QString &file, VideoReceiver::FileFormat format, const GstCaps *inputCaps)
static constexpr std::chrono::seconds kStartTimeout
static constexpr std::chrono::minutes kMaxPartDuration
static void absorbFlowErrors(GstElement *part)
FileFormat
Values are persisted by VideoSettings::recordingFormat.
static QString recordingComment()
The comment recordings carry, of GStreamer and of a USB camera alike: the application and its version...
void disposeChild(GstElement *element)
std::unique_ptr< GstCaps, GstCapsDeleter > GstCapsPtr
Definition GstScoped.h:66
std::unique_ptr< GstEvent, GstEventDeleter > GstEventPtr
Definition GstScoped.h:68
GstElementPtr makeElement(const char *factory, const char *name=nullptr)
Definition GstScoped.h:178
GstEventPtr adoptEvent(GstEvent *event) noexcept
Definition GstScoped.h:119
void markBranch(GstElement *element, PipelineBranch branch)
Marks element and everything inside it as part of branch.
GstElement * addToBin(GstElement *bin, GstElementPtr element, const char *what)
std::unique_ptr< T, GstObjectDeleter > adoptFloating(T *object) noexcept
Sinks the floating ref of a new object (pipeline, bin, pad, element) and owns it. Null for null.
Definition GstScoped.h:171
void sendEventAsync(GstPad *pad, GstEvent *event)
GstCapsPtr adoptCaps(GstCaps *caps) noexcept
Definition GstScoped.h:109
std::unique_ptr< GstElement, GstObjectDeleter > GstElementPtr
Definition GstScoped.h:60
std::unique_ptr< GstPad, GstObjectDeleter > GstPadPtr
Definition GstScoped.h:61
GstElementPtr adoptElement(GstElement *element) noexcept
Definition GstScoped.h:79
QByteArray glibFileName(const QString &file)
std::unique_ptr< GstMessage, GstMessageDeleter > GstMessagePtr
Definition GstScoped.h:67
GstMessagePtr adoptMessage(GstMessage *message) noexcept
Definition GstScoped.h:114
void flushAndDisposeChild(GstElement *element)
GstPadPtr adoptPad(GstPad *pad) noexcept
Definition GstScoped.h:84
std::function< void(std::function< void()>)> post
Runs a task on the worker thread unless the session is gone by then.