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