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