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