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