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();
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()
81 m_dar = producer->profile()->dar();
82 m_ratio = (double) producer->profile()->width() / producer->profile()->height();
87 void KThumb::clearProducer()
92 bool KThumb::hasProducer() const
94 return m_producer != NULL;
97 void KThumb::updateThumbUrl(const QString &hash)
99 m_thumbFile = m_clipManager->projectFolder() + "/thumbs/" + hash + ".thumb";
102 void KThumb::updateClipUrl(KUrl url, const QString &hash)
106 //m_producer->set("resource", url.path().toUtf8().constData());
107 m_thumbFile = m_clipManager->projectFolder() + "/thumbs/" + hash + ".thumb";
111 QPixmap KThumb::getImage(KUrl url, int width, int height)
113 if (url.isEmpty()) return QPixmap();
114 return getImage(url, 0, width, height);
117 void KThumb::extractImage(int frame, int frame2)
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);
125 void KThumb::doGetThumbs()
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);
131 while (!m_requestedThumbs.isEmpty()) {
132 int frame = m_requestedThumbs.takeFirst();
134 QImage img = getFrame(m_producer, frame, swidth, dwidth, theight);
135 emit thumbReady(frame, img);
140 QPixmap KThumb::extractImage(int frame, int width, int height)
142 return QPixmap::fromImage(getFrame(m_producer, frame, (int) (height * m_ratio + 0.5), width, height));
146 QPixmap KThumb::getImage(KUrl url, int frame, int width, int height)
148 Mlt::Profile profile(KdenliveSettings::current_profile().toUtf8().constData());
149 QPixmap pix(width, height);
150 if (url.isEmpty()) return pix;
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));
162 QImage KThumb::getFrame(Mlt::Producer *producer, int framepos, int frameWidth, int displayWidth, int height)
164 QImage p(displayWidth, height, QImage::Format_ARGB32_Premultiplied);
165 if (producer == NULL || !producer->is_valid()) {
170 if (producer->is_blank()) {
175 producer->seek(framepos);
176 Mlt::Frame *frame = producer->get_frame();
177 p = getFrame(frame, frameWidth, displayWidth, height);
184 QImage KThumb::getFrame(Mlt::Frame *frame, int frameWidth, int displayWidth, int height)
186 QImage p(displayWidth, height, QImage::Format_ARGB32_Premultiplied);
187 if (frame == NULL || !frame->is_valid()) {
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();
203 image = image.scaled(displayWidth, height, Qt::IgnoreAspectRatio).rgbSwapped();
205 QPainter painter(&p);
206 painter.fillRect(p.rect(), Qt::black);
207 painter.setCompositionMode(QPainter::CompositionMode_SourceOver);
208 painter.drawImage(p.rect(), image);
216 uint KThumb::imageVariance(QImage image )
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
234 // Second Step: calculate delta (average?)
235 for (uint i=0; i<STEPS; i++)
237 #if QT_VERSION >= 0x040700
238 int curdelta=abs(int(avg - pivot.at(i)));
240 int curdelta=abs(int(avg - pivot[i]));
248 void KThumb::getImage(KUrl url, int frame, int width, int height)
250 if (url.isEmpty()) return;
251 QPixmap image(width, height);
252 Mlt::Producer m_producer(url.path().toUtf8().constData());
253 image.fill(Qt::black);
255 if (m_producer.is_blank()) {
256 emit thumbReady(frame, image);
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;
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);
272 if (m_frame) delete m_frame;
273 emit thumbReady(frame, image);
276 void KThumb::getThumbs(KUrl url, int startframe, int endframe, int width, int height)
278 if (url.isEmpty()) return;
279 QPixmap image(width, height);
280 Mlt::Producer m_producer(url.path().toUtf8().constData());
281 image.fill(Qt::black);
283 if (m_producer.is_blank()) {
284 emit thumbReady(startframe, image);
285 emit thumbReady(endframe, image);
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;
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);
302 if (m_frame) delete m_frame;
303 emit thumbReady(startframe, image);
305 image.fill(Qt::black);
306 m_producer.seek(endframe);
307 m_frame = m_producer.get_frame();
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);
314 if (m_frame) delete m_frame;
315 emit thumbReady(endframe, image);
318 void KThumb::stopAudioThumbs()
320 if (m_audioThumbProducer.isRunning()) {
321 m_stopAudioThumbs = true;
322 m_audioThumbProducer.waitForFinished();
323 slotAudioThumbOver();
327 void KThumb::removeAudioThumb()
329 if (m_thumbFile.isEmpty()) return;
331 QFile f(m_thumbFile);
335 void KThumb::getAudioThumbs(int channel, double frame, double frameLength, int arrayWidth)
338 slotAudioThumbOver();
341 if (m_audioThumbProducer.isRunning()) {
345 QMap <int, QMap <int, QByteArray> > storeIn;
346 //FIXME: Hardcoded!!!
348 m_channels = channel;
350 QFile f(m_thumbFile);
351 if (f.open(QIODevice::ReadOnly)) {
352 const QByteArray channelarray = f.readAll();
354 if (channelarray.size() != arrayWidth*(frame + frameLength)*m_channels) {
355 kDebug() << "--- BROKEN THUMB FOR: " << m_url.fileName() << " ---------------------- " << endl;
357 slotAudioThumbOver();
361 kDebug() << "reading audio thumbs from file";
363 int h1 = arrayWidth * m_channels;
364 int h2 = (int) frame * h1;
366 for (int z = (int) frame; z < (int)(frame + frameLength); z++) {
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);
374 storeIn[z][c] = m_array;
378 emit audioThumbReady(storeIn);
379 slotAudioThumbOver();
381 if (m_audioThumbProducer.isRunning()) return;
382 m_audioThumbFile.setFileName(m_thumbFile);
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 << " ................................";
393 void KThumb::slotCreateAudioThumbs()
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();
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);
408 if (KdenliveSettings::normaliseaudiothumbs()) {
409 Mlt::Filter m_convert(prof, "volume");
410 m_convert.set("gain", "normalise");
411 producer.attach(m_convert);
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);
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));
432 for (int c = 0; c < m_channels; c++) {
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 ;
438 m_audioThumbFile.write(m_array);
442 m_audioThumbFile.write(QByteArray(m_arrayWidth, '\x00'));
446 m_audioThumbFile.close();
447 if (m_stopAudioThumbs) {
448 m_audioThumbFile.remove();
450 slotAudioThumbOver();
454 void KThumb::slotAudioThumbOver()
456 m_clipManager->setThumbsProgress(i18n("Creating thumbnail for %1", m_url.fileName()), -1);
457 m_clipManager->endAudioThumbsGeneration(m_id);
460 void KThumb::askForAudioThumbs(const QString &id)
462 m_clipManager->askForAudioThumb(id);
465 #if KDE_IS_VERSION(4,5,0)
466 void KThumb::queryIntraThumbs(QList <int> missingFrames)
468 foreach (int i, missingFrames) {
469 if (!m_intraFramesQueue.contains(i)) m_intraFramesQueue.append(i);
471 qSort(m_intraFramesQueue);
472 if (!m_intra.isRunning()) m_intra = QtConcurrent::run(this, &KThumb::slotGetIntraThumbs);
475 void KThumb::slotGetIntraThumbs()
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;
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))) {
489 else kDebug()<<"// INSERT FAILD FOR: "<<pos;
491 m_intraFramesQueue.removeAll(pos);
493 if (addedThumbs) emit thumbsCached();
496 QImage KThumb::findCachedThumb(const QString path)
499 m_clipManager->pixmapCache->findImage(path, &img);
504 #include "kthumb.moc"