1 /***************************************************************************
2 krender.cpp - description
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
12 ***************************************************************************/
14 /***************************************************************************
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. *
21 ***************************************************************************/
24 #include "clipmanager.h"
26 #include "kdenlivesettings.h"
28 #include <mlt++/Mlt.h>
30 #include <kio/netaccess.h>
33 #include <kfileitem.h>
34 #include <kmessagebox.h>
35 #include <KStandardDirs>
39 #include <QApplication>
40 #include <QtConcurrentRun>
41 #include <QVarLengthArray>
43 KThumb::KThumb(ClipManager *clipManager, KUrl url, const QString &id, const QString &hash, QObject * parent, const char */*name*/) :
45 m_audioThumbProducer(),
51 m_clipManager(clipManager),
53 m_stopAudioThumbs(false)
55 m_thumbFile = clipManager->projectFolder() + "/thumbs/" + hash + ".thumb";
60 m_requestedThumbs.clear();
61 m_intraFramesQueue.clear();
62 if (m_audioThumbProducer.isRunning()) {
63 m_stopAudioThumbs = true;
64 m_audioThumbProducer.waitForFinished();
67 m_future.waitForFinished();
68 m_intra.waitForFinished();
71 void KThumb::setProducer(Mlt::Producer *producer)
73 m_requestedThumbs.clear();
74 m_intraFramesQueue.clear();
75 m_future.waitForFinished();
76 m_intra.waitForFinished();
78 m_producer = producer;
80 // FIXME: the profile() call leaks an object, but trying to free
81 // it leads to a double-free in Profile::~Profile()
83 m_dar = producer->profile()->dar();
84 m_ratio = (double) producer->profile()->width() / producer->profile()->height();
89 void KThumb::clearProducer()
94 bool KThumb::hasProducer() const
96 return m_producer != NULL;
99 void KThumb::updateThumbUrl(const QString &hash)
101 m_thumbFile = m_clipManager->projectFolder() + "/thumbs/" + hash + ".thumb";
104 void KThumb::updateClipUrl(KUrl url, const QString &hash)
108 //m_producer->set("resource", url.path().toUtf8().constData());
109 m_thumbFile = m_clipManager->projectFolder() + "/thumbs/" + hash + ".thumb";
113 QPixmap KThumb::getImage(KUrl url, int width, int height)
115 if (url.isEmpty()) return QPixmap();
116 return getImage(url, 0, width, height);
119 void KThumb::extractImage(int frame, int frame2)
121 if (!KdenliveSettings::videothumbnails() || m_producer == NULL) return;
122 if (frame != -1 && !m_requestedThumbs.contains(frame)) m_requestedThumbs.append(frame);
123 if (frame2 != -1 && !m_requestedThumbs.contains(frame2)) m_requestedThumbs.append(frame2);
124 if (!m_future.isRunning()) m_future = QtConcurrent::run(this, &KThumb::doGetThumbs);
127 void KThumb::doGetThumbs()
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);
133 while (!m_requestedThumbs.isEmpty()) {
134 int frame = m_requestedThumbs.takeFirst();
137 QImage img = getFrame(m_producer, frame, swidth, dwidth, theight);
139 emit thumbReady(frame, img);
144 QPixmap KThumb::extractImage(int frame, int width, int height)
147 QImage img = getFrame(m_producer, frame, (int) (height * m_ratio + 0.5), width, height);
149 return QPixmap::fromImage(img);
153 QPixmap KThumb::getImage(KUrl url, int frame, int width, int height)
155 Mlt::Profile profile(KdenliveSettings::current_profile().toUtf8().constData());
156 QPixmap pix(width, height);
157 if (url.isEmpty()) return pix;
159 //"<mlt><playlist><producer resource=\"" + url.path() + "\" /></playlist></mlt>");
160 //Mlt::Producer producer(profile, "xml-string", tmp);
161 Mlt::Producer *producer = new Mlt::Producer(profile, url.path().toUtf8().constData());
162 double swidth = (double) profile.width() / profile.height();
163 pix = QPixmap::fromImage(getFrame(producer, frame, (int) (height * swidth + 0.5), width, height));
169 QImage KThumb::getFrame(Mlt::Producer *producer, int framepos, int frameWidth, int displayWidth, int height)
171 QImage p(displayWidth, height, QImage::Format_ARGB32_Premultiplied);
172 if (producer == NULL || !producer->is_valid()) {
177 if (producer->is_blank()) {
182 producer->seek(framepos);
183 Mlt::Frame *frame = producer->get_frame();
184 p = getFrame(frame, frameWidth, displayWidth, height);
191 QImage KThumb::getFrame(Mlt::Frame *frame, int frameWidth, int displayWidth, int height)
193 QImage p(displayWidth, height, QImage::Format_ARGB32_Premultiplied);
194 if (frame == NULL || !frame->is_valid()) {
201 mlt_image_format format = mlt_image_rgb24a;
202 uint8_t *data = frame->get_image(format, ow, oh, 0);
203 QImage image((uchar *)data, ow, oh, QImage::Format_ARGB32_Premultiplied);
204 if (!image.isNull()) {
205 if (ow > (2 * displayWidth)) {
206 // there was a scaling problem, do it manually
207 QImage scaled = image.scaled(displayWidth, height);
208 image = scaled.rgbSwapped();
210 image = image.scaled(displayWidth, height, Qt::IgnoreAspectRatio).rgbSwapped();
212 QPainter painter(&p);
213 painter.fillRect(p.rect(), Qt::black);
214 painter.setCompositionMode(QPainter::CompositionMode_SourceOver);
215 painter.drawImage(p.rect(), image);
223 uint KThumb::imageVariance(QImage image )
227 uint bytes = image.numBytes();
228 uint STEPS = bytes/2;
229 QVarLengthArray<uchar> pivot(STEPS);
230 const uchar *bits=image.bits();
231 // First pass: get pivots and taking average
232 for( uint i=0; i<STEPS ; i++ ){
233 pivot[i] = bits[2 * i];
234 #if QT_VERSION >= 0x040700
241 // Second Step: calculate delta (average?)
242 for (uint i=0; i<STEPS; i++)
244 #if QT_VERSION >= 0x040700
245 int curdelta=abs(int(avg - pivot.at(i)));
247 int curdelta=abs(int(avg - pivot[i]));
255 void KThumb::getImage(KUrl url, int frame, int width, int height)
257 if (url.isEmpty()) return;
258 QPixmap image(width, height);
259 Mlt::Producer m_producer(url.path().toUtf8().constData());
260 image.fill(Qt::black);
262 if (m_producer.is_blank()) {
263 emit thumbReady(frame, image);
266 Mlt::Filter m_convert("avcolour_space");
267 m_convert.set("forced", mlt_image_rgb24a);
268 m_producer.attach(m_convert);
269 m_producer.seek(frame);
270 Mlt::Frame * m_frame = m_producer.get_frame();
271 mlt_image_format format = mlt_image_rgb24a;
274 if (m_frame && m_frame->is_valid()) {
275 uint8_t *thumb = m_frame->get_image(format, width, height);
276 QImage tmpimage(thumb, width, height, 32, NULL, 0, QImage::IgnoreEndian);
277 if (!tmpimage.isNull()) bitBlt(&image, 1, 1, &tmpimage, 0, 0, width + 2, height + 2);
279 if (m_frame) delete m_frame;
280 emit thumbReady(frame, image);
283 void KThumb::getThumbs(KUrl url, int startframe, int endframe, int width, int height)
285 if (url.isEmpty()) return;
286 QPixmap image(width, height);
287 Mlt::Producer m_producer(url.path().toUtf8().constData());
288 image.fill(Qt::black);
290 if (m_producer.is_blank()) {
291 emit thumbReady(startframe, image);
292 emit thumbReady(endframe, image);
295 Mlt::Filter m_convert("avcolour_space");
296 m_convert.set("forced", mlt_image_rgb24a);
297 m_producer.attach(m_convert);
298 m_producer.seek(startframe);
299 Mlt::Frame * m_frame = m_producer.get_frame();
300 mlt_image_format format = mlt_image_rgb24a;
304 if (m_frame && m_frame->is_valid()) {
305 uint8_t *thumb = m_frame->get_image(format, width, height);
306 QImage tmpimage(thumb, width, height, 32, NULL, 0, QImage::IgnoreEndian);
307 if (!tmpimage.isNull()) bitBlt(&image, 1, 1, &tmpimage, 0, 0, width - 2, height - 2);
309 if (m_frame) delete m_frame;
310 emit thumbReady(startframe, image);
312 image.fill(Qt::black);
313 m_producer.seek(endframe);
314 m_frame = m_producer.get_frame();
316 if (m_frame && m_frame->is_valid()) {
317 uint8_t *thumb = m_frame->get_image(format, width, height);
318 QImage tmpimage(thumb, width, height, 32, NULL, 0, QImage::IgnoreEndian);
319 if (!tmpimage.isNull()) bitBlt(&image, 1, 1, &tmpimage, 0, 0, width - 2, height - 2);
321 if (m_frame) delete m_frame;
322 emit thumbReady(endframe, image);
325 void KThumb::stopAudioThumbs()
327 if (m_audioThumbProducer.isRunning()) {
328 m_stopAudioThumbs = true;
329 m_audioThumbProducer.waitForFinished();
330 slotAudioThumbOver();
334 void KThumb::removeAudioThumb()
336 if (m_thumbFile.isEmpty()) return;
338 QFile f(m_thumbFile);
342 void KThumb::getAudioThumbs(int channel, double frame, double frameLength, int arrayWidth)
345 slotAudioThumbOver();
348 if (m_audioThumbProducer.isRunning()) {
352 QMap <int, QMap <int, QByteArray> > storeIn;
353 //FIXME: Hardcoded!!!
355 m_channels = channel;
357 QFile f(m_thumbFile);
358 if (f.open(QIODevice::ReadOnly)) {
359 const QByteArray channelarray = f.readAll();
361 if (channelarray.size() != arrayWidth*(frame + frameLength)*m_channels) {
362 kDebug() << "--- BROKEN THUMB FOR: " << m_url.fileName() << " ---------------------- " << endl;
364 slotAudioThumbOver();
368 kDebug() << "reading audio thumbs from file";
370 int h1 = arrayWidth * m_channels;
371 int h2 = (int) frame * h1;
373 for (int z = (int) frame; z < (int)(frame + frameLength); z++) {
375 for (int c = 0; c < m_channels; c++) {
376 QByteArray m_array(arrayWidth, '\x00');
377 for (int i = 0; i < arrayWidth; i++) {
378 m_array[i] = channelarray.at(h2 + h3 + i);
381 storeIn[z][c] = m_array;
385 emit audioThumbReady(storeIn);
386 slotAudioThumbOver();
388 if (m_audioThumbProducer.isRunning()) return;
389 m_audioThumbFile.setFileName(m_thumbFile);
391 m_frameLength = frameLength;
392 m_arrayWidth = arrayWidth;
393 m_audioThumbProducer = QtConcurrent::run(this, &KThumb::slotCreateAudioThumbs);
394 /*m_audioThumbProducer.init(m_url, m_thumbFile, frame, frameLength, m_frequency, m_channels, arrayWidth);
395 m_audioThumbProducer.start(QThread::LowestPriority);*/
396 // kDebug() << "STARTING GENERATE THMB FOR: " <<m_id<<", URL: "<< m_url << " ................................";
400 void KThumb::slotCreateAudioThumbs()
402 Mlt::Profile prof((char*) KdenliveSettings::current_profile().toUtf8().data());
403 Mlt::Producer producer(prof, m_url.path().toUtf8().data());
404 if (!producer.is_valid()) {
405 kDebug() << "++++++++ INVALID CLIP: " << m_url.path();
408 if (!m_audioThumbFile.open(QIODevice::WriteOnly)) {
409 kDebug() << "++++++++ ERROR WRITING TO FILE: " << m_audioThumbFile.fileName();
410 kDebug() << "++++++++ DISABLING AUDIO THUMBS";
411 KdenliveSettings::setAudiothumbnails(false);
415 if (KdenliveSettings::normaliseaudiothumbs()) {
416 Mlt::Filter m_convert(prof, "volume");
417 m_convert.set("gain", "normalise");
418 producer.attach(m_convert);
423 //kDebug() << "for " << m_frame << " " << m_frameLength << " " << m_producer.is_valid();
424 for (int z = (int) m_frame; z < (int)(m_frame + m_frameLength) && producer.is_valid(); z++) {
425 if (m_stopAudioThumbs) break;
426 val = (int)((z - m_frame) / (m_frame + m_frameLength) * 100.0);
427 if (last_val != val && val > 1) {
428 m_clipManager->setThumbsProgress(i18n("Creating thumbnail for %1", m_url.fileName()), val);
432 Mlt::Frame *mlt_frame = producer.get_frame();
433 if (mlt_frame && mlt_frame->is_valid()) {
434 double m_framesPerSecond = mlt_producer_get_fps(producer.get_producer());
435 int m_samples = mlt_sample_calculator(m_framesPerSecond, m_frequency, mlt_frame_get_position(mlt_frame->get_frame()));
436 mlt_audio_format m_audioFormat = mlt_audio_pcm;
437 qint16* m_pcm = static_cast<qint16*>(mlt_frame->get_audio(m_audioFormat, m_frequency, m_channels, m_samples));
439 for (int c = 0; c < m_channels; c++) {
441 m_array.resize(m_arrayWidth);
442 for (int i = 0; i < m_array.size(); i++) {
443 m_array[i] = ((*(m_pcm + c + i * m_samples / m_array.size())) >> 9) + 127 / 2 ;
445 m_audioThumbFile.write(m_array);
449 m_audioThumbFile.write(QByteArray(m_arrayWidth, '\x00'));
453 m_audioThumbFile.close();
454 if (m_stopAudioThumbs) {
455 m_audioThumbFile.remove();
457 slotAudioThumbOver();
461 void KThumb::slotAudioThumbOver()
463 m_clipManager->setThumbsProgress(i18n("Creating thumbnail for %1", m_url.fileName()), -1);
464 m_clipManager->endAudioThumbsGeneration(m_id);
467 void KThumb::askForAudioThumbs(const QString &id)
469 m_clipManager->askForAudioThumb(id);
472 #if KDE_IS_VERSION(4,5,0)
473 void KThumb::queryIntraThumbs(QList <int> missingFrames)
475 foreach (int i, missingFrames) {
476 if (!m_intraFramesQueue.contains(i)) m_intraFramesQueue.append(i);
478 qSort(m_intraFramesQueue);
479 if (!m_intra.isRunning()) m_intra = QtConcurrent::run(this, &KThumb::slotGetIntraThumbs);
482 void KThumb::slotGetIntraThumbs()
484 const int theight = KdenliveSettings::trackheight();
485 const int frameWidth = (int)(theight * m_ratio + 0.5);
486 const int displayWidth = (int)(theight * m_dar + 0.5);
487 QString path = m_url.path() + "_";
488 bool addedThumbs = false;
490 while (!m_intraFramesQueue.isEmpty()) {
491 int pos = m_intraFramesQueue.takeFirst();
492 if (!m_clipManager->pixmapCache->contains(path + QString::number(pos))) {
494 if (m_clipManager->pixmapCache->insertImage(path + QString::number(pos), getFrame(m_producer, pos, frameWidth, displayWidth, theight))) {
497 else kDebug()<<"// INSERT FAILD FOR: "<<pos;
500 m_intraFramesQueue.removeAll(pos);
502 if (addedThumbs) emit thumbsCached();
505 QImage KThumb::findCachedThumb(const QString path)
508 m_clipManager->pixmapCache->findImage(path, &img);
513 #include "kthumb.moc"