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