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