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