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