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