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