// SPDX-FileCopyrightText: 2026 Matvey Shcherbinin // SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL #include "VideoPoster.h" #include #include #include #include #include #include #include #include #include #include #include #include namespace { // A frame one second in says more about the recording than the very first // one, which is a black lead-in more often than a picture. constexpr qint64 kPosterPositionMs = 1000; // A poster the size of the video itself would be as heavy in memory as the // video; the tile draws it a few grid units wide. constexpr int kMaxPosterEdge = 640; // A decode that has produced nothing in this long is not going to: a codec // the platform has no decoder for fails by silence, not by error. constexpr int kGrabTimeoutMs = 8000; constexpr int kJpegQuality = 85; // Frames earlier than this (start time in microseconds) are the lead-in the // initial seek is still skipping past, not the wanted one. constexpr qint64 kMinFrameStartUs = kPosterPositionMs * 1000 * 9 / 10; QString posterCacheDir() { return QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + QStringLiteral("/video-posters"); } } VideoPoster::VideoPoster(QObject *parent) : QObject(parent) { m_player = new QMediaPlayer(this); m_audio = new QAudioOutput(this); m_audio->setMuted(true); m_player->setAudioOutput(m_audio); m_sink = new QVideoSink(this); m_player->setVideoSink(m_sink); // Some backends deliver the wanted frame while paused after a seek, the // rest only once playing, so the frame comes from whichever stream arrives // after the position lands. connect(m_player, &QMediaPlayer::mediaStatusChanged, this, [this](QMediaPlayer::MediaStatus status) { if (status != QMediaPlayer::LoadedMedia) return; if (m_player->duration() > 3 * kPosterPositionMs) m_player->setPosition(kPosterPositionMs); m_player->play(); }); connect(m_sink, &QVideoSink::videoFrameChanged, this, [this](const QVideoFrame &frame) { if (!m_busy || m_grabbed || !frame.isValid()) return; // The frames while the seek is still running are the lead-in; when // the video is too short to seek within, the first frame is the one. if (m_player->duration() > 3 * kPosterPositionMs && frame.startTime() < kMinFrameStartUs) return; m_grabbed = true; m_player->stop(); m_player->setSource(QUrl()); QImage image = frame.toImage(); if (image.isNull()) { complete({}, QStringLiteral("the grabbed frame could not be converted to an image")); return; } if (image.width() > kMaxPosterEdge) image = image.scaledToWidth(kMaxPosterEdge, Qt::SmoothTransformation); QDir().mkpath(posterCacheDir()); if (image.save(m_current.cachePath, "JPEG", kJpegQuality)) complete(m_current.cachePath); else complete({}, QStringLiteral("the frame was grabbed but not written to the cache")); }); } QString VideoPoster::posterFor(const QString &videoPath) { const QFileInfo info(videoPath); if (!info.isFile() || !info.isReadable()) return {}; const QString cachePath = cachePathFor(videoPath); if (QFileInfo::exists(cachePath)) return cachePath; // A video that gave no frame once does not get decoded again for it: the // tile it belongs to has a fallback to draw. if (m_failed.contains(cachePath)) return {}; m_queue.enqueue({videoPath, cachePath}); grabNext(); return {}; } void VideoPoster::grabNext() { if (m_busy || m_queue.isEmpty()) return; m_busy = true; m_grabbed = false; m_current = m_queue.dequeue(); m_since.start(); m_player->setSource(QUrl::fromLocalFile(m_current.videoPath)); const QString cachePath = m_current.cachePath; QTimer::singleShot(kGrabTimeoutMs, this, [this, cachePath]() { // A job that is no longer current has been answered; the cache-path // guard keeps a stale timer from abandoning the queue's next occupant. if (!m_busy || m_current.cachePath != cachePath || m_grabbed) return; // before the source is cleared, which takes the player's own account // of what went wrong with it. const QString error = m_player->errorString(); m_player->stop(); m_player->setSource(QUrl()); complete({}, error); }); } void VideoPoster::complete(const QString &posterPath, const QString &error) { if (posterPath.isEmpty()) { m_failed.insert(m_current.cachePath); // The tile's fallback hides this from the reader; without a line here, // why one chat draws a plate is nowhere to be found. qCWarning(KOUTNET_LOG_MEDIA) << "no poster frame for" << m_current.videoPath << "-" << (error.isEmpty() ? QStringLiteral("no frame arrived within the timeout") : error); } m_busy = false; Q_EMIT posterReady(m_current.videoPath, posterPath); grabNext(); } QString VideoPoster::cachePathFor(const QString &videoPath) const { const QFileInfo info(videoPath); const QString seed = videoPath + QLatin1Char('|') + QString::number(info.size()) + QLatin1Char('|') + QString::number(info.lastModified().toSecsSinceEpoch()); const QString hash = QString::fromLatin1(QCryptographicHash::hash(seed.toUtf8(), QCryptographicHash::Sha1).toHex()); return posterCacheDir() + QStringLiteral("/poster-%1.jpg").arg(hash); }