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