]> git.sesse.net Git - kdenlive/blob - src/kdenlivedoc.cpp
13d1f4fa1c0638346746aa9b0b7d55a13dfd2f73
[kdenlive] / src / kdenlivedoc.cpp
1 /***************************************************************************
2  *   Copyright (C) 2007 by Jean-Baptiste Mardelle (jb@kdenlive.org)        *
3  *                                                                         *
4  *   This program is free software; you can redistribute it and/or modify  *
5  *   it under the terms of the GNU General Public License as published by  *
6  *   the Free Software Foundation; either version 2 of the License, or     *
7  *   (at your option) any later version.                                   *
8  *                                                                         *
9  *   This program is distributed in the hope that it will be useful,       *
10  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
11  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
12  *   GNU General Public License for more details.                          *
13  *                                                                         *
14  *   You should have received a copy of the GNU General Public License     *
15  *   along with this program; if not, write to the                         *
16  *   Free Software Foundation, Inc.,                                       *
17  *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA          *
18  ***************************************************************************/
19
20
21 #include "kdenlivedoc.h"
22 #include "docclipbase.h"
23 #include "profilesdialog.h"
24 #include "kdenlivesettings.h"
25 #include "renderer.h"
26 #include "clipmanager.h"
27 #include "titlewidget.h"
28 #include "mainwindow.h"
29 #include "documentchecker.h"
30 #include "documentconvert.h"
31 #include "kdenlive-config.h"
32
33 #include <KDebug>
34 #include <KStandardDirs>
35 #include <KMessageBox>
36 #include <KLocale>
37 #include <KFileDialog>
38 #include <KIO/NetAccess>
39 #include <KIO/CopyJob>
40 #include <KApplication>
41
42 #include <QCryptographicHash>
43 #include <QFile>
44
45 #include <mlt++/Mlt.h>
46
47 const double DOCUMENTVERSION = 0.83;
48
49 KdenliveDoc::KdenliveDoc(const KUrl &url, const KUrl &projectFolder, QUndoGroup *undoGroup, const QString &profileName, const QPoint tracks, Render *render, MainWindow *parent) :
50         QObject(parent),
51         m_autosave(NULL),
52         m_url(url),
53         m_zoom(7),
54         m_startPos(0),
55         m_render(render),
56         m_commandStack(new QUndoStack(undoGroup)),
57         m_modified(false),
58         m_projectFolder(projectFolder),
59         m_documentLoadingStep(0.0),
60         m_documentLoadingProgress(0),
61         m_abortLoading(false),
62         m_zoneStart(0),
63         m_zoneEnd(100)
64 {
65     m_clipManager = new ClipManager(this);
66     m_autoSaveTimer = new QTimer(this);
67     m_autoSaveTimer->setSingleShot(true);
68     if (!url.isEmpty()) {
69         QString tmpFile;
70         bool success = KIO::NetAccess::download(url.path(), tmpFile, parent);
71         if (success) {
72             QFile file(tmpFile);
73             QString errorMsg;
74             success = m_document.setContent(&file, false, &errorMsg);
75             file.close();
76             if (success == false) {
77                 // File is corrupted, warn user
78                 KMessageBox::error(parent, errorMsg);
79             }
80         } else KMessageBox::error(parent, KIO::NetAccess::lastErrorString());
81
82         if (success) {
83             QDomNode infoXmlNode = m_document.elementsByTagName("kdenlivedoc").at(0);
84             if (!infoXmlNode.isNull()) {
85                 QDomElement infoXml = infoXmlNode.toElement();
86                 double version = infoXml.attribute("version").toDouble();
87
88                 // Upgrade old Kdenlive documents to current version
89                 DocumentConvert converter(m_document);
90                 if (!converter.doConvert(version, DOCUMENTVERSION)) {
91                     m_url.clear();
92                     m_document = createEmptyDocument(tracks.x(), tracks.y());
93                     setProfilePath(profileName);
94                 } else {
95                     /*
96                      * read again <kdenlivedoc> and <mlt> to get all the new
97                      * stuff (convertDocument() can now do anything without breaking
98                      * document loading)
99                      */
100                     setModified(converter.isModified());
101                     infoXmlNode = m_document.elementsByTagName("kdenlivedoc").at(0);
102                     infoXml = infoXmlNode.toElement();
103                     version = infoXml.attribute("version").toDouble();
104                     QDomNode mlt = m_document.elementsByTagName("mlt").at(0);
105
106                     QString profilePath = infoXml.attribute("profile");
107                     QString projectFolderPath = infoXml.attribute("projectfolder");
108                     if (!projectFolderPath.isEmpty()) m_projectFolder = KUrl(projectFolderPath);
109
110                     if (m_projectFolder.isEmpty() || !KIO::NetAccess::exists(m_projectFolder.path(), KIO::NetAccess::DestinationSide, parent)) {
111                         // Make sure the project folder is usable
112                         KMessageBox::information(parent, i18n("Document project folder is invalid, setting it to the default one: %1", KdenliveSettings::defaultprojectfolder()));
113                         m_projectFolder = KUrl(KdenliveSettings::defaultprojectfolder());
114                     }
115                     m_startPos = infoXml.attribute("position").toInt();
116                     m_zoom = infoXml.attribute("zoom", "7").toInt();
117                     m_zoneStart = infoXml.attribute("zonein", "0").toInt();
118                     m_zoneEnd = infoXml.attribute("zoneout", "100").toInt();
119                     setProfilePath(profilePath);
120
121                     // Build tracks
122                     QDomElement e;
123                     QDomNode tracksinfo = m_document.elementsByTagName("tracksinfo").at(0);
124                     TrackInfo projectTrack;
125                     if (!tracksinfo.isNull()) {
126                         QDomNodeList trackslist = tracksinfo.childNodes();
127                         int maxchild = trackslist.count();
128                         for (int k = 0; k < maxchild; k++) {
129                             e = trackslist.at(k).toElement();
130                             if (e.tagName() == "trackinfo") {
131                                 if (e.attribute("type") == "audio") projectTrack.type = AUDIOTRACK;
132                                 else projectTrack.type = VIDEOTRACK;
133                                 projectTrack.isMute = e.attribute("mute").toInt();
134                                 projectTrack.isBlind = e.attribute("blind").toInt();
135                                 projectTrack.isLocked = e.attribute("locked").toInt();
136                                 m_tracksList.append(projectTrack);
137                             }
138                         }
139                         mlt.removeChild(tracksinfo);
140                     }
141                     QDomNodeList producers = m_document.elementsByTagName("producer");
142                     QDomNodeList infoproducers = m_document.elementsByTagName("kdenlive_producer");
143                     if (checkDocumentClips(producers, infoproducers) == false) m_abortLoading = true;
144                     const int max = producers.count();
145                     const int infomax = infoproducers.count();
146
147                     QDomNodeList folders = m_document.elementsByTagName("folder");
148                     for (int i = 0; i < folders.count(); i++) {
149                         e = folders.item(i).cloneNode().toElement();
150                         m_clipManager->addFolder(e.attribute("id"), e.attribute("name"));
151                     }
152
153                     if (max > 0) {
154                         m_documentLoadingStep = 100.0 / (max + infomax + m_document.elementsByTagName("entry").count());
155                         parent->slotGotProgressInfo(i18n("Loading project clips"), (int) m_documentLoadingProgress);
156                     }
157
158
159                     for (int i = 0; i < infomax && !m_abortLoading; i++) {
160                         e = infoproducers.item(i).cloneNode().toElement();
161                         if (m_documentLoadingStep > 0) {
162                             m_documentLoadingProgress += m_documentLoadingStep;
163                             parent->slotGotProgressInfo(QString(), (int) m_documentLoadingProgress);
164                             //qApp->processEvents();
165                         }
166                         QString prodId = e.attribute("id");
167                         if (!e.isNull() && prodId != "black" && !prodId.startsWith("slowmotion") && !m_abortLoading) {
168                             e.setTagName("producer");
169                             // Get MLT's original producer properties
170                             QDomElement orig;
171                             for (int j = 0; j < max; j++) {
172                                 QDomElement o = producers.item(j).cloneNode().toElement();
173                                 QString origId = o.attribute("id").section('_', 0, 0);
174                                 if (origId == prodId) {
175                                     orig = o;
176                                     break;
177                                 }
178                             }
179                             addClipInfo(e, orig, prodId);
180                             kDebug() << "// NLIVE PROD: " << prodId;
181                         }
182                     }
183                     if (m_abortLoading) {
184                         //parent->slotGotProgressInfo(i18n("File %1 is not a Kdenlive project file."), 100);
185                         emit resetProjectList();
186                         m_startPos = 0;
187                         m_url = KUrl();
188                         m_tracksList.clear();
189                         kWarning() << "Aborted loading of: " << url.path();
190                         m_document = createEmptyDocument(KdenliveSettings::videotracks(), KdenliveSettings::audiotracks());
191                         setProfilePath(KdenliveSettings::default_profile());
192                         m_clipManager->clear();
193                     } else {
194                         QDomNode markers = m_document.elementsByTagName("markers").at(0);
195                         if (!markers.isNull()) {
196                             QDomNodeList markerslist = markers.childNodes();
197                             int maxchild = markerslist.count();
198                             for (int k = 0; k < maxchild; k++) {
199                                 e = markerslist.at(k).toElement();
200                                 if (e.tagName() == "marker") {
201                                     m_clipManager->getClipById(e.attribute("id"))->addSnapMarker(GenTime(e.attribute("time").toDouble()), e.attribute("comment"));
202                                 }
203                             }
204                             mlt.removeChild(markers);
205                         }
206                         m_document.removeChild(infoXmlNode);
207                         kDebug() << "Reading file: " << url.path() << ", found clips: " << producers.count();
208                     }
209                 }
210             } else {
211                 parent->slotGotProgressInfo(i18n("File %1 is not a Kdenlive project file."), 100);
212                 kWarning() << "  NO KDENLIVE INFO FOUND IN FILE: " << url.path();
213                 m_document = createEmptyDocument(KdenliveSettings::videotracks(), KdenliveSettings::audiotracks());
214                 m_url = KUrl();
215                 setProfilePath(KdenliveSettings::default_profile());
216             }
217             KIO::NetAccess::removeTempFile(tmpFile);
218         } else {
219             parent->slotGotProgressInfo(i18n("File %1 is not a Kdenlive project file."), 100);
220             m_url = KUrl();
221             m_document = createEmptyDocument(KdenliveSettings::videotracks(), KdenliveSettings::audiotracks());
222             setProfilePath(KdenliveSettings::default_profile());
223         }
224     } else {
225         m_document = createEmptyDocument(tracks.x(), tracks.y());
226         setProfilePath(profileName);
227     }
228     if (m_projectFolder.isEmpty()) m_projectFolder = KUrl(KdenliveSettings::defaultprojectfolder());
229
230     // make sure that the necessary folders exist
231     KStandardDirs::makeDir(m_projectFolder.path() + "/titles/");
232     KStandardDirs::makeDir(m_projectFolder.path() + "/thumbs/");
233     KStandardDirs::makeDir(m_projectFolder.path() + "/ladspa/");
234
235     kDebug() << "KDEnlive document, init timecode: " << m_fps;
236     if (m_fps == 30000.0 / 1001.0) m_timecode.setFormat(30, true);
237     else m_timecode.setFormat((int) m_fps);
238
239     //kDebug() << "// SETTING SCENE LIST:\n\n" << m_document.toString();
240     connect(m_autoSaveTimer, SIGNAL(timeout()), this, SLOT(slotAutoSave()));
241
242 }
243
244 KdenliveDoc::~KdenliveDoc()
245 {
246     delete m_commandStack;
247     delete m_clipManager;
248     delete m_autoSaveTimer;
249     if (m_autosave) {
250         m_autosave->remove();
251         delete m_autosave;
252     }
253 }
254
255 void KdenliveDoc::setSceneList()
256 {
257     m_render->setSceneList(m_document.toString(), m_startPos);
258     // m_document xml is now useless, clear it
259     m_document.clear();
260     checkProjectClips();
261 }
262
263 QDomDocument KdenliveDoc::createEmptyDocument(const int videotracks, const int audiotracks)
264 {
265     // Creating new document
266     QDomDocument doc;
267     QDomElement mlt = doc.createElement("mlt");
268     doc.appendChild(mlt);
269
270
271     TrackInfo videoTrack;
272     videoTrack.type = VIDEOTRACK;
273     videoTrack.isMute = false;
274     videoTrack.isBlind = false;
275     videoTrack.isLocked = false;
276
277     TrackInfo audioTrack;
278     audioTrack.type = AUDIOTRACK;
279     audioTrack.isMute = false;
280     audioTrack.isBlind = true;
281     audioTrack.isLocked = false;
282
283     QDomElement tractor = doc.createElement("tractor");
284     tractor.setAttribute("id", "maintractor");
285     QDomElement multitrack = doc.createElement("multitrack");
286     QDomElement playlist = doc.createElement("playlist");
287     playlist.setAttribute("id", "black_track");
288     mlt.appendChild(playlist);
289
290
291     // create playlists
292     int total = audiotracks + videotracks + 1;
293
294     for (int i = 1; i < total; i++) {
295         QDomElement playlist = doc.createElement("playlist");
296         playlist.setAttribute("id", "playlist" + QString::number(i));
297         mlt.appendChild(playlist);
298     }
299
300     QDomElement track0 = doc.createElement("track");
301     track0.setAttribute("producer", "black_track");
302     tractor.appendChild(track0);
303
304     // create audio tracks
305     for (int i = 1; i < audiotracks + 1; i++) {
306         QDomElement track = doc.createElement("track");
307         track.setAttribute("producer", "playlist" + QString::number(i));
308         track.setAttribute("hide", "video");
309         tractor.appendChild(track);
310         m_tracksList.append(audioTrack);
311     }
312
313     // create video tracks
314     for (int i = audiotracks + 1; i < total; i++) {
315         QDomElement track = doc.createElement("track");
316         track.setAttribute("producer", "playlist" + QString::number(i));
317         tractor.appendChild(track);
318         m_tracksList.append(videoTrack);
319     }
320
321     for (int i = 2; i < total ; i++) {
322         QDomElement transition = doc.createElement("transition");
323         transition.setAttribute("always_active", "1");
324
325         QDomElement property = doc.createElement("property");
326         property.setAttribute("name", "a_track");
327         QDomText value = doc.createTextNode(QString::number(1));
328         property.appendChild(value);
329         transition.appendChild(property);
330
331         property = doc.createElement("property");
332         property.setAttribute("name", "b_track");
333         value = doc.createTextNode(QString::number(i));
334         property.appendChild(value);
335         transition.appendChild(property);
336
337         property = doc.createElement("property");
338         property.setAttribute("name", "mlt_service");
339         value = doc.createTextNode("mix");
340         property.appendChild(value);
341         transition.appendChild(property);
342
343         property = doc.createElement("property");
344         property.setAttribute("name", "combine");
345         value = doc.createTextNode("1");
346         property.appendChild(value);
347         transition.appendChild(property);
348
349         property = doc.createElement("property");
350         property.setAttribute("name", "internal_added");
351         value = doc.createTextNode("237");
352         property.appendChild(value);
353         transition.appendChild(property);
354         tractor.appendChild(transition);
355     }
356     mlt.appendChild(tractor);
357     return doc;
358 }
359
360
361 void KdenliveDoc::syncGuides(QList <Guide *> guides)
362 {
363     m_guidesXml.clear();
364     QDomElement guideNode = m_guidesXml.createElement("guides");
365     m_guidesXml.appendChild(guideNode);
366     QDomElement e;
367
368     for (int i = 0; i < guides.count(); i++) {
369         e = m_guidesXml.createElement("guide");
370         e.setAttribute("time", guides.at(i)->position().ms() / 1000);
371         e.setAttribute("comment", guides.at(i)->label());
372         guideNode.appendChild(e);
373     }
374     emit guidesUpdated();
375 }
376
377 QDomElement KdenliveDoc::guidesXml() const
378 {
379     return m_guidesXml.documentElement();
380 }
381
382 void KdenliveDoc::slotAutoSave()
383 {
384     if (m_render && m_autosave) {
385         if (!m_autosave->isOpen() && !m_autosave->open(QIODevice::ReadWrite)) {
386             // show error: could not open the autosave file
387             kDebug() << "ERROR; CANNOT CREATE AUTOSAVE FILE";
388         }
389         kDebug() << "// AUTOSAVE FILE: " << m_autosave->fileName();
390         QString doc;
391         if (KdenliveSettings::dropbframes()) {
392             KdenliveSettings::setDropbframes(false);
393             m_clipManager->updatePreviewSettings();
394             doc = m_render->sceneList();
395             KdenliveSettings::setDropbframes(true);
396             m_clipManager->updatePreviewSettings();
397         } else doc = m_render->sceneList();
398         saveSceneList(m_autosave->fileName(), doc);
399     }
400 }
401
402 void KdenliveDoc::setZoom(int factor)
403 {
404     m_zoom = factor;
405 }
406
407 int KdenliveDoc::zoom() const
408 {
409     return m_zoom;
410 }
411
412 void KdenliveDoc::setZone(int start, int end)
413 {
414     m_zoneStart = start;
415     m_zoneEnd = end;
416 }
417
418 QPoint KdenliveDoc::zone() const
419 {
420     return QPoint(m_zoneStart, m_zoneEnd);
421 }
422
423 bool KdenliveDoc::saveSceneList(const QString &path, const QString &scene)
424 {
425     QDomDocument sceneList;
426     sceneList.setContent(scene, true);
427     QDomNode mlt = sceneList.elementsByTagName("mlt").at(0);
428     QDomElement addedXml = sceneList.createElement("kdenlivedoc");
429     mlt.appendChild(addedXml);
430
431     QDomElement markers = sceneList.createElement("markers");
432     addedXml.setAttribute("version", "0.82");
433     addedXml.setAttribute("kdenliveversion", VERSION);
434     addedXml.setAttribute("profile", profilePath());
435     addedXml.setAttribute("position", m_render->seekPosition().frames(m_fps));
436     addedXml.setAttribute("zonein", m_zoneStart);
437     addedXml.setAttribute("zoneout", m_zoneEnd);
438     addedXml.setAttribute("projectfolder", m_projectFolder.path());
439     addedXml.setAttribute("zoom", m_zoom);
440
441     // tracks info
442     QDomElement tracksinfo = sceneList.createElement("tracksinfo");
443     foreach(const TrackInfo &info, m_tracksList) {
444         QDomElement trackinfo = sceneList.createElement("trackinfo");
445         if (info.type == AUDIOTRACK) trackinfo.setAttribute("type", "audio");
446         trackinfo.setAttribute("mute", info.isMute);
447         trackinfo.setAttribute("blind", info.isBlind);
448         trackinfo.setAttribute("locked", info.isLocked);
449         tracksinfo.appendChild(trackinfo);
450     }
451     addedXml.appendChild(tracksinfo);
452
453     // save project folders
454     QMap <QString, QString> folderlist = m_clipManager->documentFolderList();
455
456     QMapIterator<QString, QString> f(folderlist);
457     while (f.hasNext()) {
458         f.next();
459         QDomElement folder = sceneList.createElement("folder");
460         folder.setAttribute("id", f.key());
461         folder.setAttribute("name", f.value());
462         addedXml.appendChild(folder);
463     }
464
465     // Save project clips
466     QDomElement e;
467     QList <DocClipBase*> list = m_clipManager->documentClipList();
468     for (int i = 0; i < list.count(); i++) {
469         e = list.at(i)->toXML();
470         e.setTagName("kdenlive_producer");
471         addedXml.appendChild(sceneList.importNode(e, true));
472         QList < CommentedTime > marks = list.at(i)->commentedSnapMarkers();
473         for (int j = 0; j < marks.count(); j++) {
474             QDomElement marker = sceneList.createElement("marker");
475             marker.setAttribute("time", marks.at(j).time().ms() / 1000);
476             marker.setAttribute("comment", marks.at(j).comment());
477             marker.setAttribute("id", e.attribute("id"));
478             markers.appendChild(marker);
479         }
480     }
481     addedXml.appendChild(markers);
482
483     // Add guides
484     if (!m_guidesXml.isNull()) addedXml.appendChild(sceneList.importNode(m_guidesXml.documentElement(), true));
485
486     // Add clip groups
487     addedXml.appendChild(sceneList.importNode(m_clipManager->groupsXml(), true));
488
489     //wes.appendChild(doc.importNode(kdenliveData, true));
490
491     QFile file(path);
492     if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
493         kWarning() << "//////  ERROR writing to file: " << path;
494         KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1", path));
495         return false;
496     }
497
498     file.write(sceneList.toString().toUtf8());
499     if (file.error() != QFile::NoError) {
500         KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1", path));
501         file.close();
502         return false;
503     }
504     file.close();
505     return true;
506 }
507
508 ClipManager *KdenliveDoc::clipManager()
509 {
510     return m_clipManager;
511 }
512
513 KUrl KdenliveDoc::projectFolder() const
514 {
515     //if (m_projectFolder.isEmpty()) return KUrl(KStandardDirs::locateLocal("appdata", "/projects/"));
516     return m_projectFolder;
517 }
518
519 void KdenliveDoc::setProjectFolder(KUrl url)
520 {
521     if (url == m_projectFolder) return;
522     setModified(true);
523     KStandardDirs::makeDir(url.path());
524     KStandardDirs::makeDir(url.path() + "/titles/");
525     KStandardDirs::makeDir(url.path() + "/thumbs/");
526     if (KMessageBox::questionYesNo(kapp->activeWindow(), i18n("You have changed the project folder. Do you want to copy the cached data from %1 to the new folder %2?").arg(m_projectFolder.path(), url.path())) == KMessageBox::Yes) moveProjectData(url);
527     m_projectFolder = url;
528 }
529
530 void KdenliveDoc::moveProjectData(KUrl url)
531 {
532     QList <DocClipBase*> list = m_clipManager->documentClipList();
533     //TODO: Also move ladspa effects files
534     for (int i = 0; i < list.count(); i++) {
535         DocClipBase *clip = list.at(i);
536         if (clip->clipType() == TEXT) {
537             // the image for title clip must be moved
538             KUrl oldUrl = clip->fileURL();
539             KUrl newUrl = KUrl(url.path() + "/titles/" + oldUrl.fileName());
540             KIO::Job *job = KIO::copy(oldUrl, newUrl);
541             if (KIO::NetAccess::synchronousRun(job, 0)) clip->setProperty("resource", newUrl.path());
542         }
543         QString hash = clip->getClipHash();
544         KUrl oldVideoThumbUrl = KUrl(m_projectFolder.path() + "/thumbs/" + hash + ".png");
545         KUrl oldAudioThumbUrl = KUrl(m_projectFolder.path() + "/thumbs/" + hash + ".thumb");
546         if (KIO::NetAccess::exists(oldVideoThumbUrl, KIO::NetAccess::SourceSide, 0)) {
547             KUrl newUrl = KUrl(url.path() + "/thumbs/" + hash + ".png");
548             KIO::Job *job = KIO::copy(oldVideoThumbUrl, newUrl);
549             KIO::NetAccess::synchronousRun(job, 0);
550         }
551         if (KIO::NetAccess::exists(oldAudioThumbUrl, KIO::NetAccess::SourceSide, 0)) {
552             KUrl newUrl = KUrl(url.path() + "/thumbs/" + hash + ".thumb");
553             KIO::Job *job = KIO::copy(oldAudioThumbUrl, newUrl);
554             if (KIO::NetAccess::synchronousRun(job, 0)) clip->refreshThumbUrl();
555         }
556     }
557 }
558
559 const QString &KdenliveDoc::profilePath() const
560 {
561     return m_profile.path;
562 }
563
564 MltVideoProfile KdenliveDoc::mltProfile() const
565 {
566     return m_profile;
567 }
568
569 void KdenliveDoc::setProfilePath(QString path)
570 {
571     if (path.isEmpty()) path = KdenliveSettings::default_profile();
572     if (path.isEmpty()) path = "dv_pal";
573     m_profile = ProfilesDialog::getVideoProfile(path);
574     KdenliveSettings::setProject_display_ratio((double) m_profile.display_aspect_num / m_profile.display_aspect_den);
575     m_fps = (double) m_profile.frame_rate_num / m_profile.frame_rate_den;
576     KdenliveSettings::setProject_fps(m_fps);
577     m_width = m_profile.width;
578     m_height = m_profile.height;
579     kDebug() << "KDEnnlive document, init timecode from path: " << path << ",  " << m_fps;
580     if (m_fps == 30000.0 / 1001.0) m_timecode.setFormat(30, true);
581     else m_timecode.setFormat((int) m_fps);
582 }
583
584 double KdenliveDoc::dar()
585 {
586     return (double) m_profile.display_aspect_num / m_profile.display_aspect_den;
587 }
588
589 void KdenliveDoc::setThumbsProgress(const QString &message, int progress)
590 {
591     emit progressInfo(message, progress);
592 }
593
594 void KdenliveDoc::loadingProgressed()
595 {
596     m_documentLoadingProgress += m_documentLoadingStep;
597     emit progressInfo(QString(), (int) m_documentLoadingProgress);
598 }
599
600 QUndoStack *KdenliveDoc::commandStack()
601 {
602     return m_commandStack;
603 }
604
605 /*
606 void KdenliveDoc::setRenderer(Render *render) {
607     if (m_render) return;
608     m_render = render;
609     emit progressInfo(i18n("Loading playlist..."), 0);
610     //qApp->processEvents();
611     if (m_render) {
612         m_render->setSceneList(m_document.toString(), m_startPos);
613         kDebug() << "// SETTING SCENE LIST:\n\n" << m_document.toString();
614         checkProjectClips();
615     }
616     emit progressInfo(QString(), -1);
617 }*/
618
619 void KdenliveDoc::checkProjectClips()
620 {
621     kDebug() << "+++++++++++++ + + + + CHK PCLIPS";
622     if (m_render == NULL) return;
623     m_clipManager->resetProducersList(m_render->producersList());
624     return;
625
626     // Useless now...
627     QList <Mlt::Producer *> prods = m_render->producersList();
628     QString id ;
629     QString prodId ;
630     QString prodTrack ;
631     for (int i = 0; i < prods.count(); i++) {
632         id = prods.at(i)->get("id");
633         prodId = id.section('_', 0, 0);
634         prodTrack = id.section('_', 1, 1);
635         DocClipBase *clip = m_clipManager->getClipById(prodId);
636         if (clip) clip->setProducer(prods.at(i));
637         if (clip && clip->clipType() == TEXT && !QFile::exists(clip->fileURL().path())) {
638             // regenerate text clip image if required
639             //kDebug() << "// TITLE: " << clip->getProperty("titlename") << " Preview file: " << clip->getProperty("resource") << " DOES NOT EXIST";
640             QString titlename = clip->getProperty("name");
641             QString titleresource;
642             if (titlename.isEmpty()) {
643                 QStringList titleInfo = TitleWidget::getFreeTitleInfo(projectFolder());
644                 titlename = titleInfo.at(0);
645                 titleresource = titleInfo.at(1);
646                 clip->setProperty("name", titlename);
647                 kDebug() << "// New title set to: " << titlename;
648             } else {
649                 titleresource = TitleWidget::getFreeTitleInfo(projectFolder()).at(1);
650                 //titleresource = TitleWidget::getTitleResourceFromName(projectFolder(), titlename);
651             }
652             TitleWidget *dia_ui = new TitleWidget(KUrl(), KUrl(titleresource).directory(), m_render, kapp->activeWindow());
653             QDomDocument doc;
654             doc.setContent(clip->getProperty("xmldata"));
655             dia_ui->setXml(doc);
656             QImage pix = dia_ui->renderedPixmap();
657             pix.save(titleresource);
658             clip->setProperty("resource", titleresource);
659             delete dia_ui;
660             clip->producer()->set("force_reload", 1);
661         }
662     }
663 }
664
665 void KdenliveDoc::updatePreviewSettings()
666 {
667     m_clipManager->updatePreviewSettings();
668     m_render->updatePreviewSettings();
669     m_clipManager->resetProducersList(m_render->producersList());
670
671 }
672
673 Render *KdenliveDoc::renderer()
674 {
675     return m_render;
676 }
677
678 void KdenliveDoc::updateClip(const QString &id)
679 {
680     emit updateClipDisplay(id);
681 }
682
683 int KdenliveDoc::getFramePos(QString duration)
684 {
685     return m_timecode.getFrameCount(duration, m_fps);
686 }
687
688 QString KdenliveDoc::producerName(const QString &id)
689 {
690     QString result = "unnamed";
691     QDomNodeList prods = producersList();
692     int ct = prods.count();
693     for (int i = 0; i <  ct ; i++) {
694         QDomElement e = prods.item(i).toElement();
695         if (e.attribute("id") != "black" && e.attribute("id") == id) {
696             result = e.attribute("name");
697             if (result.isEmpty()) result = KUrl(e.attribute("resource")).fileName();
698             break;
699         }
700     }
701     return result;
702 }
703
704 QDomDocument KdenliveDoc::toXml()
705 {
706     return m_document;
707 }
708
709 Timecode KdenliveDoc::timecode() const
710 {
711     return m_timecode;
712 }
713
714 QDomNodeList KdenliveDoc::producersList()
715 {
716     return m_document.elementsByTagName("producer");
717 }
718
719 double KdenliveDoc::projectDuration() const
720 {
721     if (m_render)
722         return GenTime(m_render->getLength(), m_fps).ms() / 1000;
723     else
724         return 0;
725 }
726
727 double KdenliveDoc::fps() const
728 {
729     return m_fps;
730 }
731
732 int KdenliveDoc::width() const
733 {
734     return m_width;
735 }
736
737 int KdenliveDoc::height() const
738 {
739     return m_height;
740 }
741
742 KUrl KdenliveDoc::url() const
743 {
744     return m_url;
745 }
746
747 void KdenliveDoc::setUrl(KUrl url)
748 {
749     m_url = url;
750 }
751
752 void KdenliveDoc::setModified(bool mod)
753 {
754     if (!m_url.isEmpty() && mod && KdenliveSettings::crashrecovery()) {
755         m_autoSaveTimer->start(3000);
756     }
757     if (mod == m_modified) return;
758     m_modified = mod;
759     emit docModified(m_modified);
760 }
761
762 bool KdenliveDoc::isModified() const
763 {
764     return m_modified;
765 }
766
767 const QString KdenliveDoc::description() const
768 {
769     if (m_url.isEmpty())
770         return i18n("Untitled") + " / " + m_profile.description;
771     else
772         return m_url.fileName() + " / " + m_profile.description;
773 }
774
775 void KdenliveDoc::addClip(QDomElement elem, QString clipId, bool createClipItem)
776 {
777     const QString producerId = clipId.section('_', 0, 0);
778     DocClipBase *clip = m_clipManager->getClipById(producerId);
779
780     if (clip == NULL) {
781         elem.setAttribute("id", producerId);
782         QString path = elem.attribute("resource");
783         QString extension;
784         if (elem.attribute("type").toInt() == SLIDESHOW) {
785             extension = KUrl(path).fileName();
786             path = KUrl(path).directory();
787         } else if (elem.attribute("type").toInt() == TEXT && QFile::exists(path) == false) {
788             kDebug() << "// TITLE: " << elem.attribute("name") << " Preview file: " << elem.attribute("resource") << " DOES NOT EXIST";
789             QString titlename = elem.attribute("name");
790             QString titleresource;
791             if (titlename.isEmpty()) {
792                 QStringList titleInfo = TitleWidget::getFreeTitleInfo(projectFolder());
793                 titlename = titleInfo.at(0);
794                 titleresource = titleInfo.at(1);
795                 elem.setAttribute("name", titlename);
796                 kDebug() << "// New title set to: " << titlename;
797             } else {
798                 titleresource = TitleWidget::getFreeTitleInfo(projectFolder()).at(1);
799                 //titleresource = TitleWidget::getTitleResourceFromName(projectFolder(), titlename);
800             }
801             TitleWidget *dia_ui = new TitleWidget(KUrl(), KUrl(titleresource).directory(), m_render, kapp->activeWindow());
802             QDomDocument doc;
803             doc.setContent(elem.attribute("xmldata"));
804             dia_ui->setXml(doc);
805             QImage pix = dia_ui->renderedPixmap();
806             pix.save(titleresource);
807             elem.setAttribute("resource", titleresource);
808             setNewClipResource(clipId, titleresource);
809             delete dia_ui;
810         }
811
812         if (path.isEmpty() == false && QFile::exists(path) == false && elem.attribute("type").toInt() != TEXT && !elem.hasAttribute("placeholder")) {
813             kDebug() << "// FOUND MISSING CLIP: " << path << ", TYPE: " << elem.attribute("type").toInt();
814             const QString size = elem.attribute("file_size");
815             const QString hash = elem.attribute("file_hash");
816             QString newpath;
817             int action = KMessageBox::No;
818             if (!size.isEmpty() && !hash.isEmpty()) {
819                 if (!m_searchFolder.isEmpty()) newpath = searchFileRecursively(m_searchFolder, size, hash);
820                 else action = (KMessageBox::ButtonCode) KMessageBox::questionYesNoCancel(kapp->activeWindow(), i18n("Clip <b>%1</b><br>is invalid, what do you want to do?", path), i18n("File not found"), KGuiItem(i18n("Search automatically")), KGuiItem(i18n("Keep as placeholder")));
821             } else {
822                 if (elem.attribute("type").toInt() == SLIDESHOW) {
823                     int res = KMessageBox::questionYesNoCancel(kapp->activeWindow(), i18n("Clip <b>%1</b><br>is invalid or missing, what do you want to do?", path), i18n("File not found"), KGuiItem(i18n("Search manually")), KGuiItem(i18n("Keep as placeholder")));
824                     if (res == KMessageBox::Yes)
825                         newpath = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow(), i18n("Looking for %1", path));
826                     else {
827                         // Abort project loading
828                         action = res;
829                     }
830                 } else {
831                     int res = KMessageBox::questionYesNoCancel(kapp->activeWindow(), i18n("Clip <b>%1</b><br>is invalid or missing, what do you want to do?", path), i18n("File not found"), KGuiItem(i18n("Search manually")), KGuiItem(i18n("Keep as placeholder")));
832                     if (res == KMessageBox::Yes)
833                         newpath = KFileDialog::getOpenFileName(KUrl("kfiledialog:///clipfolder"), QString(), kapp->activeWindow(), i18n("Looking for %1", path));
834                     else {
835                         // Abort project loading
836                         action = res;
837                     }
838                 }
839             }
840             if (action == KMessageBox::Yes) {
841                 kDebug() << "// ASKED FOR SRCH CLIP: " << clipId;
842                 m_searchFolder = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow());
843                 if (!m_searchFolder.isEmpty()) {
844                     newpath = searchFileRecursively(QDir(m_searchFolder), size, hash);
845                 }
846             } else if (action == KMessageBox::Cancel) {
847                 m_abortLoading = true;
848                 return;
849             } else if (action == KMessageBox::No) {
850                 // Keep clip as placeHolder
851                 elem.setAttribute("placeholder", '1');
852             }
853             if (!newpath.isEmpty()) {
854                 if (elem.attribute("type").toInt() == SLIDESHOW) newpath.append('/' + extension);
855                 elem.setAttribute("resource", newpath);
856                 setNewClipResource(clipId, newpath);
857                 setModified(true);
858             }
859         }
860         clip = new DocClipBase(m_clipManager, elem, producerId);
861         m_clipManager->addClip(clip);
862     }
863
864     if (createClipItem) {
865         emit addProjectClip(clip);
866         qApp->processEvents();
867         m_render->getFileProperties(clip->toXML(), clip->getId());
868     }
869 }
870
871
872 void KdenliveDoc::setNewClipResource(const QString &id, const QString &path)
873 {
874     QDomNodeList prods = m_document.elementsByTagName("producer");
875     int maxprod = prods.count();
876     for (int i = 0; i < maxprod; i++) {
877         QDomNode m = prods.at(i);
878         QString prodId = m.toElement().attribute("id");
879         if (prodId == id || prodId.startsWith(id + '_')) {
880             QDomNodeList params = m.childNodes();
881             for (int j = 0; j < params.count(); j++) {
882                 QDomElement e = params.item(j).toElement();
883                 if (e.attribute("name") == "resource") {
884                     e.firstChild().setNodeValue(path);
885                     break;
886                 }
887             }
888         }
889     }
890 }
891
892 QString KdenliveDoc::searchFileRecursively(const QDir &dir, const QString &matchSize, const QString &matchHash) const
893 {
894     QString foundFileName;
895     QByteArray fileData;
896     QByteArray fileHash;
897     QStringList filesAndDirs = dir.entryList(QDir::Files | QDir::Readable);
898     for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
899         QFile file(dir.absoluteFilePath(filesAndDirs.at(i)));
900         if (file.open(QIODevice::ReadOnly)) {
901             if (QString::number(file.size()) == matchSize) {
902                 /*
903                 * 1 MB = 1 second per 450 files (or faster)
904                 * 10 MB = 9 seconds per 450 files (or faster)
905                 */
906                 if (file.size() > 1000000*2) {
907                     fileData = file.read(1000000);
908                     if (file.seek(file.size() - 1000000))
909                         fileData.append(file.readAll());
910                 } else
911                     fileData = file.readAll();
912                 file.close();
913                 fileHash = QCryptographicHash::hash(fileData, QCryptographicHash::Md5);
914                 if (QString(fileHash.toHex()) == matchHash)
915                     return file.fileName();
916             }
917         }
918         kDebug() << filesAndDirs.at(i) << file.size() << fileHash.toHex();
919     }
920     filesAndDirs = dir.entryList(QDir::Dirs | QDir::Readable | QDir::Executable | QDir::NoDotAndDotDot);
921     for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
922         foundFileName = searchFileRecursively(dir.absoluteFilePath(filesAndDirs.at(i)), matchSize, matchHash);
923         if (!foundFileName.isEmpty())
924             break;
925     }
926     return foundFileName;
927 }
928
929 void KdenliveDoc::addClipInfo(QDomElement elem, QDomElement orig, QString clipId)
930 {
931     DocClipBase *clip = m_clipManager->getClipById(clipId);
932     if (clip == NULL) {
933         addClip(elem, clipId, false);
934     } else {
935         QMap <QString, QString> properties;
936         QDomNamedNodeMap attributes = elem.attributes();
937         QString attrname;
938         for (int i = 0; i < attributes.count(); i++) {
939             attrname = attributes.item(i).nodeName();
940             if (attrname != "resource")
941                 properties.insert(attrname, attributes.item(i).nodeValue());
942             kDebug() << attrname << " = " << attributes.item(i).nodeValue();
943         }
944         clip->setProperties(properties);
945         emit addProjectClip(clip, false);
946     }
947     if (orig != QDomElement()) {
948         QMap<QString, QString> meta;
949         QDomNode m = orig.firstChild();
950         while (!m.isNull()) {
951             QString name = m.toElement().attribute("name");
952             if (name.startsWith("meta.attr")) {
953                 meta.insert(name.section('.', 2, 3), m.firstChild().nodeValue());
954             }
955             m = m.nextSibling();
956         }
957         if (!meta.isEmpty()) {
958             if (clip == NULL) clip = m_clipManager->getClipById(clipId);
959             if (clip) clip->setMetadata(meta);
960         }
961     }
962 }
963
964 void KdenliveDoc::deleteProjectClip(QList <QString> ids)
965 {
966     for (int i = 0; i < ids.size(); ++i) {
967         emit deleteTimelineClip(ids.at(i));
968         m_clipManager->slotDeleteClip(ids.at(i));
969     }
970     setModified(true);
971 }
972
973 void KdenliveDoc::deleteClip(const QString &clipId)
974 {
975     emit signalDeleteProjectClip(clipId);
976     m_clipManager->deleteClip(clipId);
977 }
978
979 void KdenliveDoc::slotAddClipList(const KUrl::List urls, const QString group, const QString &groupId)
980 {
981     m_clipManager->slotAddClipList(urls, group, groupId);
982     emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
983     setModified(true);
984 }
985
986
987 void KdenliveDoc::slotAddClipFile(const KUrl url, const QString group, const QString &groupId)
988 {
989     //kDebug() << "/////////  DOCUM, ADD CLP: " << url;
990     m_clipManager->slotAddClipFile(url, group, groupId);
991     emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
992     setModified(true);
993 }
994
995 const QString KdenliveDoc::getFreeClipId()
996 {
997     return QString::number(m_clipManager->getFreeClipId());
998 }
999
1000 DocClipBase *KdenliveDoc::getBaseClip(const QString &clipId)
1001 {
1002     return m_clipManager->getClipById(clipId);
1003 }
1004
1005 void KdenliveDoc::slotCreateTextClip(QString /*group*/, const QString &/*groupId*/)
1006 {
1007     QString titlesFolder = projectFolder().path() + "/titles/";
1008     KStandardDirs::makeDir(titlesFolder);
1009     TitleWidget *dia_ui = new TitleWidget(KUrl(), titlesFolder, m_render, kapp->activeWindow());
1010     if (dia_ui->exec() == QDialog::Accepted) {
1011         QStringList titleInfo = TitleWidget::getFreeTitleInfo(projectFolder());
1012         QImage pix = dia_ui->renderedPixmap();
1013         pix.save(titleInfo.at(1));
1014         //dia_ui->saveTitle(path + ".kdenlivetitle");
1015         m_clipManager->slotAddTextClipFile(titleInfo.at(0), titleInfo.at(1), dia_ui->xml().toString(), QString(), QString());
1016         setModified(true);
1017     }
1018     delete dia_ui;
1019 }
1020
1021 int KdenliveDoc::tracksCount() const
1022 {
1023     return m_tracksList.count();
1024 }
1025
1026 TrackInfo KdenliveDoc::trackInfoAt(int ix) const
1027 {
1028     return m_tracksList.at(ix);
1029 }
1030
1031 void KdenliveDoc::switchTrackAudio(int ix, bool hide)
1032 {
1033     m_tracksList[ix].isMute = hide; // !m_tracksList.at(ix).isMute;
1034 }
1035
1036 void KdenliveDoc::switchTrackLock(int ix, bool lock)
1037 {
1038     m_tracksList[ix].isLocked = lock;
1039 }
1040
1041 bool KdenliveDoc::isTrackLocked(int ix) const
1042 {
1043     return m_tracksList.at(ix).isLocked;
1044 }
1045
1046 void KdenliveDoc::switchTrackVideo(int ix, bool hide)
1047 {
1048     m_tracksList[ix].isBlind = hide; // !m_tracksList.at(ix).isBlind;
1049 }
1050
1051 void KdenliveDoc::insertTrack(int ix, TrackInfo type)
1052 {
1053     if (ix == -1) m_tracksList << type;
1054     else m_tracksList.insert(ix, type);
1055 }
1056
1057 void KdenliveDoc::deleteTrack(int ix)
1058 {
1059     m_tracksList.removeAt(ix);
1060 }
1061
1062 void KdenliveDoc::setTrackType(int ix, TrackInfo type)
1063 {
1064     m_tracksList[ix].type = type.type;
1065     m_tracksList[ix].isMute = type.isMute;
1066     m_tracksList[ix].isBlind = type.isBlind;
1067     m_tracksList[ix].isLocked = type.isLocked;
1068 }
1069
1070 const QList <TrackInfo> KdenliveDoc::tracksList() const
1071 {
1072     return m_tracksList;
1073 }
1074
1075 QPoint KdenliveDoc::getTracksCount() const
1076 {
1077     int audio = 0;
1078     int video = 0;
1079     foreach(const TrackInfo &info, m_tracksList) {
1080         if (info.type == VIDEOTRACK) video++;
1081         else audio++;
1082     }
1083     return QPoint(video, audio);
1084 }
1085
1086 void KdenliveDoc::cachePixmap(const QString &fileId, const QPixmap &pix) const
1087 {
1088     pix.save(m_projectFolder.path() + "/thumbs/" + fileId + ".png");
1089 }
1090
1091 QString KdenliveDoc::getLadspaFile() const
1092 {
1093     int ct = 0;
1094     QString counter = QString::number(ct).rightJustified(5, '0', false);
1095     while (QFile::exists(m_projectFolder.path() + "/ladspa/" + counter + ".ladspa")) {
1096         ct++;
1097         counter = QString::number(ct).rightJustified(5, '0', false);
1098     }
1099     return m_projectFolder.path() + "/ladspa/" + counter + ".ladspa";
1100 }
1101
1102 bool KdenliveDoc::checkDocumentClips(QDomNodeList producers, QDomNodeList infoproducers)
1103 {
1104     int clipType;
1105     QDomElement e;
1106     QString id;
1107     QString resource;
1108     QList <QDomElement> missingClips;
1109     for (int i = 0; i < infoproducers.count(); i++) {
1110         e = infoproducers.item(i).toElement();
1111         clipType = e.attribute("type").toInt();
1112         if (clipType == TEXT || clipType == COLOR) continue;
1113         id = e.attribute("id");
1114         resource = e.attribute("resource");
1115         if (clipType == SLIDESHOW) resource = KUrl(resource).directory();
1116         if (!KIO::NetAccess::exists(KUrl(resource), KIO::NetAccess::SourceSide, 0)) {
1117             // Missing clip found
1118             missingClips.append(e);
1119         }
1120     }
1121     if (missingClips.isEmpty()) return true;
1122     DocumentChecker d(producers, infoproducers, missingClips, m_document);
1123     return (d.exec() == QDialog::Accepted);
1124 }
1125
1126
1127 #include "kdenlivedoc.moc"
1128