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