]> git.sesse.net Git - kdenlive/blob - src/kthumb.cpp
kthumb.cpp: check for division by zero
[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) :
44     QObject(parent),
45     m_url(url),
46     m_thumbFile(),
47     m_dar(1),
48     m_ratio(1),
49     m_producer(NULL),
50     m_clipManager(clipManager),
51     m_id(id)
52 {
53     m_thumbFile = clipManager->projectFolder() + "/thumbs/" + hash + ".thumb";
54 }
55
56 KThumb::~KThumb()
57 {
58     if (m_producer) m_clipManager->stopThumbs(m_id);
59     m_producer = NULL;
60     m_intraFramesQueue.clear();
61     m_intra.waitForFinished();
62 }
63
64 void KThumb::setProducer(Mlt::Producer *producer)
65 {
66     if (m_producer) m_clipManager->stopThumbs(m_id);
67     m_intraFramesQueue.clear();
68     m_intra.waitForFinished();
69     m_mutex.lock();
70     m_producer = producer;
71     // FIXME: the profile() call leaks an object, but trying to free
72     // it leads to a double-free in Profile::~Profile()
73     if (producer) {
74         Mlt::Profile *profile = producer->profile();
75         m_dar = profile->dar();
76         m_ratio = (double) profile->width() / profile->height();
77     }
78     m_mutex.unlock();
79 }
80
81 void KThumb::clearProducer()
82 {
83     if (m_producer) setProducer(NULL);
84 }
85
86 bool KThumb::hasProducer() const
87 {
88     return m_producer != NULL;
89 }
90
91 void KThumb::updateThumbUrl(const QString &hash)
92 {
93     m_thumbFile = m_clipManager->projectFolder() + "/thumbs/" + hash + ".thumb";
94 }
95
96 void KThumb::updateClipUrl(KUrl url, const QString &hash)
97 {
98     m_url = url;
99     m_thumbFile = m_clipManager->projectFolder() + "/thumbs/" + hash + ".thumb";
100 }
101
102 //static
103 QPixmap KThumb::getImage(KUrl url, int width, int height)
104 {
105     if (url.isEmpty()) return QPixmap();
106     return getImage(url, 0, width, height);
107 }
108
109 void KThumb::extractImage(QList <int>frames)
110 {
111     if (!KdenliveSettings::videothumbnails() || m_producer == NULL) return;
112     m_clipManager->requestThumbs(m_id, frames);
113 }
114
115
116 void KThumb::getThumb(int frame)
117 {
118     const int theight = KdenliveSettings::trackheight();
119     const int swidth = (int)(theight * m_ratio + 0.5);
120     const int dwidth = (int)(theight * m_dar + 0.5);
121
122     QImage img = getProducerFrame(frame, swidth, dwidth, theight);
123     emit thumbReady(frame, img);
124 }
125
126 QImage KThumb::extractImage(int frame, int width, int height)
127 {
128     if (m_producer == NULL) {
129         QImage img(width, height, QImage::Format_ARGB32_Premultiplied);
130         img.fill(Qt::black);
131         return img;
132     }
133     return getProducerFrame(frame, (int) (height * m_ratio + 0.5), width, height);
134 }
135
136 //static
137 QPixmap KThumb::getImage(KUrl url, int frame, int width, int height)
138 {
139     Mlt::Profile profile(KdenliveSettings::current_profile().toUtf8().constData());
140     QPixmap pix(width, height);
141     if (url.isEmpty()) return pix;
142
143     //"<mlt><playlist><producer resource=\"" + url.path() + "\" /></playlist></mlt>");
144     //Mlt::Producer producer(profile, "xml-string", tmp);
145     Mlt::Producer *producer = new Mlt::Producer(profile, url.path().toUtf8().constData());
146     double swidth = (double) profile.width() / profile.height();
147     pix = QPixmap::fromImage(getFrame(producer, frame, (int) (height * swidth + 0.5), width, height));
148     delete producer;
149     return pix;
150 }
151
152
153 QImage KThumb::getProducerFrame(int framepos, int frameWidth, int displayWidth, int height)
154 {
155     if (m_producer == NULL || !m_producer->is_valid()) {
156         QImage p(displayWidth, height, QImage::Format_ARGB32_Premultiplied);
157         p.fill(QColor(Qt::red).rgb());
158         return p;
159     }
160     if (m_producer->is_blank()) {
161         QImage p(displayWidth, height, QImage::Format_ARGB32_Premultiplied);
162         p.fill(QColor(Qt::black).rgb());
163         return p;
164     }
165     m_mutex.lock();
166     m_producer->seek(framepos);
167     Mlt::Frame *frame = m_producer->get_frame();
168     QImage p = getFrame(frame, frameWidth, displayWidth, height);
169     delete frame;
170     m_mutex.unlock();
171     return p;
172 }
173
174 //static
175 QImage KThumb::getFrame(Mlt::Producer *producer, int framepos, int frameWidth, int displayWidth, int height)
176 {
177     if (producer == NULL || !producer->is_valid()) {
178         QImage p(displayWidth, height, QImage::Format_ARGB32_Premultiplied);
179         p.fill(QColor(Qt::red).rgb());
180         return p;
181     }
182     if (producer->is_blank()) {
183         QImage p(displayWidth, height, QImage::Format_ARGB32_Premultiplied);
184         p.fill(QColor(Qt::black).rgb());
185         return p;
186     }
187
188     producer->seek(framepos);
189     Mlt::Frame *frame = producer->get_frame();
190     QImage p = getFrame(frame, frameWidth, displayWidth, height);
191     delete frame;
192     return p;
193 }
194
195
196 //static
197 QImage KThumb::getFrame(Mlt::Frame *frame, int frameWidth, int displayWidth, int height)
198 {
199     QImage p(displayWidth, height, QImage::Format_ARGB32_Premultiplied);
200     if (frame == NULL || !frame->is_valid()) {
201         p.fill(QColor(Qt::red).rgb());
202         return p;
203     }
204
205     int ow = frameWidth;
206     int oh = height;
207     mlt_image_format format = mlt_image_rgb24a;
208
209     const uchar* imagedata = frame->get_image(format, ow, oh);
210     QImage image(ow, oh, QImage::Format_ARGB32_Premultiplied);
211     memcpy(image.bits(), imagedata, ow * oh * 4);//.byteCount());
212     
213     //const uchar* imagedata = frame->get_image(format, ow, oh);
214     //QImage image(imagedata, ow, oh, QImage::Format_ARGB32_Premultiplied);
215     
216     if (!image.isNull()) {
217         if (ow > (2 * displayWidth)) {
218             // there was a scaling problem, do it manually
219             image = image.scaled(displayWidth, height).rgbSwapped();
220         } else {
221             image = image.scaled(displayWidth, height, Qt::IgnoreAspectRatio).rgbSwapped();
222         }
223         p.fill(QColor(Qt::black).rgb());
224         QPainter painter(&p);
225         painter.drawImage(p.rect(), image);
226         painter.end();
227     } else
228         p.fill(QColor(Qt::red).rgb());
229     return p;
230 }
231
232 //static
233 uint KThumb::imageVariance(QImage image )
234 {
235     uint delta = 0;
236     uint avg = 0;
237     uint bytes = image.numBytes();
238     uint STEPS = bytes/2;
239     QVarLengthArray<uchar> pivot(STEPS);
240     const uchar *bits=image.bits();
241     // First pass: get pivots and taking average
242     for( uint i=0; i<STEPS ; i++ ){
243         pivot[i] = bits[2 * i];
244 #if QT_VERSION >= 0x040700
245         avg+=pivot.at(i);
246 #else
247         avg+=pivot[i];
248 #endif
249     }
250     if (STEPS)
251         avg=avg/STEPS;
252     // Second Step: calculate delta (average?)
253     for (uint i=0; i<STEPS; i++)
254     {
255 #if QT_VERSION >= 0x040700
256         int curdelta=abs(int(avg - pivot.at(i)));
257 #else
258         int curdelta=abs(int(avg - pivot[i]));
259 #endif
260         delta+=curdelta;
261     }
262     if (STEPS)
263         return delta/STEPS;
264     else
265         return 0;
266 }
267
268 /*
269 void KThumb::getImage(KUrl url, int frame, int width, int height)
270 {
271     if (url.isEmpty()) return;
272     QPixmap image(width, height);
273     Mlt::Producer m_producer(url.path().toUtf8().constData());
274     image.fill(Qt::black);
275
276     if (m_producer.is_blank()) {
277  emit thumbReady(frame, image);
278  return;
279     }
280     Mlt::Filter m_convert("avcolour_space");
281     m_convert.set("forced", mlt_image_rgb24a);
282     m_producer.attach(m_convert);
283     m_producer.seek(frame);
284     Mlt::Frame * m_frame = m_producer.get_frame();
285     mlt_image_format format = mlt_image_rgb24a;
286     width = width - 2;
287     height = height - 2;
288     if (m_frame && m_frame->is_valid()) {
289      uint8_t *thumb = m_frame->get_image(format, width, height);
290      QImage tmpimage(thumb, width, height, 32, NULL, 0, QImage::IgnoreEndian);
291      if (!tmpimage.isNull()) bitBlt(&image, 1, 1, &tmpimage, 0, 0, width + 2, height + 2);
292     }
293     if (m_frame) delete m_frame;
294     emit thumbReady(frame, image);
295 }
296
297 void KThumb::getThumbs(KUrl url, int startframe, int endframe, int width, int height)
298 {
299     if (url.isEmpty()) return;
300     QPixmap image(width, height);
301     Mlt::Producer m_producer(url.path().toUtf8().constData());
302     image.fill(Qt::black);
303
304     if (m_producer.is_blank()) {
305  emit thumbReady(startframe, image);
306  emit thumbReady(endframe, image);
307  return;
308     }
309     Mlt::Filter m_convert("avcolour_space");
310     m_convert.set("forced", mlt_image_rgb24a);
311     m_producer.attach(m_convert);
312     m_producer.seek(startframe);
313     Mlt::Frame * m_frame = m_producer.get_frame();
314     mlt_image_format format = mlt_image_rgb24a;
315     width = width - 2;
316     height = height - 2;
317
318     if (m_frame && m_frame->is_valid()) {
319      uint8_t *thumb = m_frame->get_image(format, width, height);
320      QImage tmpimage(thumb, width, height, 32, NULL, 0, QImage::IgnoreEndian);
321      if (!tmpimage.isNull()) bitBlt(&image, 1, 1, &tmpimage, 0, 0, width - 2, height - 2);
322     }
323     if (m_frame) delete m_frame;
324     emit thumbReady(startframe, image);
325
326     image.fill(Qt::black);
327     m_producer.seek(endframe);
328     m_frame = m_producer.get_frame();
329
330     if (m_frame && m_frame->is_valid()) {
331      uint8_t *thumb = m_frame->get_image(format, width, height);
332      QImage tmpimage(thumb, width, height, 32, NULL, 0, QImage::IgnoreEndian);
333      if (!tmpimage.isNull()) bitBlt(&image, 1, 1, &tmpimage, 0, 0, width - 2, height - 2);
334     }
335     if (m_frame) delete m_frame;
336     emit thumbReady(endframe, image);
337 }
338 */
339
340 void KThumb::slotCreateAudioThumbs()
341 {
342     m_clipManager->askForAudioThumb(m_id);
343 }
344
345 #if KDE_IS_VERSION(4,5,0)
346 void KThumb::queryIntraThumbs(QList <int> missingFrames)
347 {
348     foreach (int i, missingFrames) {
349         if (!m_intraFramesQueue.contains(i)) m_intraFramesQueue.append(i);
350     }
351     qSort(m_intraFramesQueue);
352     if (!m_intra.isRunning()) {
353         m_intra = QtConcurrent::run(this, &KThumb::slotGetIntraThumbs);
354     }
355 }
356
357 void KThumb::slotGetIntraThumbs()
358 {
359     const int theight = KdenliveSettings::trackheight();
360     const int frameWidth = (int)(theight * m_ratio + 0.5);
361     const int displayWidth = (int)(theight * m_dar + 0.5);
362     QString path = m_url.path() + '_';
363     bool addedThumbs = false;
364
365     while (!m_intraFramesQueue.isEmpty()) {
366         int pos = m_intraFramesQueue.takeFirst();
367         if (!m_clipManager->pixmapCache->contains(path + QString::number(pos))) {
368             if (m_clipManager->pixmapCache->insertImage(path + QString::number(pos), getProducerFrame(pos, frameWidth, displayWidth, theight))) {
369                 addedThumbs = true;
370             }
371             else kDebug()<<"// INSERT FAILD FOR: "<<pos;
372         }
373         m_intraFramesQueue.removeAll(pos);
374     }
375     if (addedThumbs) emit thumbsCached();
376 }
377
378 QImage KThumb::findCachedThumb(const QString &path)
379 {
380     QImage img;
381     m_clipManager->pixmapCache->findImage(path, &img);
382     return img;
383 }
384 #endif
385
386 #include "kthumb.moc"
387