]> git.sesse.net Git - kdenlive/blob - src/kthumb.cpp
Another attempt to secure thumbs creation
[kdenlive] / src / kthumb.cpp
1 /***************************************************************************
2                         krender.cpp  -  description
3                            -------------------
4   begin                : Fri Nov 22 2002
5   copyright            : (C) 2002 by Jason Wood
6   email                : jasonwood@blueyonder.co.uk
7   copyright            : (C) 2005 Lcio Fl�io Corr�
8   email                : lucio.correa@gmail.com
9   copyright            : (C) Marco Gittler
10   email                : g.marco@freenet.de
11
12 ***************************************************************************/
13
14 /***************************************************************************
15  *                                                                         *
16  *   This program is free software; you can redistribute it and/or modify  *
17  *   it under the terms of the GNU General Public License as published by  *
18  *   the Free Software Foundation; either version 2 of the License, or     *
19  *   (at your option) any later version.                                   *
20  *                                                                         *
21  ***************************************************************************/
22
23 #include "kthumb.h"
24 #include "clipmanager.h"
25 #include "renderer.h"
26 #include "kdenlivesettings.h"
27
28 #include <mlt++/Mlt.h>
29
30 #include <kio/netaccess.h>
31 #include <kdebug.h>
32 #include <klocale.h>
33 #include <kfileitem.h>
34 #include <kmessagebox.h>
35 #include <KStandardDirs>
36
37 #include <qxml.h>
38 #include <QImage>
39 #include <QApplication>
40 #include <QtConcurrentRun>
41 #include <QVarLengthArray>
42
43 KThumb::KThumb(ClipManager *clipManager, KUrl url, const QString &id, const QString &hash, QObject * parent, const char */*name*/) :
44     QObject(parent),
45     m_audioThumbProducer(),
46     m_url(url),
47     m_thumbFile(),
48     m_dar(1),
49     m_ratio(1),
50     m_producer(NULL),
51     m_clipManager(clipManager),
52     m_id(id),
53     m_stopAudioThumbs(false)
54 {
55     m_thumbFile = clipManager->projectFolder() + "/thumbs/" + hash + ".thumb";
56 }
57
58 KThumb::~KThumb()
59 {
60     m_requestedThumbs.clear();
61     m_intraFramesQueue.clear();
62     if (m_audioThumbProducer.isRunning()) {
63         m_stopAudioThumbs = true;
64         m_audioThumbProducer.waitForFinished();
65         slotAudioThumbOver();
66     }
67     m_future.waitForFinished();
68     m_intra.waitForFinished();
69 }
70
71 void KThumb::setProducer(Mlt::Producer *producer)
72 {
73     m_requestedThumbs.clear();
74     m_intraFramesQueue.clear();
75     m_future.waitForFinished();
76     m_intra.waitForFinished();
77     m_mutex.lock();
78     m_producer = producer;
79     m_mutex.unlock();
80     // FIXME: the profile() call leaks an object, but trying to free
81     // it leads to a double-free in Profile::~Profile()
82     if (producer) {
83         m_dar = producer->profile()->dar();
84         m_ratio = (double) producer->profile()->width() / producer->profile()->height();
85     }
86         
87 }
88
89 void KThumb::clearProducer()
90 {
91     setProducer(NULL);
92 }
93
94 bool KThumb::hasProducer() const
95 {
96     return m_producer != NULL;
97 }
98
99 void KThumb::updateThumbUrl(const QString &hash)
100 {
101     m_thumbFile = m_clipManager->projectFolder() + "/thumbs/" + hash + ".thumb";
102 }
103
104 void KThumb::updateClipUrl(KUrl url, const QString &hash)
105 {
106     m_url = url;
107     //if (m_producer)
108         //m_producer->set("resource", url.path().toUtf8().constData());
109     m_thumbFile = m_clipManager->projectFolder() + "/thumbs/" + hash + ".thumb";
110 }
111
112 //static
113 QPixmap KThumb::getImage(KUrl url, int width, int height)
114 {
115     if (url.isEmpty()) return QPixmap();
116     return getImage(url, 0, width, height);
117 }
118
119 void KThumb::extractImage(int frame, int frame2)
120 {
121     if (!KdenliveSettings::videothumbnails() || m_producer == NULL) return;
122     if (frame != -1 && !m_requestedThumbs.contains(frame)) m_requestedThumbs.append(frame);
123     if (frame2 != -1 && !m_requestedThumbs.contains(frame2)) m_requestedThumbs.append(frame2);
124     if (!m_future.isRunning()) {
125         m_mutex.lock();
126         m_future = QtConcurrent::run(this, &KThumb::doGetThumbs);
127         m_mutex.unlock();
128     }
129 }
130
131 void KThumb::doGetThumbs()
132 {
133     const int theight = KdenliveSettings::trackheight();
134     const int swidth = (int)(theight * m_ratio + 0.5);
135     const int dwidth = (int)(theight * m_dar + 0.5);
136
137     while (!m_requestedThumbs.isEmpty()) {
138         int frame = m_requestedThumbs.takeFirst();
139         if (frame != -1) {
140             emit thumbReady(frame, getFrame(m_producer, frame, swidth, dwidth, theight));
141         }
142     }
143 }
144
145 QPixmap KThumb::extractImage(int frame, int width, int height)
146 {
147     m_mutex.lock();
148     QImage img = getFrame(m_producer, frame, (int) (height * m_ratio + 0.5), width, height);
149     m_mutex.unlock();
150     return QPixmap::fromImage(img);
151 }
152
153 //static
154 QPixmap KThumb::getImage(KUrl url, int frame, int width, int height)
155 {
156     Mlt::Profile profile(KdenliveSettings::current_profile().toUtf8().constData());
157     QPixmap pix(width, height);
158     if (url.isEmpty()) return pix;
159
160     //"<mlt><playlist><producer resource=\"" + url.path() + "\" /></playlist></mlt>");
161     //Mlt::Producer producer(profile, "xml-string", tmp);
162     Mlt::Producer *producer = new Mlt::Producer(profile, url.path().toUtf8().constData());
163     double swidth = (double) profile.width() / profile.height();
164     pix = QPixmap::fromImage(getFrame(producer, frame, (int) (height * swidth + 0.5), width, height));
165     delete producer;
166     return pix;
167 }
168
169 //static
170 QImage KThumb::getFrame(Mlt::Producer *producer, int framepos, int frameWidth, int displayWidth, int height)
171 {
172     QImage p(displayWidth, height, QImage::Format_ARGB32_Premultiplied);
173     if (producer == NULL || !producer->is_valid()) {
174         p.fill(Qt::red);
175         return p;
176     }
177
178     if (producer->is_blank()) {
179         p.fill(Qt::black);
180         return p;
181     }
182
183     producer->seek(framepos);
184     Mlt::Frame *frame = producer->get_frame();
185     p = getFrame(frame, frameWidth, displayWidth, height);
186     delete frame;
187     return p;
188 }
189
190
191 //static
192 QImage KThumb::getFrame(Mlt::Frame *frame, int frameWidth, int displayWidth, int height)
193 {
194     QImage p(displayWidth, height, QImage::Format_ARGB32_Premultiplied);
195     if (frame == NULL || !frame->is_valid()) {
196         p.fill(Qt::red);
197         return p;
198     }
199
200     int ow = frameWidth;
201     int oh = height;
202     mlt_image_format format = mlt_image_rgb24a;
203     uint8_t *data = frame->get_image(format, ow, oh, 0);
204     QImage image((uchar *)data, ow, oh, QImage::Format_ARGB32_Premultiplied);
205     if (!image.isNull()) {
206         if (ow > (2 * displayWidth)) {
207             // there was a scaling problem, do it manually
208             QImage scaled = image.scaled(displayWidth, height);
209             image = scaled.rgbSwapped();
210         } else {
211             image = image.scaled(displayWidth, height, Qt::IgnoreAspectRatio).rgbSwapped();
212         }
213         QPainter painter(&p);
214         painter.fillRect(p.rect(), Qt::black);
215         painter.setCompositionMode(QPainter::CompositionMode_SourceOver);
216         painter.drawImage(p.rect(), image);
217         painter.end();
218     } else
219         p.fill(Qt::red);
220     return p;
221 }
222
223 //static
224 uint KThumb::imageVariance(QImage image )
225 {
226     uint delta = 0;
227     uint avg = 0;
228     uint bytes = image.numBytes();
229     uint STEPS = bytes/2;
230     QVarLengthArray<uchar> pivot(STEPS);
231     const uchar *bits=image.bits();
232     // First pass: get pivots and taking average
233     for( uint i=0; i<STEPS ; i++ ){
234         pivot[i] = bits[2 * i];
235 #if QT_VERSION >= 0x040700
236         avg+=pivot.at(i);
237 #else
238         avg+=pivot[i];
239 #endif
240     }
241     avg=avg/STEPS;
242     // Second Step: calculate delta (average?)
243     for (uint i=0; i<STEPS; i++)
244     {
245 #if QT_VERSION >= 0x040700
246         int curdelta=abs(int(avg - pivot.at(i)));
247 #else
248         int curdelta=abs(int(avg - pivot[i]));
249 #endif
250         delta+=curdelta;
251     }
252     return delta/STEPS;
253 }
254
255 /*
256 void KThumb::getImage(KUrl url, int frame, int width, int height)
257 {
258     if (url.isEmpty()) return;
259     QPixmap image(width, height);
260     Mlt::Producer m_producer(url.path().toUtf8().constData());
261     image.fill(Qt::black);
262
263     if (m_producer.is_blank()) {
264  emit thumbReady(frame, image);
265  return;
266     }
267     Mlt::Filter m_convert("avcolour_space");
268     m_convert.set("forced", mlt_image_rgb24a);
269     m_producer.attach(m_convert);
270     m_producer.seek(frame);
271     Mlt::Frame * m_frame = m_producer.get_frame();
272     mlt_image_format format = mlt_image_rgb24a;
273     width = width - 2;
274     height = height - 2;
275     if (m_frame && m_frame->is_valid()) {
276      uint8_t *thumb = m_frame->get_image(format, width, height);
277      QImage tmpimage(thumb, width, height, 32, NULL, 0, QImage::IgnoreEndian);
278      if (!tmpimage.isNull()) bitBlt(&image, 1, 1, &tmpimage, 0, 0, width + 2, height + 2);
279     }
280     if (m_frame) delete m_frame;
281     emit thumbReady(frame, image);
282 }
283
284 void KThumb::getThumbs(KUrl url, int startframe, int endframe, int width, int height)
285 {
286     if (url.isEmpty()) return;
287     QPixmap image(width, height);
288     Mlt::Producer m_producer(url.path().toUtf8().constData());
289     image.fill(Qt::black);
290
291     if (m_producer.is_blank()) {
292  emit thumbReady(startframe, image);
293  emit thumbReady(endframe, image);
294  return;
295     }
296     Mlt::Filter m_convert("avcolour_space");
297     m_convert.set("forced", mlt_image_rgb24a);
298     m_producer.attach(m_convert);
299     m_producer.seek(startframe);
300     Mlt::Frame * m_frame = m_producer.get_frame();
301     mlt_image_format format = mlt_image_rgb24a;
302     width = width - 2;
303     height = height - 2;
304
305     if (m_frame && m_frame->is_valid()) {
306      uint8_t *thumb = m_frame->get_image(format, width, height);
307      QImage tmpimage(thumb, width, height, 32, NULL, 0, QImage::IgnoreEndian);
308      if (!tmpimage.isNull()) bitBlt(&image, 1, 1, &tmpimage, 0, 0, width - 2, height - 2);
309     }
310     if (m_frame) delete m_frame;
311     emit thumbReady(startframe, image);
312
313     image.fill(Qt::black);
314     m_producer.seek(endframe);
315     m_frame = m_producer.get_frame();
316
317     if (m_frame && m_frame->is_valid()) {
318      uint8_t *thumb = m_frame->get_image(format, width, height);
319      QImage tmpimage(thumb, width, height, 32, NULL, 0, QImage::IgnoreEndian);
320      if (!tmpimage.isNull()) bitBlt(&image, 1, 1, &tmpimage, 0, 0, width - 2, height - 2);
321     }
322     if (m_frame) delete m_frame;
323     emit thumbReady(endframe, image);
324 }
325 */
326 void KThumb::stopAudioThumbs()
327 {
328     if (m_audioThumbProducer.isRunning()) {
329         m_stopAudioThumbs = true;
330         m_audioThumbProducer.waitForFinished();
331         slotAudioThumbOver();
332     }
333 }
334
335 void KThumb::removeAudioThumb()
336 {
337     if (m_thumbFile.isEmpty()) return;
338     stopAudioThumbs();
339     QFile f(m_thumbFile);
340     f.remove();
341 }
342
343 void KThumb::getAudioThumbs(int channel, double frame, double frameLength, int arrayWidth)
344 {
345     if (channel == 0) {
346         slotAudioThumbOver();
347         return;
348     }
349     if (m_audioThumbProducer.isRunning()) {
350         return;
351     }
352
353     QMap <int, QMap <int, QByteArray> > storeIn;
354     //FIXME: Hardcoded!!!
355     m_frequency = 48000;
356     m_channels = channel;
357
358     QFile f(m_thumbFile);
359     if (f.open(QIODevice::ReadOnly)) {
360         const QByteArray channelarray = f.readAll();
361         f.close();
362         if (channelarray.size() != arrayWidth*(frame + frameLength)*m_channels) {
363             kDebug() << "--- BROKEN THUMB FOR: " << m_url.fileName() << " ---------------------- " << endl;
364             f.remove();
365             slotAudioThumbOver();
366             return;
367         }
368
369         kDebug() << "reading audio thumbs from file";
370
371         int h1 = arrayWidth * m_channels;
372         int h2 = (int) frame * h1;
373         int h3;
374         for (int z = (int) frame; z < (int)(frame + frameLength); z++) {
375             h3 = 0;
376             for (int c = 0; c < m_channels; c++) {
377                 QByteArray m_array(arrayWidth, '\x00');
378                 for (int i = 0; i < arrayWidth; i++) {
379                     m_array[i] = channelarray.at(h2 + h3 + i);
380                 }
381                 h3 += arrayWidth;
382                 storeIn[z][c] = m_array;
383             }
384             h2 += h1;
385         }
386         emit audioThumbReady(storeIn);
387         slotAudioThumbOver();
388     } else {
389         if (m_audioThumbProducer.isRunning()) return;
390         m_audioThumbFile.setFileName(m_thumbFile);
391         m_frame = frame;
392         m_frameLength = frameLength;
393         m_arrayWidth = arrayWidth;
394         m_audioThumbProducer = QtConcurrent::run(this, &KThumb::slotCreateAudioThumbs);
395         /*m_audioThumbProducer.init(m_url, m_thumbFile, frame, frameLength, m_frequency, m_channels, arrayWidth);
396         m_audioThumbProducer.start(QThread::LowestPriority);*/
397         // kDebug() << "STARTING GENERATE THMB FOR: " <<m_id<<", URL: "<< m_url << " ................................";
398     }
399 }
400
401 void KThumb::slotCreateAudioThumbs()
402 {
403     Mlt::Profile prof((char*) KdenliveSettings::current_profile().toUtf8().data());
404     Mlt::Producer producer(prof, m_url.path().toUtf8().data());
405     if (!producer.is_valid()) {
406         kDebug() << "++++++++  INVALID CLIP: " << m_url.path();
407         return;
408     }
409     if (!m_audioThumbFile.open(QIODevice::WriteOnly)) {
410         kDebug() << "++++++++  ERROR WRITING TO FILE: " << m_audioThumbFile.fileName();
411         kDebug() << "++++++++  DISABLING AUDIO THUMBS";
412         KdenliveSettings::setAudiothumbnails(false);
413         return;
414     }
415
416     if (KdenliveSettings::normaliseaudiothumbs()) {
417         Mlt::Filter m_convert(prof, "volume");
418         m_convert.set("gain", "normalise");
419         producer.attach(m_convert);
420     }
421
422     int last_val = 0;
423     int val = 0;
424     //kDebug() << "for " << m_frame << " " << m_frameLength << " " << m_producer.is_valid();
425     for (int z = (int) m_frame; z < (int)(m_frame + m_frameLength) && producer.is_valid(); z++) {
426         if (m_stopAudioThumbs) break;
427         val = (int)((z - m_frame) / (m_frame + m_frameLength) * 100.0);
428         if (last_val != val && val > 1) {
429             m_clipManager->setThumbsProgress(i18n("Creating thumbnail for %1", m_url.fileName()), val);
430             last_val = val;
431         }
432         producer.seek(z);
433         Mlt::Frame *mlt_frame = producer.get_frame();
434         if (mlt_frame && mlt_frame->is_valid()) {
435             double m_framesPerSecond = mlt_producer_get_fps(producer.get_producer());
436             int m_samples = mlt_sample_calculator(m_framesPerSecond, m_frequency, mlt_frame_get_position(mlt_frame->get_frame()));
437             mlt_audio_format m_audioFormat = mlt_audio_pcm;
438             qint16* m_pcm = static_cast<qint16*>(mlt_frame->get_audio(m_audioFormat, m_frequency, m_channels, m_samples));
439
440             for (int c = 0; c < m_channels; c++) {
441                 QByteArray m_array;
442                 m_array.resize(m_arrayWidth);
443                 for (int i = 0; i < m_array.size(); i++) {
444                     m_array[i] = ((*(m_pcm + c + i * m_samples / m_array.size())) >> 9) + 127 / 2 ;
445                 }
446                 m_audioThumbFile.write(m_array);
447
448             }
449         } else {
450             m_audioThumbFile.write(QByteArray(m_arrayWidth, '\x00'));
451         }
452         delete mlt_frame;
453     }
454     m_audioThumbFile.close();
455     if (m_stopAudioThumbs) {
456         m_audioThumbFile.remove();
457     } else {
458         slotAudioThumbOver();
459     }
460 }
461
462 void KThumb::slotAudioThumbOver()
463 {
464     m_clipManager->setThumbsProgress(i18n("Creating thumbnail for %1", m_url.fileName()), -1);
465     m_clipManager->endAudioThumbsGeneration(m_id);
466 }
467
468 void KThumb::askForAudioThumbs(const QString &id)
469 {
470     m_clipManager->askForAudioThumb(id);
471 }
472
473 #if KDE_IS_VERSION(4,5,0)
474 void KThumb::queryIntraThumbs(QList <int> missingFrames)
475 {
476     foreach (int i, missingFrames) {
477         if (!m_intraFramesQueue.contains(i)) m_intraFramesQueue.append(i);
478     }
479     qSort(m_intraFramesQueue);
480     if (!m_intra.isRunning()) {
481         m_mutex.lock();
482         m_intra = QtConcurrent::run(this, &KThumb::slotGetIntraThumbs);
483         m_mutex.unlock();
484     }
485 }
486
487 void KThumb::slotGetIntraThumbs()
488 {
489     const int theight = KdenliveSettings::trackheight();
490     const int frameWidth = (int)(theight * m_ratio + 0.5);
491     const int displayWidth = (int)(theight * m_dar + 0.5);
492     QString path = m_url.path() + "_";
493     bool addedThumbs = false;
494
495     while (!m_intraFramesQueue.isEmpty()) {
496         int pos = m_intraFramesQueue.takeFirst();
497         if (!m_clipManager->pixmapCache->contains(path + QString::number(pos))) {
498             if (m_clipManager->pixmapCache->insertImage(path + QString::number(pos), getFrame(m_producer, pos, frameWidth, displayWidth, theight))) {
499                 addedThumbs = true;
500             }
501             else kDebug()<<"// INSERT FAILD FOR: "<<pos;
502         }
503         m_intraFramesQueue.removeAll(pos);
504     }
505     if (addedThumbs) emit thumbsCached();
506 }
507
508 QImage KThumb::findCachedThumb(const QString path)
509 {
510     QImage img;
511     m_clipManager->pixmapCache->findImage(path, &img);
512     return img;
513 }
514 #endif
515
516 #include "kthumb.moc"
517