1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
/* ============================================================
 *
 * This file is a part of digiKam project
 * https://www.digikam.org
 *
 * Date        : 2016-04-21
 * Description : video thumbnails extraction based on ffmpeg
 *
 * SPDX-FileCopyrightText: 2010      by Dirk Vanden Boer <dirk dot vdb at gmail dot com>
 * SPDX-FileCopyrightText: 2016-2018 by Maik Qualmann <metzpinguin at gmail dot com>
 * SPDX-FileCopyrightText: 2016-2025 by Gilles Caulier <caulier dot gilles at gmail dot com>
 *
 * SPDX-License-Identifier: GPL-2.0-or-later
 *
 * ============================================================ */

#include "videothumbnailer.h"

// C++ includes

#include <cfloat>

// Qt includes

#include <QtGlobal>
#include <QtMath>
#include <QTime>

// Local includes

#include "digikam_debug.h"
#include "videothumbdecoder.h"
#include "videostripfilter.h"
#include "videothumbwriter.h"

using namespace std;

namespace Digikam
{

class Q_DECL_HIDDEN VideoThumbnailer::Private
{
public:

    template <typename T>
    class Q_DECL_HIDDEN Histogram
    {

    public:

        Histogram()
        {
            memset(r, 0, 255 * sizeof(T));
            memset(g, 0, 255 * sizeof(T));
            memset(b, 0, 255 * sizeof(T));
        }

        ~Histogram() = default;

    public:

        T r[256];
        T g[256];
        T b[256];
    };

public:

    Private() = default;

    void generateHistogram(const VideoFrame& videoFrame, Histogram<int>& histogram);
    int  getBestThumbnailIndex(std::vector<VideoFrame>& videoFrames,
                               const std::vector<Histogram<int> >& histograms);

public:

    int                        thumbnailSize        = 256;
    quint16                    seekPercentage       = 10;
    bool                       overlayFilmStrip     = false;
    bool                       workAroundIssues     = false;
    bool                       maintainAspectRatio  = true;
    bool                       smartFrameSelection  = false;
    QString                    seekTime;
    QVector<VideoStripFilter*> filters;

