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