1// Copyright (C) 2024 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3#include "qffmpegmuxer_p.h"
4#include "qffmpegrecordingengine_p.h"
5#include "qffmpegrecordingengineutils_p.h"
6#include <QtCore/qloggingcategory.h>
7
8QT_BEGIN_NAMESPACE
9
10namespace QFFmpeg {
11
12Q_STATIC_LOGGING_CATEGORY(qLcFFmpegMuxer, "qt.multimedia.ffmpeg.muxer");
13
14Muxer::Muxer(RecordingEngine *encoder) : m_encoder(encoder)
15{
16 setObjectName(QLatin1String("Muxer"));
17}
18
19void Muxer::addPacket(AVPacketUPtr packet)
20{
21 {
22 QMutexLocker locker = lockLoopData();
23 m_packetQueue.push(x: std::move(packet));
24 }
25
26 // qCDebug(qLcFFmpegEncoder) << "Muxer::addPacket" << packet->pts << packet->stream_index;
27 dataReady();
28}
29
30AVPacketUPtr Muxer::takePacket()
31{
32 QMutexLocker locker = lockLoopData();
33 return dequeueIfPossible(queue&: m_packetQueue);
34}
35
36bool Muxer::init()
37{
38 qCDebug(qLcFFmpegMuxer) << "Muxer::init started thread.";
39 return true;
40}
41
42void Muxer::cleanup()
43{
44 while (!m_packetQueue.empty())
45 processOne();
46}
47
48bool QFFmpeg::Muxer::hasData() const
49{
50 return !m_packetQueue.empty();
51}
52
53void Muxer::processOne()
54{
55 auto packet = takePacket();
56 // qCDebug(qLcFFmpegEncoder) << "writing packet to file" << packet->pts << packet->duration <<
57 // packet->stream_index;
58
59 // from AVPacket Struct Reference:
60 // "The semantics of data ownership depends on the buf field. If it is set, the packet data is
61 // dynamically allocated and is valid indefinitely until a call to av_packet_unref() reduces the
62 // reference count to 0."
63 //
64 // from av_interleaved_write_frame:
65 // "If the packet is reference-counted, this function will take ownership of this reference and
66 // unreference it later when it sees fit. The caller must not access the data through this
67 // reference after this function returns. If the packet is not reference-counted, libavformat
68 // will make a copy."
69 //
70 // This means that av_interleaved_write_frame takes ownership of the AVBufferRef field, not the
71 // whole AVPacket.
72
73 av_interleaved_write_frame(s: m_encoder->avFormatContext(), pkt: packet.get());
74 Q_ASSERT(packet->buf == nullptr); // av_interleaved_write_frame took ownership of the buffer
75}
76
77} // namespace QFFmpeg
78
79QT_END_NAMESPACE
80

source code of qtmultimedia/src/plugins/multimedia/ffmpeg/recordingengine/qffmpegmuxer.cpp