    const int                  SMART_FRAME_ATTEMPTS = 25;
};

VideoThumbnailer::VideoThumbnailer()
    : d(new Private)
{
}

VideoThumbnailer::VideoThumbnailer(int thumbnailSize,
                                   bool workaroundIssues,
                                   bool maintainAspectRatio,
                                   bool smartFrameSelection)
    : d(new Private)
{
    d->thumbnailSize       = thumbnailSize;
    d->workAroundIssues    = workaroundIssues;
    d->maintainAspectRatio = maintainAspectRatio;
    d->smartFrameSelection = smartFrameSelection;
}

VideoThumbnailer::~VideoThumbnailer()
{
    delete d;
}

void VideoThumbnailer::setSeekPercentage(int percentage)
{
    d->seekTime.clear();
    d->seekPercentage = (percentage > 95) ? 95
                                          : percentage;
}

void VideoThumbnailer::setSeekTime(const QString& seekTime)
{
    d->seekTime = seekTime;
}

void VideoThumbnailer::setThumbnailSize(int size)
{
    d->thumbnailSize = size;
}

void VideoThumbnailer::setWorkAroundIssues(bool workAround)
{
    d->workAroundIssues = workAround;
}

void VideoThumbnailer::setMaintainAspectRatio(bool enabled)
{
    d->maintainAspectRatio = enabled;
}

void VideoThumbnailer::setSmartFrameSelection(bool enabled)
{
    d->smartFrameSelection = enabled;
}

int VideoThumbnailer::timeToSeconds(const QString& time) const
{
    return QTime::fromString(time, QLatin1String("hh:mm:ss")).secsTo(QTime(0, 0, 0));
}

void VideoThumbnailer::generateThumbnail(const QString& videoFile,
                                         VideoThumbWriter& imageWriter,
                                         QImage &image)
{
    VideoThumbDecoder movieDecoder(videoFile);

    if (movieDecoder.getInitialized())
    {
        // before seeking, a frame has to be decoded

        if (!movieDecoder.decodeVideoFrame())
        {
            return;
        }

        if ((!d->workAroundIssues) || (movieDecoder.getCodec() != QLatin1String("h264")))
        {
            // workaround for bug in older ffmpeg (100% cpu usage when seeking in h264 files)

            int secondToSeekTo = d->seekTime.isEmpty() ? movieDecoder.getDuration() * d->seekPercentage / 100
                                                       : timeToSeconds(d->seekTime);
            movieDecoder.seek(secondToSeekTo);
        }

        VideoFrame videoFrame;

        if (d->smartFrameSelection)
        {
            generateSmartThumbnail(movieDecoder, videoFrame);
        }
        else
        {
            movieDecoder.getScaledVideoFrame(d->thumbnailSize, d->maintainAspectRatio, videoFrame);
        }

        applyFilters(videoFrame);
        imageWriter.writeFrame(videoFrame, image);
    }
}

void VideoThumbnailer::generateSmartThumbnail(VideoThumbDecoder& movieDecoder,
                                              VideoFrame& videoFrame)
{
    vector<VideoFrame> videoFrames(d->SMART_FRAME_ATTEMPTS);
    vector<Private::Histogram<int> > histograms(d->SMART_FRAME_ATTEMPTS);

    for (int i = 0 ; i < d->SMART_FRAME_ATTEMPTS ; ++i)
    {
        movieDecoder.decodeVideoFrame();
        movieDecoder.getScaledVideoFrame(d->thumbnailSize, d->maintainAspectRatio, videoFrames[i]);
        d->generateHistogram(videoFrames[i], histograms[i]);
    }

    int bestFrame = d->getBestThumbnailIndex(videoFrames, histograms);

    if (bestFrame == -1)
    {
        bestFrame = 0;
    }

    videoFrame = videoFrames[bestFrame];
}

void VideoThumbnailer::generateThumbnail(const QString& videoFile,
                                         QImage &image)
{
    VideoThumbWriter* const imageWriter = new  VideoThumbWriter();
    generateThumbnail(videoFile, *imageWriter, image);
    delete imageWriter;
}

void VideoThumbnailer::addFilter(VideoStripFilter* const filter)
{
    d->filters.append(filter);
}

void VideoThumbnailer::removeFilter(const VideoStripFilter* const filter)
{
    for (QVector<VideoStripFilter*>::iterator it = d->filters.begin() ;
         it != d->filters.end() ; ++it)
    {
        if (*it == filter)
        {<--- Consider using std::find_if algorithm instead of a raw loop.
            d->filters.erase(it);
            break;
        }
    }
}

void VideoThumbnailer::clearFilters()
{
    d->filters.clear();
}

void VideoThumbnailer::applyFilters(VideoFrame& videoFrame)
{
    for (QVector<VideoStripFilter*>::iterator it = d->filters.begin() ;
         it != d->filters.end() ; ++it)
    {
        (*it)->process(videoFrame);
    }
}

void VideoThumbnailer::Private::generateHistogram(const VideoFrame& videoFrame,
                                                  Private::Histogram<int>& histogram)
{
    for (quint32 i = 0 ; i < videoFrame.height ; ++i)
    {
        int pixelIndex = i * videoFrame.lineSize;

        for (quint32 j = 0 ; j < videoFrame.width * 3 ; j += 3)
        {
            ++histogram.r[videoFrame.frameData[pixelIndex + j    ]];
            ++histogram.g[videoFrame.frameData[pixelIndex + j + 1]];
            ++histogram.b[videoFrame.frameData[pixelIndex + j + 2]];
        }
    }
}

int VideoThumbnailer::Private::getBestThumbnailIndex(vector<VideoFrame>& videoFrames,
                                                     const vector<Private::Histogram<int> >& histograms)
{
    Q_UNUSED(videoFrames);

    Private::Histogram<float> avgHistogram;

    for (size_t i = 0 ; i < histograms.size() ; ++i)
    {
        for (int j = 0 ; j < 255 ; ++j)
        {
            avgHistogram.r[j] += static_cast<float>(histograms[i].r[j]) / histograms.size();
            avgHistogram.g[j] += static_cast<float>(histograms[i].g[j]) / histograms.size();
            avgHistogram.b[j] += static_cast<float>(histograms[i].b[j]) / histograms.size();
        }
    }

    int bestFrame = -1;
    float minRMSE = FLT_MAX;

    for (size_t i = 0 ; i < histograms.size() ; ++i)
    {
        // calculate root mean squared error

        float rmse = 0.0;

        for (int j = 0 ; j < 255 ; ++j)
        {
            float error = qFabs(avgHistogram.r[j] - histograms[i].r[j]) +
                          qFabs(avgHistogram.g[j] - histograms[i].g[j]) +
                          qFabs(avgHistogram.b[j] - histograms[i].b[j]);
            rmse += (error * error) / 255;
        }

        rmse = qSqrt(rmse);

        if (rmse < minRMSE)
        {
            minRMSE   = rmse;
            bestFrame = i;
        }
    }
/*
    qCDebug(DIGIKAM_GENERAL_LOG) << "Best frame was: "
                                 << bestFrame
                                 << "(RMSE: "
                                 << minRMSE
                                 << ")" << Qt::endl;
*/
    return bestFrame;
}

} // namespace Digikam