KPipewire

pipewirerecord.cpp
1/*
2 SPDX-FileCopyrightText: 2022 Aleix Pol Gonzalez <aleixpol@kde.org>
3
4 SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
5*/
6
7#include "pipewirerecord.h"
8#include "encoder_p.h"
9#include "glhelpers.h"
10#include "pipewirerecord_p.h"
11#include <logging_record.h>
12
13#include <QGuiApplication>
14#include <QImage>
15#include <QPainter>
16#include <qpa/qplatformnativeinterface.h>
17
18#include <KShell>
19
20#include <unistd.h>
21extern "C" {
22#include <libavcodec/avcodec.h>
23#include <libavformat/avformat.h>
24#include <libavutil/timestamp.h>
25}
26
27#undef av_err2str
28
29#ifdef av_ts2str
30#undef av_ts2str
31char buf[AV_TS_MAX_STRING_SIZE];
32#define av_ts2str(ts) av_ts_make_string(buf, ts)
33#endif // av_ts2str
34
35#ifdef av_ts2timestr
36#undef av_ts2timestr
37char timebuf[AV_TS_MAX_STRING_SIZE];
38#define av_ts2timestr(ts, tb) av_ts_make_time_string(timebuf, ts, tb)
39#endif // av_ts2timestr
40
41static void log_packet(const AVFormatContext *fmt_ctx, const AVPacket *pkt)
42{
43 AVRational *time_base = &fmt_ctx->streams[pkt->stream_index]->time_base;
44
45 qCDebug(PIPEWIRERECORD_LOGGING,
46 "pts:%s pts_time:%s dts:%s dts_time:%s duration:%s duration_time:%s "
47 "stream_index:%d",
48 av_ts2str(pkt->pts),
49 av_ts2timestr(pkt->pts, time_base),
50 av_ts2str(pkt->dts),
51 av_ts2timestr(pkt->dts, time_base),
52 av_ts2str(pkt->duration),
53 av_ts2timestr(pkt->duration, time_base),
54 pkt->stream_index);
55}
56
57PipeWireRecord::PipeWireRecord(QObject *parent)
58 : PipeWireBaseEncodedStream(parent)
59 , d(new PipeWireRecordPrivate)
60{
61}
62
63PipeWireRecord::~PipeWireRecord() = default;
64
65void PipeWireRecord::setOutput(const QString &_output)
66{
67 const QString output = KShell::tildeExpand(_output);
68
69 if (d->m_output == output)
70 return;
71
72 d->m_output = output;
73 refresh();
74 Q_EMIT outputChanged(output);
75}
76
77QString PipeWireRecord::output() const
78{
79 return d->m_output;
80}
81
82QString PipeWireRecord::extension() const
83{
85 {PipeWireBaseEncodedStream::H264Main, QStringLiteral("mp4")},
86 {PipeWireBaseEncodedStream::H264Baseline, QStringLiteral("mp4")},
87 {PipeWireBaseEncodedStream::VP8, QStringLiteral("webm")},
88 {PipeWireBaseEncodedStream::VP9, QStringLiteral("webm")},
89 };
90 return s_extensions.value(encoder());
91}
92
93PipeWireRecordProduce::PipeWireRecordProduce(PipeWireBaseEncodedStream::Encoder encoder, uint nodeId, uint fd, const Fraction &framerate, const QString &output)
94 : PipeWireProduce(encoder, nodeId, fd, framerate)
95 , m_output(output)
96{
97}
98
99bool PipeWireRecordProduce::setupFormat()
100{
101 avformat_alloc_output_context2(&m_avFormatContext, nullptr, nullptr, m_output.toUtf8().constData());
102 if (!m_avFormatContext) {
103 qCWarning(PIPEWIRERECORD_LOGGING) << "Could not deduce output format from file: using WebM." << m_output;
104 avformat_alloc_output_context2(&m_avFormatContext, nullptr, "webm", m_output.toUtf8().constData());
105 }
106 if (!m_avFormatContext) {
107 qCDebug(PIPEWIRERECORD_LOGGING) << "could not set stream up";
108 return false;
109 }
110
111 const Fraction framerate = m_stream->framerate();
112 int ret = avio_open(&m_avFormatContext->pb, QFile::encodeName(m_output).constData(), AVIO_FLAG_WRITE);
113 if (ret < 0) {
114 qCWarning(PIPEWIRERECORD_LOGGING) << "Could not open" << m_output << av_err2str(ret);
115 return false;
116 }
117
118 auto avStream = avformat_new_stream(m_avFormatContext, nullptr);
119 avStream->start_time = 0;
120 if (framerate) {
121 avStream->r_frame_rate.num = framerate.numerator;
122 avStream->r_frame_rate.den = framerate.denominator;
123 avStream->avg_frame_rate.num = framerate.numerator;
124 avStream->avg_frame_rate.den = framerate.denominator;
125 }
126
127 ret = avcodec_parameters_from_context(avStream->codecpar, m_encoder->avCodecContext());
128 if (ret < 0) {
129 qCWarning(PIPEWIRERECORD_LOGGING) << "Error occurred when passing the codec:" << av_err2str(ret);
130 return false;
131 }
132
133 ret = avformat_write_header(m_avFormatContext, nullptr);
134 if (ret < 0) {
135 qCWarning(PIPEWIRERECORD_LOGGING) << "Error occurred when writing header:" << av_err2str(ret);
136 return false;
137 }
138
139 return true;
140}
141
142void PipeWireRecordProduce::processFrame(const PipeWireFrame &frame)
143{
144 PipeWireProduce::processFrame(frame);
145 if (frame.cursor && !frame.dmabuf && !frame.dataFrame && m_frameWithoutMetadataCursor.dataFrame) {
146 m_encoder->filterFrame(m_frameWithoutMetadataCursor);
147 }
148}
149
150void PipeWireRecordProduce::aboutToEncode(PipeWireFrame &frame)
151{
152 if (!frame.dataFrame) {
153 return;
154 }
155
156 if (m_cursor.position && !m_cursor.texture.isNull()) {
157 auto image = frame.dataFrame->toImage();
158 // Do not copy the image if it's already ours
159 if (m_frameWithoutMetadataCursor.dataFrame->cleanup != frame.dataFrame->cleanup) {
160 m_frameWithoutMetadataCursor.dataFrame = frame.dataFrame->copy();
161 }
162 QPainter p(&image);
163 p.drawImage(*m_cursor.position, m_cursor.texture);
164 }
165}
166
167void PipeWireRecordProduce::processPacket(AVPacket *packet)
168{
169 packet->stream_index = (*m_avFormatContext->streams)->index;
170 av_packet_rescale_ts(packet, m_encoder->avCodecContext()->time_base, (*m_avFormatContext->streams)->time_base);
171 log_packet(m_avFormatContext, packet);
172 auto ret = av_interleaved_write_frame(m_avFormatContext, packet);
173 if (ret < 0) {
174 qCWarning(PIPEWIRERECORD_LOGGING) << "Error while writing output packet:" << av_err2str(ret);
175 }
176}
177
178std::unique_ptr<PipeWireProduce> PipeWireRecord::makeProduce()
179{
180 return std::make_unique<PipeWireRecordProduce>(encoder(), nodeId(), fd(), maxFramerate(), d->m_output);
181}
182
183int64_t PipeWireRecordProduce::framePts(const std::optional<std::chrono::nanoseconds> &presentationTimestamp)
184{
185 const auto current = std::chrono::duration_cast<std::chrono::milliseconds>(*presentationTimestamp).count();
186 if ((*m_avFormatContext->streams)->start_time == 0) {
187 (*m_avFormatContext->streams)->start_time = current;
188 }
189
190 return current - (*m_avFormatContext->streams)->start_time;
191}
192
193void PipeWireRecordProduce::cleanup()
194{
195 if (m_avFormatContext) {
196 if (auto result = av_write_trailer(m_avFormatContext); result < 0) {
197 qCWarning(PIPEWIRERECORD_LOGGING) << "Could not write trailer";
198 }
199
200 avio_closep(&m_avFormatContext->pb);
201 avformat_free_context(m_avFormatContext);
202 }
203}
204
205#include "moc_pipewirerecord.cpp"
206
207#include "moc_pipewirerecord_p.cpp"
KCOREADDONS_EXPORT QString tildeExpand(const QString &path)
const char * constData() const const
QByteArray encodeName(const QString &fileName)
T value(const Key &key) const const
Q_EMITQ_EMIT
This file is part of the KDE documentation.
Documentation copyright © 1996-2024 The KDE developers.
Generated on Mon Nov 18 2024 12:15:17 by doxygen 1.12.0 written by Dimitri van Heesch, © 1997-2006

KDE's Doxygen guidelines are available online.