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