]> git.sesse.net Git - kdenlive/blob - src/docclipbase.cpp
Make sure we only use one thread to create video thumbnails
[kdenlive] / src / docclipbase.cpp
1 /***************************************************************************
2  *                         DocClipBase.cpp  -  description                 *
3  *                           -------------------                           *
4  *   begin                : Fri Apr 12 2002                                *
5  *   Copyright (C) 2002 by Jason Wood (jasonwood@blueyonder.co.uk)         *
6  *   Copyright (C) 2007 by Jean-Baptiste Mardelle (jb@kdenlive.org)        *
7  *                                                                         *
8  *   This program is free software; you can redistribute it and/or modify  *
9  *   it under the terms of the GNU General Public License as published by  *
10  *   the Free Software Foundation; either version 2 of the License, or     *
11  *   (at your option) any later version.                                   *
12  *                                                                         *
13  *   This program is distributed in the hope that it will be useful,       *
14  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
15  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
16  *   GNU General Public License for more details.                          *
17  *                                                                         *
18  *   You should have received a copy of the GNU General Public License     *
19  *   along with this program; if not, write to the                         *
20  *   Free Software Foundation, Inc.,                                       *
21  *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA          *
22  ***************************************************************************/
23
24
25
26
27 #include "docclipbase.h"
28 #include "kdenlivesettings.h"
29 #include "kthumb.h"
30 #include "clipmanager.h"
31 #include "slideshowclip.h"
32
33 #include <KIO/NetAccess>
34 #include <KStandardDirs>
35 #include <KDebug>
36
37 #include <QCryptographicHash>
38 #include <QtConcurrentRun>
39
40 #include <cstdio>
41
42 DocClipBase::DocClipBase(ClipManager *clipManager, QDomElement xml, const QString &id) :
43         QObject(),
44         m_audioFrameCache(),
45         m_refcount(0),
46         m_baseTrackProducers(),
47         m_audioTrackProducers(),
48         m_videoOnlyProducer(NULL),
49         m_snapMarkers(QList < CommentedTime >()),
50         m_duration(),
51         m_audioTimer(NULL),
52         m_thumbProd(NULL),
53         m_audioThumbCreated(false),
54         m_id(id),
55         m_placeHolder(xml.hasAttribute("placeholder")),
56         m_properties()
57 {
58     int type = xml.attribute("type").toInt();
59     m_clipType = (CLIPTYPE) type;
60     if (m_placeHolder) xml.removeAttribute("placeholder");
61     QDomNamedNodeMap attributes = xml.attributes();
62     for (int i = 0; i < attributes.count(); i++) {
63         QString name = attributes.item(i).nodeName();
64         if (name.startsWith("meta.attr.")) {
65             m_metadata.insert(name.section('.', 2, 3), attributes.item(i).nodeValue());
66         } else m_properties.insert(name, attributes.item(i).nodeValue());
67     }
68
69     if (xml.hasAttribute("cutzones")) {
70         QStringList cuts = xml.attribute("cutzones").split(";", QString::SkipEmptyParts);
71         for (int i = 0; i < cuts.count(); i++) {
72             QString z = cuts.at(i);
73             addCutZone(z.section('-', 0, 0).toInt(), z.section('-', 1, 1).toInt(), z.section('-', 2, 2));
74         }
75     }
76
77     KUrl url = KUrl(xml.attribute("resource"));
78     if (!m_properties.contains("file_hash") && !url.isEmpty()) getFileHash(url.path());
79
80     if (xml.hasAttribute("duration")) {
81         setDuration(GenTime(xml.attribute("duration").toInt(), KdenliveSettings::project_fps()));
82     } else {
83         int out = xml.attribute("out").toInt();
84         int in = xml.attribute("in").toInt();
85         setDuration(GenTime(out - in, KdenliveSettings::project_fps()));
86     }
87
88     if (!m_properties.contains("name")) m_properties.insert("name", url.fileName());
89
90     m_thumbProd = new KThumb(clipManager, url, m_id, m_properties.value("file_hash"));
91     if (m_clipType == AV || m_clipType == AUDIO || m_clipType == PLAYLIST) slotCreateAudioTimer();
92 }
93
94 DocClipBase::~DocClipBase()
95 {
96     delete m_thumbProd;
97     if (m_audioTimer) {
98         m_audioTimer->stop();
99         delete m_audioTimer;
100     }
101     qDeleteAll(m_baseTrackProducers);
102     m_baseTrackProducers.clear();
103     qDeleteAll(m_audioTrackProducers);
104     m_audioTrackProducers.clear();
105     delete m_videoOnlyProducer;
106     m_videoOnlyProducer = NULL;
107 }
108
109 void DocClipBase::setZone(QPoint zone)
110 {
111     m_properties.insert("zone_in", QString::number(zone.x()));
112     m_properties.insert("zone_out", QString::number(zone.y()));
113 }
114
115 QPoint DocClipBase::zone() const
116 {
117     QPoint zone(m_properties.value("zone_in", "0").toInt(), m_properties.value("zone_out", "50").toInt());
118     return zone;
119 }
120
121 void DocClipBase::slotCreateAudioTimer()
122 {
123     connect(m_thumbProd, SIGNAL(audioThumbReady(const audioByteArray&)), this , SLOT(updateAudioThumbnail(const audioByteArray&)));
124     m_audioTimer = new QTimer(this);
125     connect(m_audioTimer, SIGNAL(timeout()), this, SLOT(slotGetAudioThumbs()));
126 }
127
128 void DocClipBase::askForAudioThumbs()
129 {
130     if (m_thumbProd && m_audioTimer) m_thumbProd->askForAudioThumbs(getId());
131 }
132
133 void DocClipBase::slotClearAudioCache()
134 {
135     if (m_thumbProd) m_thumbProd->stopAudioThumbs();
136     if (m_audioTimer != NULL) m_audioTimer->stop();
137     m_audioFrameCache.clear();
138     m_audioThumbCreated = false;
139 }
140
141 /*void DocClipBase::getClipMainThumb() {
142     if (m_thumbProd) m_thumbProd->getMainThumb(m_properties.value("thumbnail").toInt());
143 }*/
144
145 KThumb *DocClipBase::thumbProducer()
146 {
147     return m_thumbProd;
148 }
149
150 bool DocClipBase::audioThumbCreated() const
151 {
152     return m_audioThumbCreated;
153 }
154
155 const QString DocClipBase::name() const
156 {
157
158     return m_properties.value("name");
159 }
160
161 const QString &DocClipBase::getId() const
162 {
163     return m_id;
164 }
165
166 const CLIPTYPE & DocClipBase::clipType() const
167 {
168     return m_clipType;
169 }
170
171 void DocClipBase::setClipType(CLIPTYPE type)
172 {
173     m_clipType = type;
174
175     m_properties.insert("type", QString::number((int) type));
176     if (m_thumbProd && m_audioTimer == NULL && (m_clipType == AV || m_clipType == AUDIO || m_clipType == PLAYLIST))
177         slotCreateAudioTimer();
178 }
179
180 KUrl DocClipBase::fileURL() const
181 {
182     QString res = m_properties.value("resource");
183     if (m_clipType != COLOR && !res.isEmpty()) return KUrl(res);
184     return KUrl();
185 }
186
187 void DocClipBase::setClipThumbFrame(const uint &ix)
188 {
189     m_properties.insert("thumbnail", QString::number((int) ix));
190 }
191
192 uint DocClipBase::getClipThumbFrame() const
193 {
194     return (uint) m_properties.value("thumbnail").toInt();
195 }
196
197 const QString DocClipBase::description() const
198 {
199     return m_properties.value("description");
200 }
201
202 bool DocClipBase::isTransparent() const
203 {
204     return (m_properties.value("transparency") == "1");
205 }
206
207 const QString DocClipBase::getProperty(const QString &prop) const
208 {
209     return m_properties.value(prop);
210 }
211
212 void DocClipBase::setDuration(GenTime dur)
213 {
214     m_duration = dur;
215     m_properties.insert("duration", QString::number((int) dur.frames(KdenliveSettings::project_fps())));
216 }
217
218 const GenTime &DocClipBase::duration() const
219 {
220     return m_duration;
221 }
222
223 const GenTime DocClipBase::maxDuration() const
224 {
225     if (m_clipType == COLOR || m_clipType == IMAGE || m_clipType == TEXT || (m_clipType == SLIDESHOW &&  m_properties.value("loop") == "1")) {
226         /*const GenTime dur(15000, KdenliveSettings::project_fps());
227         return dur;*/
228         return GenTime();
229     }
230     return m_duration;
231 }
232
233 bool DocClipBase::hasFileSize() const
234 {
235     return true;
236 }
237
238 qulonglong DocClipBase::fileSize() const
239 {
240     return m_properties.value("file_size").toULongLong();
241 }
242
243 // virtual
244 QDomElement DocClipBase::toXML() const
245 {
246     QDomDocument doc;
247     QDomElement clip = doc.createElement("producer");
248
249     QMapIterator<QString, QString> i(m_properties);
250     while (i.hasNext()) {
251         i.next();
252         if (!i.value().isEmpty()) clip.setAttribute(i.key(), i.value());
253     }
254     doc.appendChild(clip);
255     if (!m_cutZones.isEmpty()) {
256         QStringList cuts;
257         for (int i = 0; i < m_cutZones.size(); i++) {
258             CutZoneInfo info = m_cutZones.at(i);
259             cuts << QString::number(info.zone.x()) + "-" + QString::number(info.zone.y()) + "-" + info.description;
260         }
261         clip.setAttribute("cutzones", cuts.join(";"));
262     }
263     //kDebug() << "/// CLIP XML: " << doc.toString();
264     return doc.documentElement();
265 }
266
267
268 void DocClipBase::setAudioThumbCreated(bool isDone)
269 {
270     m_audioThumbCreated = isDone;
271 }
272
273
274 void DocClipBase::setThumbnail(const QPixmap & pixmap)
275 {
276     m_thumbnail = pixmap;
277 }
278
279 const QPixmap & DocClipBase::thumbnail() const
280 {
281     return m_thumbnail;
282 }
283
284 void DocClipBase::updateAudioThumbnail(const audioByteArray& data)
285 {
286     //kDebug() << "CLIPBASE RECIEDVED AUDIO DATA*********************************************";
287     m_audioFrameCache = data;
288     m_audioThumbCreated = true;
289     emit gotAudioData();
290 }
291
292 QList < GenTime > DocClipBase::snapMarkers() const
293 {
294     QList < GenTime > markers;
295
296     for (int count = 0; count < m_snapMarkers.count(); ++count) {
297         markers.append(m_snapMarkers.at(count).time());
298     }
299
300     return markers;
301 }
302
303 QList < CommentedTime > DocClipBase::commentedSnapMarkers() const
304 {
305     return m_snapMarkers;
306 }
307
308
309 void DocClipBase::addSnapMarker(const GenTime & time, QString comment)
310 {
311     QList < CommentedTime >::Iterator it = m_snapMarkers.begin();
312     for (it = m_snapMarkers.begin(); it != m_snapMarkers.end(); ++it) {
313         if ((*it).time() >= time)
314             break;
315     }
316
317     if ((it != m_snapMarkers.end()) && ((*it).time() == time)) {
318         (*it).setComment(comment);
319         //kError() << "trying to add Snap Marker that already exists, this will cause inconsistancies with undo/redo";
320     } else {
321         CommentedTime t(time, comment);
322         m_snapMarkers.insert(it, t);
323     }
324
325 }
326
327 void DocClipBase::editSnapMarker(const GenTime & time, QString comment)
328 {
329     QList < CommentedTime >::Iterator it;
330     for (it = m_snapMarkers.begin(); it != m_snapMarkers.end(); ++it) {
331         if ((*it).time() == time)
332             break;
333     }
334     if (it != m_snapMarkers.end()) {
335         (*it).setComment(comment);
336     } else {
337         kError() << "trying to edit Snap Marker that does not already exists";
338     }
339 }
340
341 QString DocClipBase::deleteSnapMarker(const GenTime & time)
342 {
343     QString result = i18n("Marker");
344     QList < CommentedTime >::Iterator itt = m_snapMarkers.begin();
345
346     while (itt != m_snapMarkers.end()) {
347         if ((*itt).time() == time)
348             break;
349         ++itt;
350     }
351
352     if ((itt != m_snapMarkers.end()) && ((*itt).time() == time)) {
353         result = (*itt).comment();
354         m_snapMarkers.erase(itt);
355     }
356     return result;
357 }
358
359
360 GenTime DocClipBase::hasSnapMarkers(const GenTime & time)
361 {
362     QList < CommentedTime >::Iterator itt = m_snapMarkers.begin();
363
364     while (itt != m_snapMarkers.end()) {
365         if ((*itt).time() == time)
366             return time;
367         ++itt;
368     }
369
370     return GenTime(0.0);
371 }
372
373 GenTime DocClipBase::findPreviousSnapMarker(const GenTime & currTime)
374 {
375     int it;
376     for (it = 0; it < m_snapMarkers.count(); it++) {
377         if (m_snapMarkers.at(it).time() >= currTime)
378             break;
379     }
380     if (it == 0) return GenTime();
381     else if (it == m_snapMarkers.count() - 1 && m_snapMarkers.at(it).time() < currTime)
382         return m_snapMarkers.at(it).time();
383     else return m_snapMarkers.at(it - 1).time();
384 }
385
386 GenTime DocClipBase::findNextSnapMarker(const GenTime & currTime)
387 {
388     int it;
389     for (it = 0; it < m_snapMarkers.count(); it++) {
390         if (m_snapMarkers.at(it).time() > currTime)
391             break;
392     }
393     if (it < m_snapMarkers.count() && m_snapMarkers.at(it).time() > currTime) return m_snapMarkers.at(it).time();
394     return duration();
395 }
396
397 QString DocClipBase::markerComment(GenTime t)
398 {
399     QList < CommentedTime >::Iterator itt = m_snapMarkers.begin();
400
401     while (itt != m_snapMarkers.end()) {
402         if ((*itt).time() == t)
403             return (*itt).comment();
404         ++itt;
405     }
406     return QString();
407 }
408
409 void DocClipBase::clearThumbProducer()
410 {
411     if (m_thumbProd) m_thumbProd->clearProducer();
412 }
413
414 void DocClipBase::deleteProducers()
415 {
416     m_thumbProd->clearProducer();
417     
418     if (numReferences() > 0) {
419         // Clip is used in timeline, delay producers deletion
420         if (m_videoOnlyProducer) m_toDeleteProducers.append(m_videoOnlyProducer);
421         for (int i = 0; i < m_baseTrackProducers.count(); i++) {
422             m_toDeleteProducers.append(m_baseTrackProducers.at(i));
423         }
424         for (int i = 0; i < m_audioTrackProducers.count(); i++) {
425             m_toDeleteProducers.append(m_audioTrackProducers.at(i));
426         }
427     }
428     else {
429         delete m_videoOnlyProducer;
430         qDeleteAll(m_baseTrackProducers);
431         qDeleteAll(m_audioTrackProducers);
432         m_replaceMutex.unlock();
433     }
434     m_videoOnlyProducer = NULL;
435     m_baseTrackProducers.clear();
436     m_audioTrackProducers.clear();
437 }
438
439 void DocClipBase::cleanupProducers()
440 {
441     /*
442     int ct = 0;
443     kDebug()<<"----------------------------------------------------------------------------------";
444     for (int i = 0; i < m_toDeleteProducers.count(); i++) {
445         if (m_toDeleteProducers.at(i) != NULL) {
446             Mlt::Properties props(m_toDeleteProducers.at(i)->get_properties());
447             if (props.ref_count() > 2) {
448                 kDebug()<<"PRODUCER: "<<i<<", COUNTS: "<<props.ref_count();
449                 //exit(1);
450             }
451             ct++;
452         }
453     }*/
454
455     qDeleteAll(m_toDeleteProducers);
456     m_toDeleteProducers.clear();
457     m_replaceMutex.unlock();
458 }
459
460 bool DocClipBase::isClean() const
461 {
462     return m_toDeleteProducers.isEmpty();
463 }
464
465 void DocClipBase::setValid()
466 {
467     m_placeHolder = false;
468 }
469
470 void DocClipBase::setProducer(Mlt::Producer *producer, bool reset, bool readPropertiesFromProducer)
471 {
472     if (producer == NULL) return;
473     if (reset) {
474         QMutexLocker locker(&m_producerMutex);
475         m_replaceMutex.lock();
476         deleteProducers();
477     }
478     QString id = producer->get("id");
479     if (m_placeHolder || !producer->is_valid()) {
480         char *tmp = qstrdup(i18n("Missing clip").toUtf8().constData());
481         producer->set("markup", tmp);
482         producer->set("bgcolour", "0xff0000ff");
483         producer->set("pad", "10");
484         delete[] tmp;
485     }
486     else if (m_thumbProd && !m_thumbProd->hasProducer()) {
487         if (m_clipType != AUDIO) {
488             if (!id.endsWith("_audio"))
489                 m_thumbProd->setProducer(producer);
490         }
491         else m_thumbProd->setProducer(producer);
492     }
493     bool updated = false;
494     if (id.contains('_')) {
495         // this is a subtrack producer, insert it at correct place
496         id = id.section('_', 1);
497         if (id.endsWith("audio")) {
498             int pos = id.section('_', 0, 0).toInt();
499             if (pos >= m_audioTrackProducers.count()) {
500                 while (m_audioTrackProducers.count() - 1 < pos) {
501                     m_audioTrackProducers.append(NULL);
502                 }
503             }
504             if (m_audioTrackProducers.at(pos) == NULL) {
505                 m_audioTrackProducers[pos] = producer;
506                 updated = true;
507             }
508             else delete producer;
509             return;
510         } else if (id.endsWith("video")) {
511             if (m_videoOnlyProducer == NULL) {
512                 m_videoOnlyProducer = producer;
513                 updated = true;
514             }
515             else delete producer;
516             return;
517         }
518         int pos = id.toInt();
519         if (pos >= m_baseTrackProducers.count()) {
520             while (m_baseTrackProducers.count() - 1 < pos) {
521                 m_baseTrackProducers.append(NULL);
522             }
523         }
524         if (m_baseTrackProducers.at(pos) == NULL) {
525             m_baseTrackProducers[pos] = producer;
526             updated = true;
527         }
528         else delete producer;
529     } else {
530         if (m_baseTrackProducers.isEmpty()) {
531             m_baseTrackProducers.append(producer);
532             updated = true;
533         }
534         else if (m_baseTrackProducers.at(0) == NULL) {
535             m_baseTrackProducers[0] = producer;
536             updated = true;
537         }
538         else delete producer;
539     }
540     if (updated && readPropertiesFromProducer && (m_clipType != COLOR && m_clipType != IMAGE && m_clipType != TEXT))
541         setDuration(GenTime(producer->get_length(), KdenliveSettings::project_fps()));
542 }
543
544 static double getPixelAspect(QMap<QString, QString>& props) {
545     int width = props.value("frame_size").section('x', 0, 0).toInt();
546     int height = props.value("frame_size").section('x', 1, 1).toInt();
547     int aspectNumerator = props.value("force_aspect_num").toInt();
548     int aspectDenominator = props.value("force_aspect_den").toInt();
549     if (aspectDenominator != 0 && width != 0)
550         return double(height) * aspectNumerator / aspectDenominator / width;    
551     else
552         return 1.0;
553 }
554
555 Mlt::Producer *DocClipBase::audioProducer(int track)
556 {
557     QMutexLocker locker(&m_producerMutex);
558     if (m_audioTrackProducers.count() <= track) {
559         while (m_audioTrackProducers.count() - 1 < track) {
560             m_audioTrackProducers.append(NULL);
561         }
562     }
563     if (m_audioTrackProducers.at(track) == NULL) {
564         int i;
565         for (i = 0; i < m_audioTrackProducers.count(); i++)
566             if (m_audioTrackProducers.at(i) != NULL) break;
567         Mlt::Producer *base;
568         if (i >= m_audioTrackProducers.count()) {
569             // Could not find a valid producer for that clip
570             locker.unlock();
571             base = getProducer();
572             if (base == NULL) {
573                 return NULL;
574             }
575             locker.relock();
576         }
577         else base = m_audioTrackProducers.at(i);
578         m_audioTrackProducers[track] = cloneProducer(base);
579         adjustProducerProperties(m_audioTrackProducers.at(track), QString(getId() + '_' + QString::number(track) + "_audio"), false, true);
580     }
581     return m_audioTrackProducers.at(track);
582 }
583
584
585 void DocClipBase::adjustProducerProperties(Mlt::Producer *prod, const QString &id, bool mute, bool blind)
586 {
587         if (m_properties.contains("force_aspect_num") && m_properties.contains("force_aspect_den") && m_properties.contains("frame_size"))
588             prod->set("force_aspect_ratio", getPixelAspect(m_properties));
589         if (m_properties.contains("force_fps")) prod->set("force_fps", m_properties.value("force_fps").toDouble());
590         if (m_properties.contains("force_progressive")) prod->set("force_progressive", m_properties.value("force_progressive").toInt());
591         if (m_properties.contains("force_tff")) prod->set("force_tff", m_properties.value("force_tff").toInt());
592         if (m_properties.contains("threads")) prod->set("threads", m_properties.value("threads").toInt());
593         if (mute) prod->set("audio_index", -1);
594         else if (m_properties.contains("audio_index")) prod->set("audio_index", m_properties.value("audio_index").toInt());
595         if (blind) prod->set("video_index", -1);
596         else if (m_properties.contains("video_index")) prod->set("video_index", m_properties.value("video_index").toInt());
597         prod->set("id", id.toUtf8().constData());
598         if (m_properties.contains("force_colorspace")) prod->set("force_colorspace", m_properties.value("force_colorspace").toInt());
599         if (m_properties.contains("full_luma")) prod->set("set.force_full_luma", m_properties.value("full_luma").toInt());
600         if (m_properties.contains("proxy_out")) {
601             // We have a proxy clip, make sure the proxy has same duration as original
602             prod->set("length", m_properties.value("duration").toInt());
603             prod->set("out", m_properties.value("proxy_out").toInt());
604         }
605
606 }
607
608 Mlt::Producer *DocClipBase::videoProducer()
609 {
610     QMutexLocker locker(&m_producerMutex);
611     if (m_videoOnlyProducer == NULL) {
612         int i;
613         for (i = 0; i < m_baseTrackProducers.count(); i++)
614             if (m_baseTrackProducers.at(i) != NULL) break;
615         if (i >= m_baseTrackProducers.count()) return NULL;
616         m_videoOnlyProducer = cloneProducer(m_baseTrackProducers.at(i));
617         adjustProducerProperties(m_videoOnlyProducer, QString(getId() + "_video"), true, false);
618     }
619     return m_videoOnlyProducer;
620 }
621
622 Mlt::Producer *DocClipBase::getCloneProducer()
623 {
624     Mlt::Producer *source = NULL;
625     Mlt::Producer *prod = NULL;
626     if (m_clipType != AUDIO && m_clipType != AV && m_clipType != PLAYLIST) {
627         source = getProducer();
628         if (!source) return NULL;
629     }
630     if (m_clipType == COLOR) {
631         prod = new Mlt::Producer(*(source->profile()), 0, QString("colour:" + QString(source->get("resource"))).toUtf8().constData());
632     } else if (m_clipType == TEXT) {
633         prod = new Mlt::Producer(*(source->profile()), 0, QString("kdenlivetitle:" + QString(source->get("resource"))).toUtf8().constData());
634         if (prod && prod->is_valid() && m_properties.contains("xmldata"))
635             prod->set("xmldata", m_properties.value("xmldata").toUtf8().constData());
636     }
637     if (!prod) {
638         if (!source) {
639             QMutexLocker locker(&m_producerMutex);
640             for (int i = 0; i < m_baseTrackProducers.count(); i++) {
641                 if (m_baseTrackProducers.at(i) != NULL) {
642                     source = m_baseTrackProducers.at(i);
643                     break;
644                 }
645             }
646             if (!source) return NULL;
647         }
648         prod = cloneProducer(source);
649     }
650     if (prod) {
651         adjustProducerProperties(prod, getId() + "_", false, false);
652         if (!m_properties.contains("proxy_out")) {
653             // Adjust length in case...
654             if (m_properties.contains("duration")) prod->set("length", m_properties.value("duration").toInt());
655             if (m_properties.contains("out"))prod->set("out", m_properties.value("out").toInt());
656         }
657     }
658     return prod;
659 }
660
661 Mlt::Producer *DocClipBase::getProducer(int track)
662 {
663     QMutexLocker locker(&m_producerMutex);
664     if (track == -1 || (m_clipType != AUDIO && m_clipType != AV && m_clipType != PLAYLIST)) {
665         if (m_baseTrackProducers.count() == 0) {
666             return NULL;
667         }
668         for (int i = 0; i < m_baseTrackProducers.count(); i++) {
669             if (m_baseTrackProducers.at(i) != NULL) {
670                 return m_baseTrackProducers.at(i);
671             }
672         }
673         return NULL;
674     }
675     if (track >= m_baseTrackProducers.count()) {
676         while (m_baseTrackProducers.count() - 1 < track) {
677             m_baseTrackProducers.append(NULL);
678         }
679     }
680     if (m_baseTrackProducers.at(track) == NULL) {
681         int i;
682         for (i = 0; i < m_baseTrackProducers.count(); i++)
683             if (m_baseTrackProducers.at(i) != NULL) break;
684
685         if (i >= m_baseTrackProducers.count()) {
686             // Could not find a valid producer for that clip, check in 
687             return NULL;
688         }
689         Mlt::Producer *prod = cloneProducer(m_baseTrackProducers.at(i));
690         adjustProducerProperties(prod, QString(getId() + '_' + QString::number(track)), false, false);
691         m_baseTrackProducers[track] = prod;
692     }
693     return m_baseTrackProducers.at(track);
694 }
695
696
697 Mlt::Producer *DocClipBase::cloneProducer(Mlt::Producer *source)
698 {
699     Mlt::Producer *result = NULL;
700     QString url = QString::fromUtf8(source->get("resource"));
701     if (KIO::NetAccess::exists(KUrl(url), KIO::NetAccess::SourceSide, 0)) {
702         result = new Mlt::Producer(*(source->profile()), url.toUtf8().constData());
703     }
704     if (result == NULL || !result->is_valid()) {
705         // placeholder clip
706         QString txt = "+" + i18n("Missing clip") + ".txt";
707         char *tmp = qstrdup(txt.toUtf8().constData());
708         result = new Mlt::Producer(*source->profile(), tmp);
709         delete[] tmp;
710         if (result == NULL || !result->is_valid())
711             result = new Mlt::Producer(*(source->profile()), "colour:red");
712         else {
713             result->set("bgcolour", "0xff0000ff");
714             result->set("pad", "10");
715         }
716         return result;
717     }
718     /*Mlt::Properties src_props(source->get_properties());
719     Mlt::Properties props(result->get_properties());
720     props.inherit(src_props);*/
721     return result;
722 }
723
724 void DocClipBase::setProducerProperty(const char *name, int data)
725 {
726     QMutexLocker locker(&m_producerMutex);
727     for (int i = 0; i < m_baseTrackProducers.count(); i++) {
728         if (m_baseTrackProducers.at(i) != NULL)
729             m_baseTrackProducers[i]->set(name, data);
730     }
731 }
732
733 void DocClipBase::setProducerProperty(const char *name, double data)
734 {
735     QMutexLocker locker(&m_producerMutex);
736     for (int i = 0; i < m_baseTrackProducers.count(); i++) {
737         if (m_baseTrackProducers.at(i) != NULL)
738             m_baseTrackProducers[i]->set(name, data);
739     }
740 }
741
742 void DocClipBase::setProducerProperty(const char *name, const char *data)
743 {
744     QMutexLocker locker(&m_producerMutex);
745     for (int i = 0; i < m_baseTrackProducers.count(); i++) {
746         if (m_baseTrackProducers.at(i) != NULL)
747             m_baseTrackProducers[i]->set(name, data);
748     }
749 }
750
751 void DocClipBase::resetProducerProperty(const char *name)
752 {
753     QMutexLocker locker(&m_producerMutex);
754     for (int i = 0; i < m_baseTrackProducers.count(); i++) {
755         if (m_baseTrackProducers.at(i) != NULL)
756             m_baseTrackProducers[i]->set(name, (const char*) NULL);
757     }
758 }
759
760 const char *DocClipBase::producerProperty(const char *name) const
761 {
762     for (int i = 0; i < m_baseTrackProducers.count(); i++) {
763         if (m_baseTrackProducers.at(i) != NULL) {
764             return m_baseTrackProducers.at(i)->get(name);
765         }
766     }
767     return NULL;
768 }
769
770
771 void DocClipBase::slotRefreshProducer()
772 {
773     if (m_baseTrackProducers.count() == 0) return;
774     if (m_clipType == SLIDESHOW) {
775         setProducerProperty("ttl", getProperty("ttl").toInt());
776         //m_clipProducer->set("id", getProperty("id"));
777         if (!getProperty("animation").isEmpty()) {
778             Mlt::Service clipService(m_baseTrackProducers.at(0)->get_service());
779             int ct = 0;
780             Mlt::Filter *filter = clipService.filter(ct);
781             while (filter) {
782                 if (strcmp(filter->get("mlt_service"), "affine") == 0) {
783                     break;
784                 } else if (strcmp(filter->get("mlt_service"), "boxblur") == 0) {
785                     clipService.detach(*filter);
786                 } else ct++;
787                 filter = clipService.filter(ct);
788             }
789
790             if (!filter || strcmp(filter->get("mlt_service"), "affine")) {
791                 // filter does not exist, create it.
792                 Mlt::Filter *filter = new Mlt::Filter(*(m_baseTrackProducers.at(0)->profile()), "affine");
793                 if (filter && filter->is_valid()) {
794                     int cycle = getProperty("ttl").toInt();
795                     QString geometry = SlideshowClip::animationToGeometry(getProperty("animation"), cycle);
796                     if (!geometry.isEmpty()) {
797                         if (getProperty("animation").contains("low-pass")) {
798                             Mlt::Filter *blur = new Mlt::Filter(*(m_baseTrackProducers.at(0)->profile()), "boxblur");
799                             if (blur && blur->is_valid())
800                                 clipService.attach(*blur);
801                         }
802                         filter->set("transition.geometry", geometry.toUtf8().data());
803                         filter->set("transition.cycle", cycle);
804                         clipService.attach(*filter);
805                     }
806                 }
807             }
808         } else {
809             Mlt::Service clipService(m_baseTrackProducers.at(0)->get_service());
810             int ct = 0;
811             Mlt::Filter *filter = clipService.filter(0);
812             while (filter) {
813                 if (strcmp(filter->get("mlt_service"), "affine") == 0 || strcmp(filter->get("mlt_service"), "boxblur") == 0) {
814                     clipService.detach(*filter);
815                 } else ct++;
816                 filter = clipService.filter(ct);
817             }
818         }
819         if (getProperty("fade") == "1") {
820             // we want a fade filter effect
821             kDebug() << "////////////   FADE WANTED";
822             Mlt::Service clipService(m_baseTrackProducers.at(0)->get_service());
823             int ct = 0;
824             Mlt::Filter *filter = clipService.filter(ct);
825             while (filter) {
826                 if (strcmp(filter->get("mlt_service"), "luma") == 0) {
827                     break;
828                 }
829                 ct++;
830                 filter = clipService.filter(ct);
831             }
832
833             if (filter && strcmp(filter->get("mlt_service"), "luma") == 0) {
834                 filter->set("cycle", getProperty("ttl").toInt());
835                 filter->set("duration", getProperty("luma_duration").toInt());
836                 filter->set("luma.resource", getProperty("luma_file").toUtf8().data());
837                 if (!getProperty("softness").isEmpty()) {
838                     int soft = getProperty("softness").toInt();
839                     filter->set("luma.softness", (double) soft / 100.0);
840                 }
841             } else {
842                 // filter does not exist, create it...
843                 Mlt::Filter *filter = new Mlt::Filter(*(m_baseTrackProducers.at(0)->profile()), "luma");
844                 filter->set("cycle", getProperty("ttl").toInt());
845                 filter->set("duration", getProperty("luma_duration").toInt());
846                 filter->set("luma.resource", getProperty("luma_file").toUtf8().data());
847                 if (!getProperty("softness").isEmpty()) {
848                     int soft = getProperty("softness").toInt();
849                     filter->set("luma.softness", (double) soft / 100.0);
850                 }
851                 clipService.attach(*filter);
852             }
853         } else {
854             kDebug() << "////////////   FADE NOT WANTED!!!";
855             Mlt::Service clipService(m_baseTrackProducers.at(0)->get_service());
856             int ct = 0;
857             Mlt::Filter *filter = clipService.filter(0);
858             while (filter) {
859                 if (strcmp(filter->get("mlt_service"), "luma") == 0) {
860                     clipService.detach(*filter);
861                 } else ct++;
862                 filter = clipService.filter(ct);
863             }
864         }
865         if (getProperty("crop") == "1") {
866             // we want a center crop filter effect
867             Mlt::Service clipService(m_baseTrackProducers.at(0)->get_service());
868             int ct = 0;
869             Mlt::Filter *filter = clipService.filter(ct);
870             while (filter) {
871                 if (strcmp(filter->get("mlt_service"), "crop") == 0) {
872                     break;
873                 }
874                 ct++;
875                 filter = clipService.filter(ct);
876             }
877
878             if (!filter || strcmp(filter->get("mlt_service"), "crop")) {
879                 // filter does not exist, create it...
880                 Mlt::Filter *filter = new Mlt::Filter(*(m_baseTrackProducers.at(0)->profile()), "crop");
881                 filter->set("center", 1);
882                 clipService.attach(*filter);
883             }
884         } else {
885             Mlt::Service clipService(m_baseTrackProducers.at(0)->get_service());
886             int ct = 0;
887             Mlt::Filter *filter = clipService.filter(0);
888             while (filter) {
889                 if (strcmp(filter->get("mlt_service"), "crop") == 0) {
890                     clipService.detach(*filter);
891                 } else ct++;
892                 filter = clipService.filter(ct);
893             }
894         }
895     }
896 }
897
898 void DocClipBase::setProperties(QMap <QString, QString> properties)
899 {
900     // changing clip type is not allowed
901     properties.remove("type");
902     QMapIterator<QString, QString> i(properties);
903     bool refreshProducer = false;
904     QStringList keys;
905     keys << "luma_duration" << "luma_file" << "fade" << "ttl" << "softness" << "crop" << "animation";
906     QString oldProxy = m_properties.value("proxy");
907     while (i.hasNext()) {
908         i.next();
909         setProperty(i.key(), i.value());
910         if (m_clipType == SLIDESHOW && keys.contains(i.key())) refreshProducer = true;
911     }
912     if (properties.contains("proxy")) {
913         QString value = properties.value("proxy");
914         // If value is "-", that means user manually disabled proxy on this clip
915         if (value.isEmpty() || value == "-") {
916             // reset proxy
917             emit abortProxy(m_id, oldProxy);
918         }
919         else {
920             emit createProxy(m_id);
921         }
922     }
923     if (refreshProducer) slotRefreshProducer();
924 }
925
926 void DocClipBase::setMetadata(QMap <QString, QString> properties)
927 {
928     QMapIterator<QString, QString> i(properties);
929     while (i.hasNext()) {
930         i.next();
931         if (i.value().isEmpty() && m_metadata.contains(i.key())) {
932             m_metadata.remove(i.key());
933         } else {
934             m_metadata.insert(i.key(), i.value());
935         }
936     }
937 }
938
939 QMap <QString, QString> DocClipBase::metadata() const
940 {
941     return m_metadata;
942 }
943
944 void DocClipBase::clearProperty(const QString &key)
945 {
946     m_properties.remove(key);
947 }
948
949 void DocClipBase::getFileHash(const QString &url)
950 {
951     if (m_clipType == SLIDESHOW) return;
952     QFile file(url);
953     if (file.open(QIODevice::ReadOnly)) { // write size and hash only if resource points to a file
954         QByteArray fileData;
955         QByteArray fileHash;
956         //kDebug() << "SETTING HASH of" << value;
957         m_properties.insert("file_size", QString::number(file.size()));
958         /*
959                * 1 MB = 1 second per 450 files (or faster)
960                * 10 MB = 9 seconds per 450 files (or faster)
961                */
962         if (file.size() > 1000000*2) {
963             fileData = file.read(1000000);
964             if (file.seek(file.size() - 1000000))
965                 fileData.append(file.readAll());
966         } else
967             fileData = file.readAll();
968         file.close();
969         fileHash = QCryptographicHash::hash(fileData, QCryptographicHash::Md5);
970         m_properties.insert("file_hash", QString(fileHash.toHex()));
971     }
972 }
973
974 bool DocClipBase::checkHash() const
975 {
976     KUrl url = fileURL();
977     if (!url.isEmpty() && getClipHash() != getHash(url.path())) return false;
978     return true;
979 }
980
981 QString DocClipBase::getClipHash() const
982 {
983     QString hash;
984     if (m_clipType == SLIDESHOW) hash = QCryptographicHash::hash(m_properties.value("resource").toAscii().data(), QCryptographicHash::Md5).toHex();
985     else if (m_clipType == COLOR) hash = QCryptographicHash::hash(m_properties.value("colour").toAscii().data(), QCryptographicHash::Md5).toHex();
986     else if (m_clipType == TEXT) hash = QCryptographicHash::hash(QString("title" + getId() + m_properties.value("xmldata")).toUtf8().data(), QCryptographicHash::Md5).toHex();
987     else {
988         if (m_properties.contains("file_hash")) hash = m_properties.value("file_hash");
989         if (hash.isEmpty()) hash = getHash(fileURL().path());
990         
991     }
992     return hash;
993 }
994
995 void DocClipBase::setPlaceHolder(bool place)
996 {
997     m_placeHolder = place;
998 }
999
1000 // static
1001 QString DocClipBase::getHash(const QString &path)
1002 {
1003     QFile file(path);
1004     if (file.open(QIODevice::ReadOnly)) { // write size and hash only if resource points to a file
1005         QByteArray fileData;
1006         QByteArray fileHash;
1007         /*
1008                * 1 MB = 1 second per 450 files (or faster)
1009                * 10 MB = 9 seconds per 450 files (or faster)
1010                */
1011         if (file.size() > 1000000*2) {
1012             fileData = file.read(1000000);
1013             if (file.seek(file.size() - 1000000))
1014                 fileData.append(file.readAll());
1015         } else
1016             fileData = file.readAll();
1017         file.close();
1018         return QCryptographicHash::hash(fileData, QCryptographicHash::Md5).toHex();
1019     }
1020     return QString();
1021 }
1022
1023 void DocClipBase::refreshThumbUrl()
1024 {
1025     if (m_thumbProd) m_thumbProd->updateThumbUrl(m_properties.value("file_hash"));
1026 }
1027
1028 void DocClipBase::setProperty(const QString &key, const QString &value)
1029 {
1030     m_properties.insert(key, value);
1031     if (key == "resource") {
1032         getFileHash(value);
1033         if (m_thumbProd) m_thumbProd->updateClipUrl(KUrl(value), m_properties.value("file_hash"));
1034     } else if (key == "out") setDuration(GenTime(value.toInt(), KdenliveSettings::project_fps()));
1035     //else if (key == "transparency") m_clipProducer->set("transparency", value.toInt());
1036     else if (key == "colour") {
1037         setProducerProperty("colour", value.toUtf8().data());
1038     } else if (key == "templatetext") {
1039         setProducerProperty("templatetext", value.toUtf8().data());
1040         setProducerProperty("force_reload", 1);
1041     } else if (key == "xmldata") {
1042         setProducerProperty("xmldata", value.toUtf8().data());
1043         setProducerProperty("force_reload", 1);
1044     } else if (key == "force_aspect_num") {
1045         if (value.isEmpty()) {
1046             m_properties.remove("force_aspect_num");
1047             resetProducerProperty("force_aspect_ratio");
1048         } else setProducerProperty("force_aspect_ratio", getPixelAspect(m_properties));
1049     } else if (key == "force_aspect_den") {
1050         if (value.isEmpty()) {
1051             m_properties.remove("force_aspect_den");
1052             resetProducerProperty("force_aspect_ratio");
1053         } else setProducerProperty("force_aspect_ratio", getPixelAspect(m_properties));
1054     } else if (key == "force_fps") {
1055         if (value.isEmpty()) {
1056             m_properties.remove("force_fps");
1057             resetProducerProperty("force_fps");
1058         } else setProducerProperty("force_fps", value.toDouble());
1059     } else if (key == "force_progressive") {
1060         if (value.isEmpty()) {
1061             m_properties.remove("force_progressive");
1062             resetProducerProperty("force_progressive");
1063         } else setProducerProperty("force_progressive", value.toInt());
1064     } else if (key == "force_tff") {
1065         if (value.isEmpty()) {
1066             m_properties.remove("force_tff");
1067             resetProducerProperty("force_tff");
1068         } else setProducerProperty("force_tff", value.toInt());
1069     } else if (key == "threads") {
1070         if (value.isEmpty()) {
1071             m_properties.remove("threads");
1072             setProducerProperty("threads", 1);
1073         } else setProducerProperty("threads", value.toInt());
1074     } else if (key == "video_index") {
1075         if (value.isEmpty()) {
1076             m_properties.remove("video_index");
1077             setProducerProperty("video_index", m_properties.value("default_video").toInt());
1078         } else setProducerProperty("video_index", value.toInt());
1079     } else if (key == "audio_index") {
1080         if (value.isEmpty()) {
1081             m_properties.remove("audio_index");
1082             setProducerProperty("audio_index", m_properties.value("default_audio").toInt());
1083         } else setProducerProperty("audio_index", value.toInt());
1084     } else if (key == "force_colorspace") {
1085         if (value.isEmpty()) {
1086             m_properties.remove("force_colorspace");
1087             resetProducerProperty("force_colorspace");
1088         } else setProducerProperty("force_colorspace", value.toInt());
1089     } else if (key == "full_luma") {
1090         if (value.isEmpty()) {
1091             m_properties.remove("full_luma");
1092             resetProducerProperty("set.force_full_luma");
1093         } else setProducerProperty("set.force_full_luma", value.toInt());
1094     }
1095 }
1096
1097 QMap <QString, QString> DocClipBase::properties() const
1098 {
1099     return m_properties;
1100 }
1101
1102 bool DocClipBase::slotGetAudioThumbs()
1103 {
1104     if (m_thumbProd == NULL || isPlaceHolder()) return false;
1105     if (!KdenliveSettings::audiothumbnails() || m_audioTimer == NULL) {
1106         if (m_audioTimer != NULL) m_audioTimer->stop();
1107         return false;
1108     }
1109     if (m_audioThumbCreated) {
1110         m_audioTimer->stop();
1111         return false;
1112     }
1113     m_audioTimer->start(1500);
1114     double lengthInFrames = duration().frames(KdenliveSettings::project_fps());
1115     m_thumbProd->getAudioThumbs(2, 0, lengthInFrames /*must be number of frames*/, 20);
1116     return true;
1117 }
1118
1119 bool DocClipBase::isPlaceHolder() const
1120 {
1121     return m_placeHolder;
1122 }
1123
1124 void DocClipBase::addCutZone(int in, int out, QString desc)
1125 {
1126     CutZoneInfo info;
1127     info.zone = QPoint(in, out);
1128     info.description = desc;
1129     for (int i = 0; i < m_cutZones.count(); i++)
1130         if (m_cutZones.at(i).zone == info.zone) {
1131             return;
1132         }
1133     m_cutZones.append(info);
1134 }
1135
1136 bool DocClipBase::hasCutZone(QPoint p) const
1137 {
1138     for (int i = 0; i < m_cutZones.count(); i++)
1139         if (m_cutZones.at(i).zone == p) return true;
1140     return false;
1141 }
1142
1143
1144 void DocClipBase::removeCutZone(int in, int out)
1145 {
1146     QPoint p(in, out);
1147     for (int i = 0; i < m_cutZones.count(); i++) {
1148         if (m_cutZones.at(i).zone == p) {
1149             m_cutZones.removeAt(i);
1150             i--;
1151         }
1152     }
1153 }
1154
1155 void DocClipBase::updateCutZone(int oldin, int oldout, int in, int out, QString desc)
1156 {
1157     QPoint old(oldin, oldout);
1158     for (int i = 0; i < m_cutZones.size(); ++i) {
1159         if (m_cutZones.at(i).zone == old) {
1160             CutZoneInfo info;
1161             info.zone = QPoint(in, out);
1162             info.description = desc;
1163             m_cutZones.replace(i, info);
1164             break;
1165         }
1166     }
1167 }
1168
1169 QList <CutZoneInfo> DocClipBase::cutZones() const
1170 {
1171     return m_cutZones;
1172 }
1173
1174 bool DocClipBase::hasVideoCodec(const QString &codec) const
1175 {
1176     Mlt::Producer *prod = NULL;
1177     if (m_baseTrackProducers.count() == 0) return false;
1178     for (int i = 0; i < m_baseTrackProducers.count(); i++) {
1179         if (m_baseTrackProducers.at(i) != NULL) {
1180             prod = m_baseTrackProducers.at(i);
1181             break;
1182         }
1183     }
1184
1185     if (!prod) return false;
1186     int default_video = prod->get_int("video_index");
1187     char property[200];
1188     snprintf(property, sizeof(property), "meta.media.%d.codec.name", default_video);
1189     return prod->get(property) == codec;
1190 }
1191
1192 bool DocClipBase::hasAudioCodec(const QString &codec) const
1193 {
1194     Mlt::Producer *prod = NULL;
1195     if (m_baseTrackProducers.count() == 0) return false;
1196     for (int i = 0; i < m_baseTrackProducers.count(); i++) {
1197         if (m_baseTrackProducers.at(i) != NULL) {
1198             prod = m_baseTrackProducers.at(i);
1199             break;
1200         }
1201     }
1202     if (!prod) return false;
1203     int default_video = prod->get_int("audio_index");
1204     char property[200];
1205     snprintf(property, sizeof(property), "meta.media.%d.codec.name", default_video);
1206     return prod->get(property) == codec;
1207 }
1208
1209
1210 void DocClipBase::slotExtractImage(QList <int> frames)
1211 {
1212     if (m_thumbProd == NULL) return;
1213     m_thumbProd->extractImage(frames);
1214 }
1215
1216 QPixmap DocClipBase::extractImage(int frame, int width, int height)
1217 {
1218     if (m_thumbProd == NULL) return QPixmap(width, height);
1219     QMutexLocker locker(&m_producerMutex);
1220     QPixmap p = m_thumbProd->extractImage(frame, width, height);
1221     return p;
1222 }
1223
1224