]> git.sesse.net Git - kdenlive/blob - src/kdenlivedoc.cpp
Save project profile in Kdenlive document (makes it easier to move from one computer...
[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 "documentvalidator.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, 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     bool success = false;
69     if (!url.isEmpty()) {
70         QString tmpFile;
71         success = KIO::NetAccess::download(url.path(), tmpFile, parent);
72         if (!success) // The file cannot be opened
73             KMessageBox::error(parent, KIO::NetAccess::lastErrorString());
74         else {
75             QFile file(tmpFile);
76             QString errorMsg;
77             success = m_document.setContent(&file, false, &errorMsg);
78             file.close();
79             KIO::NetAccess::removeTempFile(tmpFile);
80             if (!success) // It is corrupted
81                 KMessageBox::error(parent, errorMsg);
82             else {
83                 DocumentValidator validator(m_document);
84                 success = validator.isProject();
85                 if (!success) // It is not a project file
86                     parent->slotGotProgressInfo(i18n("File %1 is not a Kdenlive project file.", m_url.path()), 100);
87                 else {
88                     /*
89                      * Validate the file against the current version (upgrade
90                      * and recover it if needed). It is NOT a passive operation
91                      */
92                     // TODO: backup the document or alert the user?
93                     success = validator.validate(DOCUMENTVERSION);
94                     if (success) { // Let the validator handle error messages
95                         setModified(validator.isModified());
96                         QDomElement mlt = m_document.firstChildElement("mlt");
97                         QDomElement infoXml = mlt.firstChildElement("kdenlivedoc");
98
99                         profileName = infoXml.attribute("profile");
100                         m_projectFolder = infoXml.attribute("projectfolder");
101
102                         m_startPos = infoXml.attribute("position").toInt();
103                         m_zoom = infoXml.attribute("zoom", "7").toInt();
104                         m_zoneStart = infoXml.attribute("zonein", "0").toInt();
105                         m_zoneEnd = infoXml.attribute("zoneout", "100").toInt();
106
107                         // Build tracks
108                         QDomElement e;
109                         QDomElement tracksinfo = infoXml.firstChildElement("tracksinfo");
110                         TrackInfo projectTrack;
111                         if (!tracksinfo.isNull()) {
112                             QDomNodeList trackslist = tracksinfo.childNodes();
113                             int maxchild = trackslist.count();
114                             for (int k = 0; k < maxchild; k++) {
115                                 e = trackslist.at(k).toElement();
116                                 if (e.tagName() == "trackinfo") {
117                                     if (e.attribute("type") == "audio") projectTrack.type = AUDIOTRACK;
118                                     else projectTrack.type = VIDEOTRACK;
119                                     projectTrack.isMute = e.attribute("mute").toInt();
120                                     projectTrack.isBlind = e.attribute("blind").toInt();
121                                     projectTrack.isLocked = e.attribute("locked").toInt();
122                                     m_tracksList.append(projectTrack);
123                                 }
124                             }
125                             mlt.removeChild(tracksinfo);
126                         }
127                         QDomNodeList producers = m_document.elementsByTagName("producer");
128                         QDomNodeList infoproducers = m_document.elementsByTagName("kdenlive_producer");
129                         if (checkDocumentClips(infoproducers) == false) m_abortLoading = true;
130                         const int max = producers.count();
131                         const int infomax = infoproducers.count();
132
133                         QDomNodeList folders = m_document.elementsByTagName("folder");
134                         for (int i = 0; i < folders.count(); i++) {
135                             e = folders.item(i).cloneNode().toElement();
136                             m_clipManager->addFolder(e.attribute("id"), e.attribute("name"));
137                         }
138
139                         if (max > 0) {
140                             m_documentLoadingStep = 100.0 / (max + infomax + m_document.elementsByTagName("entry").count());
141                             parent->slotGotProgressInfo(i18n("Loading project clips"), (int) m_documentLoadingProgress);
142                         }
143
144
145                         for (int i = 0; i < infomax && !m_abortLoading; i++) {
146                             e = infoproducers.item(i).cloneNode().toElement();
147                             if (m_documentLoadingStep > 0) {
148                                 m_documentLoadingProgress += m_documentLoadingStep;
149                                 parent->slotGotProgressInfo(QString(), (int) m_documentLoadingProgress);
150                                 //qApp->processEvents();
151                             }
152                             QString prodId = e.attribute("id");
153                             if (!e.isNull() && prodId != "black" && !prodId.startsWith("slowmotion") && !m_abortLoading) {
154                                 e.setTagName("producer");
155                                 // Get MLT's original producer properties
156                                 QDomElement orig;
157                                 for (int j = 0; j < max; j++) {
158                                     QDomElement o = producers.item(j).cloneNode().toElement();
159                                     QString origId = o.attribute("id").section('_', 0, 0);
160                                     if (origId == prodId) {
161                                         orig = o;
162                                         break;
163                                     }
164                                 }
165                                 addClipInfo(e, orig, prodId);
166                                 kDebug() << "// KDENLIVE PRODUCER: " << prodId;
167                             }
168                         }
169                         if (m_abortLoading) {
170                             //parent->slotGotProgressInfo(i18n("File %1 is not a Kdenlive project file."), 100);
171                             emit resetProjectList();
172                             m_startPos = 0;
173                             m_url = KUrl();
174                             m_tracksList.clear();
175                             kWarning() << "Aborted loading of: " << url.path();
176                             m_document = createEmptyDocument(KdenliveSettings::videotracks(), KdenliveSettings::audiotracks());
177                             setProfilePath(KdenliveSettings::default_profile());
178                             m_clipManager->clear();
179                         } else {
180                             QDomElement markers = infoXml.firstChildElement("markers");
181                             if (!markers.isNull()) {
182                                 QDomNodeList markerslist = markers.childNodes();
183                                 int maxchild = markerslist.count();
184                                 for (int k = 0; k < maxchild; k++) {
185                                     e = markerslist.at(k).toElement();
186                                     if (e.tagName() == "marker") {
187                                         m_clipManager->getClipById(e.attribute("id"))->addSnapMarker(GenTime(e.attribute("time").toDouble()), e.attribute("comment"));
188                                     }
189                                 }
190                                 infoXml.removeChild(markers);
191                             }
192                             setProfilePath(profileName);
193                             mlt.removeChild(infoXml);
194                             kDebug() << "Reading file: " << url.path() << ", found clips: " << producers.count();
195                         }
196                     }
197                 }
198             }
199         }
200     } else setProfilePath(profileName);
201
202     // Something went wrong, or a new file was requested: create a new project
203     if (!success) {
204         m_url = KUrl();
205         m_document = createEmptyDocument(tracks.x(), tracks.y());
206     }
207
208     // Set the video profile (empty == default)
209
210     // Make sure the project folder is usable
211     if (m_projectFolder.isEmpty() || !KIO::NetAccess::exists(m_projectFolder.path(), KIO::NetAccess::DestinationSide, parent)) {
212         KMessageBox::information(parent, i18n("Document project folder is invalid, setting it to the default one: %1", KdenliveSettings::defaultprojectfolder()));
213         m_projectFolder = KUrl(KdenliveSettings::defaultprojectfolder());
214     }
215
216     // Make sure that the necessary folders exist
217     KStandardDirs::makeDir(m_projectFolder.path() + "/titles/");
218     KStandardDirs::makeDir(m_projectFolder.path() + "/thumbs/");
219     KStandardDirs::makeDir(m_projectFolder.path() + "/ladspa/");
220
221     kDebug() << "Kdenlive document, init timecode: " << m_fps;
222     if (m_fps == 30000.0 / 1001.0) m_timecode.setFormat(30, true);
223     else m_timecode.setFormat((int) m_fps);
224
225     //kDebug() << "// SETTING SCENE LIST:\n\n" << m_document.toString();
226     connect(m_autoSaveTimer, SIGNAL(timeout()), this, SLOT(slotAutoSave()));
227 }
228
229 KdenliveDoc::~KdenliveDoc()
230 {
231     delete m_commandStack;
232     delete m_clipManager;
233     delete m_autoSaveTimer;
234     if (m_autosave) {
235         if (!m_autosave->fileName().isEmpty()) m_autosave->remove();
236         delete m_autosave;
237     }
238 }
239
240 void KdenliveDoc::setSceneList()
241 {
242     m_render->setSceneList(m_document.toString(), m_startPos);
243     // m_document xml is now useless, clear it
244     m_document.clear();
245     checkProjectClips();
246 }
247
248 QDomDocument KdenliveDoc::createEmptyDocument(const int videotracks, const int audiotracks)
249 {
250     // Creating new document
251     QDomDocument doc;
252     QDomElement mlt = doc.createElement("mlt");
253     doc.appendChild(mlt);
254
255
256     TrackInfo videoTrack;
257     videoTrack.type = VIDEOTRACK;
258     videoTrack.isMute = false;
259     videoTrack.isBlind = false;
260     videoTrack.isLocked = false;
261
262     TrackInfo audioTrack;
263     audioTrack.type = AUDIOTRACK;
264     audioTrack.isMute = false;
265     audioTrack.isBlind = true;
266     audioTrack.isLocked = false;
267
268     QDomElement tractor = doc.createElement("tractor");
269     tractor.setAttribute("id", "maintractor");
270     QDomElement multitrack = doc.createElement("multitrack");
271     QDomElement playlist = doc.createElement("playlist");
272     playlist.setAttribute("id", "black_track");
273     mlt.appendChild(playlist);
274
275
276     // create playlists
277     int total = audiotracks + videotracks + 1;
278
279     for (int i = 1; i < total; i++) {
280         QDomElement playlist = doc.createElement("playlist");
281         playlist.setAttribute("id", "playlist" + QString::number(i));
282         mlt.appendChild(playlist);
283     }
284
285     QDomElement track0 = doc.createElement("track");
286     track0.setAttribute("producer", "black_track");
287     tractor.appendChild(track0);
288
289     // create audio tracks
290     for (int i = 1; i < audiotracks + 1; i++) {
291         QDomElement track = doc.createElement("track");
292         track.setAttribute("producer", "playlist" + QString::number(i));
293         track.setAttribute("hide", "video");
294         tractor.appendChild(track);
295         m_tracksList.append(audioTrack);
296     }
297
298     // create video tracks
299     for (int i = audiotracks + 1; i < total; i++) {
300         QDomElement track = doc.createElement("track");
301         track.setAttribute("producer", "playlist" + QString::number(i));
302         tractor.appendChild(track);
303         m_tracksList.append(videoTrack);
304     }
305
306     for (int i = 2; i < total ; i++) {
307         QDomElement transition = doc.createElement("transition");
308         transition.setAttribute("always_active", "1");
309
310         QDomElement property = doc.createElement("property");
311         property.setAttribute("name", "a_track");
312         QDomText value = doc.createTextNode(QString::number(1));
313         property.appendChild(value);
314         transition.appendChild(property);
315
316         property = doc.createElement("property");
317         property.setAttribute("name", "b_track");
318         value = doc.createTextNode(QString::number(i));
319         property.appendChild(value);
320         transition.appendChild(property);
321
322         property = doc.createElement("property");
323         property.setAttribute("name", "mlt_service");
324         value = doc.createTextNode("mix");
325         property.appendChild(value);
326         transition.appendChild(property);
327
328         property = doc.createElement("property");
329         property.setAttribute("name", "combine");
330         value = doc.createTextNode("1");
331         property.appendChild(value);
332         transition.appendChild(property);
333
334         property = doc.createElement("property");
335         property.setAttribute("name", "internal_added");
336         value = doc.createTextNode("237");
337         property.appendChild(value);
338         transition.appendChild(property);
339         tractor.appendChild(transition);
340     }
341     mlt.appendChild(tractor);
342     return doc;
343 }
344
345
346 void KdenliveDoc::syncGuides(QList <Guide *> guides)
347 {
348     m_guidesXml.clear();
349     QDomElement guideNode = m_guidesXml.createElement("guides");
350     m_guidesXml.appendChild(guideNode);
351     QDomElement e;
352
353     for (int i = 0; i < guides.count(); i++) {
354         e = m_guidesXml.createElement("guide");
355         e.setAttribute("time", guides.at(i)->position().ms() / 1000);
356         e.setAttribute("comment", guides.at(i)->label());
357         guideNode.appendChild(e);
358     }
359     setModified(true);
360     emit guidesUpdated();
361 }
362
363 QDomElement KdenliveDoc::guidesXml() const
364 {
365     return m_guidesXml.documentElement();
366 }
367
368 void KdenliveDoc::slotAutoSave()
369 {
370     if (m_render && m_autosave) {
371         if (!m_autosave->isOpen() && !m_autosave->open(QIODevice::ReadWrite)) {
372             // show error: could not open the autosave file
373             kDebug() << "ERROR; CANNOT CREATE AUTOSAVE FILE";
374         }
375         kDebug() << "// AUTOSAVE FILE: " << m_autosave->fileName();
376         QString doc;
377         if (KdenliveSettings::dropbframes()) {
378             KdenliveSettings::setDropbframes(false);
379             m_clipManager->updatePreviewSettings();
380             doc = m_render->sceneList();
381             KdenliveSettings::setDropbframes(true);
382             m_clipManager->updatePreviewSettings();
383         } else doc = m_render->sceneList();
384         saveSceneList(m_autosave->fileName(), doc);
385     }
386 }
387
388 void KdenliveDoc::setZoom(int factor)
389 {
390     m_zoom = factor;
391 }
392
393 int KdenliveDoc::zoom() const
394 {
395     return m_zoom;
396 }
397
398 void KdenliveDoc::setZone(int start, int end)
399 {
400     m_zoneStart = start;
401     m_zoneEnd = end;
402 }
403
404 QPoint KdenliveDoc::zone() const
405 {
406     return QPoint(m_zoneStart, m_zoneEnd);
407 }
408
409 bool KdenliveDoc::saveSceneList(const QString &path, const QString &scene)
410 {
411     QDomDocument sceneList;
412     sceneList.setContent(scene, true);
413     QDomElement mlt = sceneList.firstChildElement("mlt");
414     QDomElement addedXml = sceneList.createElement("kdenlivedoc");
415     mlt.appendChild(addedXml);
416
417     QDomElement markers = sceneList.createElement("markers");
418     addedXml.setAttribute("version", DOCUMENTVERSION);
419     addedXml.setAttribute("kdenliveversion", VERSION);
420     addedXml.setAttribute("profile", profilePath());
421     addedXml.setAttribute("position", m_render->seekPosition().frames(m_fps));
422     addedXml.setAttribute("zonein", m_zoneStart);
423     addedXml.setAttribute("zoneout", m_zoneEnd);
424     addedXml.setAttribute("projectfolder", m_projectFolder.path());
425     addedXml.setAttribute("zoom", m_zoom);
426
427     // Add profile info
428     QDomElement profileinfo = sceneList.createElement("profileinfo");
429     profileinfo.setAttribute("description", m_profile.description);
430     profileinfo.setAttribute("frame_rate_num", m_profile.frame_rate_num);
431     profileinfo.setAttribute("frame_rate_den", m_profile.frame_rate_den);
432     profileinfo.setAttribute("width", m_profile.width);
433     profileinfo.setAttribute("height", m_profile.height);
434     profileinfo.setAttribute("progressive", m_profile.progressive);
435     profileinfo.setAttribute("sample_aspect_num", m_profile.sample_aspect_num);
436     profileinfo.setAttribute("sample_aspect_den", m_profile.sample_aspect_den);
437     profileinfo.setAttribute("display_aspect_num", m_profile.display_aspect_num);
438     profileinfo.setAttribute("display_aspect_den", m_profile.display_aspect_den);
439     addedXml.appendChild(profileinfo);
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     if (m_profile.path.isEmpty()) {
575         // Profile not found, use embedded profile
576         QDomElement profileInfo = m_document.elementsByTagName("profileinfo").at(0).toElement();
577         if (profileInfo.isNull()) {
578             KMessageBox::information(kapp->activeWindow(), i18n("Project profile was not found, using default profile."), i18n("Missing Profile"));
579             m_profile = ProfilesDialog::getVideoProfile(KdenliveSettings::default_profile());
580         } else {
581             KMessageBox::information(kapp->activeWindow(), i18n("Project profile was not found, it will be added to your system now."), i18n("Missing Profile"));
582             m_profile.description = profileInfo.attribute("description");
583             m_profile.frame_rate_num = profileInfo.attribute("frame_rate_num").toInt();
584             m_profile.frame_rate_den = profileInfo.attribute("frame_rate_den").toInt();
585             m_profile.width = profileInfo.attribute("width").toInt();
586             m_profile.height = profileInfo.attribute("height").toInt();
587             m_profile.progressive = profileInfo.attribute("progressive").toInt();
588             m_profile.sample_aspect_num = profileInfo.attribute("sample_aspect_num").toInt();
589             m_profile.sample_aspect_den = profileInfo.attribute("sample_aspect_den").toInt();
590             m_profile.display_aspect_num = profileInfo.attribute("display_aspect_num").toInt();
591             m_profile.display_aspect_den = profileInfo.attribute("display_aspect_den").toInt();
592             ProfilesDialog::saveProfile(m_profile);
593             setModified(true);
594         }
595     }
596
597     KdenliveSettings::setProject_display_ratio((double) m_profile.display_aspect_num / m_profile.display_aspect_den);
598     m_fps = (double) m_profile.frame_rate_num / m_profile.frame_rate_den;
599     KdenliveSettings::setProject_fps(m_fps);
600     m_width = m_profile.width;
601     m_height = m_profile.height;
602     kDebug() << "Kdenlive document, init timecode from path: " << path << ",  " << m_fps;
603     if (m_fps == 30000.0 / 1001.0) m_timecode.setFormat(30, true);
604     else m_timecode.setFormat((int) m_fps);
605 }
606
607 double KdenliveDoc::dar()
608 {
609     return (double) m_profile.display_aspect_num / m_profile.display_aspect_den;
610 }
611
612 void KdenliveDoc::setThumbsProgress(const QString &message, int progress)
613 {
614     emit progressInfo(message, progress);
615 }
616
617 void KdenliveDoc::loadingProgressed()
618 {
619     m_documentLoadingProgress += m_documentLoadingStep;
620     emit progressInfo(QString(), (int) m_documentLoadingProgress);
621 }
622
623 QUndoStack *KdenliveDoc::commandStack()
624 {
625     return m_commandStack;
626 }
627
628 /*
629 void KdenliveDoc::setRenderer(Render *render) {
630     if (m_render) return;
631     m_render = render;
632     emit progressInfo(i18n("Loading playlist..."), 0);
633     //qApp->processEvents();
634     if (m_render) {
635         m_render->setSceneList(m_document.toString(), m_startPos);
636         kDebug() << "// SETTING SCENE LIST:\n\n" << m_document.toString();
637         checkProjectClips();
638     }
639     emit progressInfo(QString(), -1);
640 }*/
641
642 void KdenliveDoc::checkProjectClips()
643 {
644     kDebug() << "+++++++++++++ + + + + CHK PCLIPS";
645     if (m_render == NULL) return;
646     m_clipManager->resetProducersList(m_render->producersList());
647     return;
648
649     // Useless now...
650     QList <Mlt::Producer *> prods = m_render->producersList();
651     QString id ;
652     QString prodId ;
653     QString prodTrack ;
654     for (int i = 0; i < prods.count(); i++) {
655         id = prods.at(i)->get("id");
656         prodId = id.section('_', 0, 0);
657         prodTrack = id.section('_', 1, 1);
658         DocClipBase *clip = m_clipManager->getClipById(prodId);
659         if (clip) clip->setProducer(prods.at(i));
660         if (clip && clip->clipType() == TEXT && !QFile::exists(clip->fileURL().path())) {
661             // regenerate text clip image if required
662             //kDebug() << "// TITLE: " << clip->getProperty("titlename") << " Preview file: " << clip->getProperty("resource") << " DOES NOT EXIST";
663             QString titlename = clip->getProperty("name");
664             QString titleresource;
665             if (titlename.isEmpty()) {
666                 QStringList titleInfo = TitleWidget::getFreeTitleInfo(projectFolder());
667                 titlename = titleInfo.at(0);
668                 titleresource = titleInfo.at(1);
669                 clip->setProperty("name", titlename);
670                 kDebug() << "// New title set to: " << titlename;
671             } else {
672                 titleresource = TitleWidget::getFreeTitleInfo(projectFolder()).at(1);
673                 //titleresource = TitleWidget::getTitleResourceFromName(projectFolder(), titlename);
674             }
675             TitleWidget *dia_ui = new TitleWidget(KUrl(), KUrl(titleresource).directory(), m_render, kapp->activeWindow());
676             QDomDocument doc;
677             doc.setContent(clip->getProperty("xmldata"));
678             dia_ui->setXml(doc);
679             QImage pix = dia_ui->renderedPixmap();
680             pix.save(titleresource);
681             clip->setProperty("resource", titleresource);
682             delete dia_ui;
683             clip->producer()->set("force_reload", 1);
684         }
685     }
686 }
687
688 void KdenliveDoc::updatePreviewSettings()
689 {
690     m_clipManager->updatePreviewSettings();
691     m_render->updatePreviewSettings();
692     m_clipManager->resetProducersList(m_render->producersList());
693
694 }
695
696 Render *KdenliveDoc::renderer()
697 {
698     return m_render;
699 }
700
701 void KdenliveDoc::updateClip(const QString &id)
702 {
703     emit updateClipDisplay(id);
704 }
705
706 int KdenliveDoc::getFramePos(QString duration)
707 {
708     return m_timecode.getFrameCount(duration, m_fps);
709 }
710
711 QString KdenliveDoc::producerName(const QString &id)
712 {
713     QString result = "unnamed";
714     QDomNodeList prods = producersList();
715     int ct = prods.count();
716     for (int i = 0; i <  ct ; i++) {
717         QDomElement e = prods.item(i).toElement();
718         if (e.attribute("id") != "black" && e.attribute("id") == id) {
719             result = e.attribute("name");
720             if (result.isEmpty()) result = KUrl(e.attribute("resource")).fileName();
721             break;
722         }
723     }
724     return result;
725 }
726
727 QDomDocument KdenliveDoc::toXml()
728 {
729     return m_document;
730 }
731
732 Timecode KdenliveDoc::timecode() const
733 {
734     return m_timecode;
735 }
736
737 QDomNodeList KdenliveDoc::producersList()
738 {
739     return m_document.elementsByTagName("producer");
740 }
741
742 double KdenliveDoc::projectDuration() const
743 {
744     if (m_render)
745         return GenTime(m_render->getLength(), m_fps).ms() / 1000;
746     else
747         return 0;
748 }
749
750 double KdenliveDoc::fps() const
751 {
752     return m_fps;
753 }
754
755 int KdenliveDoc::width() const
756 {
757     return m_width;
758 }
759
760 int KdenliveDoc::height() const
761 {
762     return m_height;
763 }
764
765 KUrl KdenliveDoc::url() const
766 {
767     return m_url;
768 }
769
770 void KdenliveDoc::setUrl(KUrl url)
771 {
772     m_url = url;
773 }
774
775 void KdenliveDoc::setModified(bool mod)
776 {
777     if (!m_url.isEmpty() && mod && KdenliveSettings::crashrecovery()) {
778         m_autoSaveTimer->start(3000);
779     }
780     if (mod == m_modified) return;
781     m_modified = mod;
782     emit docModified(m_modified);
783 }
784
785 bool KdenliveDoc::isModified() const
786 {
787     return m_modified;
788 }
789
790 const QString KdenliveDoc::description() const
791 {
792     if (m_url.isEmpty())
793         return i18n("Untitled") + " / " + m_profile.description;
794     else
795         return m_url.fileName() + " / " + m_profile.description;
796 }
797
798 void KdenliveDoc::addClip(QDomElement elem, QString clipId, bool createClipItem)
799 {
800     const QString producerId = clipId.section('_', 0, 0);
801     DocClipBase *clip = m_clipManager->getClipById(producerId);
802
803     if (clip == NULL) {
804         elem.setAttribute("id", producerId);
805         QString path = elem.attribute("resource");
806         QString extension;
807         if (elem.attribute("type").toInt() == SLIDESHOW) {
808             extension = KUrl(path).fileName();
809             path = KUrl(path).directory();
810         } else if (elem.attribute("type").toInt() == TEXT && QFile::exists(path) == false) {
811             kDebug() << "// TITLE: " << elem.attribute("name") << " Preview file: " << elem.attribute("resource") << " DOES NOT EXIST";
812             QString titlename = elem.attribute("name");
813             QString titleresource;
814             if (titlename.isEmpty()) {
815                 QStringList titleInfo = TitleWidget::getFreeTitleInfo(projectFolder());
816                 titlename = titleInfo.at(0);
817                 titleresource = titleInfo.at(1);
818                 elem.setAttribute("name", titlename);
819                 kDebug() << "// New title set to: " << titlename;
820             } else {
821                 titleresource = TitleWidget::getFreeTitleInfo(projectFolder()).at(1);
822                 //titleresource = TitleWidget::getTitleResourceFromName(projectFolder(), titlename);
823             }
824             TitleWidget *dia_ui = new TitleWidget(KUrl(), KUrl(titleresource).directory(), m_render, kapp->activeWindow());
825             QDomDocument doc;
826             doc.setContent(elem.attribute("xmldata"));
827             dia_ui->setXml(doc);
828             QImage pix = dia_ui->renderedPixmap();
829             pix.save(titleresource);
830             elem.setAttribute("resource", titleresource);
831             setNewClipResource(clipId, titleresource);
832             delete dia_ui;
833         }
834
835         if (path.isEmpty() == false && QFile::exists(path) == false && elem.attribute("type").toInt() != TEXT && !elem.hasAttribute("placeholder")) {
836             kDebug() << "// FOUND MISSING CLIP: " << path << ", TYPE: " << elem.attribute("type").toInt();
837             const QString size = elem.attribute("file_size");
838             const QString hash = elem.attribute("file_hash");
839             QString newpath;
840             int action = KMessageBox::No;
841             if (!size.isEmpty() && !hash.isEmpty()) {
842                 if (!m_searchFolder.isEmpty()) newpath = searchFileRecursively(m_searchFolder, size, hash);
843                 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")));
844             } else {
845                 if (elem.attribute("type").toInt() == SLIDESHOW) {
846                     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")));
847                     if (res == KMessageBox::Yes)
848                         newpath = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow(), i18n("Looking for %1", path));
849                     else {
850                         // Abort project loading
851                         action = res;
852                     }
853                 } else {
854                     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")));
855                     if (res == KMessageBox::Yes)
856                         newpath = KFileDialog::getOpenFileName(KUrl("kfiledialog:///clipfolder"), QString(), kapp->activeWindow(), i18n("Looking for %1", path));
857                     else {
858                         // Abort project loading
859                         action = res;
860                     }
861                 }
862             }
863             if (action == KMessageBox::Yes) {
864                 kDebug() << "// ASKED FOR SRCH CLIP: " << clipId;
865                 m_searchFolder = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow());
866                 if (!m_searchFolder.isEmpty()) {
867                     newpath = searchFileRecursively(QDir(m_searchFolder), size, hash);
868                 }
869             } else if (action == KMessageBox::Cancel) {
870                 m_abortLoading = true;
871                 return;
872             } else if (action == KMessageBox::No) {
873                 // Keep clip as placeHolder
874                 elem.setAttribute("placeholder", '1');
875             }
876             if (!newpath.isEmpty()) {
877                 if (elem.attribute("type").toInt() == SLIDESHOW) newpath.append('/' + extension);
878                 elem.setAttribute("resource", newpath);
879                 setNewClipResource(clipId, newpath);
880                 setModified(true);
881             }
882         }
883         clip = new DocClipBase(m_clipManager, elem, producerId);
884         m_clipManager->addClip(clip);
885     }
886
887     if (createClipItem) {
888         emit addProjectClip(clip);
889         qApp->processEvents();
890         m_render->getFileProperties(clip->toXML(), clip->getId());
891     }
892 }
893
894
895 void KdenliveDoc::setNewClipResource(const QString &id, const QString &path)
896 {
897     QDomNodeList prods = m_document.elementsByTagName("producer");
898     int maxprod = prods.count();
899     for (int i = 0; i < maxprod; i++) {
900         QDomNode m = prods.at(i);
901         QString prodId = m.toElement().attribute("id");
902         if (prodId == id || prodId.startsWith(id + '_')) {
903             QDomNodeList params = m.childNodes();
904             for (int j = 0; j < params.count(); j++) {
905                 QDomElement e = params.item(j).toElement();
906                 if (e.attribute("name") == "resource") {
907                     e.firstChild().setNodeValue(path);
908                     break;
909                 }
910             }
911         }
912     }
913 }
914
915 QString KdenliveDoc::searchFileRecursively(const QDir &dir, const QString &matchSize, const QString &matchHash) const
916 {
917     QString foundFileName;
918     QByteArray fileData;
919     QByteArray fileHash;
920     QStringList filesAndDirs = dir.entryList(QDir::Files | QDir::Readable);
921     for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
922         QFile file(dir.absoluteFilePath(filesAndDirs.at(i)));
923         if (file.open(QIODevice::ReadOnly)) {
924             if (QString::number(file.size()) == matchSize) {
925                 /*
926                 * 1 MB = 1 second per 450 files (or faster)
927                 * 10 MB = 9 seconds per 450 files (or faster)
928                 */
929                 if (file.size() > 1000000*2) {
930                     fileData = file.read(1000000);
931                     if (file.seek(file.size() - 1000000))
932                         fileData.append(file.readAll());
933                 } else
934                     fileData = file.readAll();
935                 file.close();
936                 fileHash = QCryptographicHash::hash(fileData, QCryptographicHash::Md5);
937                 if (QString(fileHash.toHex()) == matchHash)
938                     return file.fileName();
939             }
940         }
941         kDebug() << filesAndDirs.at(i) << file.size() << fileHash.toHex();
942     }
943     filesAndDirs = dir.entryList(QDir::Dirs | QDir::Readable | QDir::Executable | QDir::NoDotAndDotDot);
944     for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
945         foundFileName = searchFileRecursively(dir.absoluteFilePath(filesAndDirs.at(i)), matchSize, matchHash);
946         if (!foundFileName.isEmpty())
947             break;
948     }
949     return foundFileName;
950 }
951
952 void KdenliveDoc::addClipInfo(QDomElement elem, QDomElement orig, QString clipId)
953 {
954     DocClipBase *clip = m_clipManager->getClipById(clipId);
955     if (clip == NULL) {
956         addClip(elem, clipId, false);
957     } else {
958         QMap <QString, QString> properties;
959         QDomNamedNodeMap attributes = elem.attributes();
960         QString attrname;
961         for (int i = 0; i < attributes.count(); i++) {
962             attrname = attributes.item(i).nodeName();
963             if (attrname != "resource")
964                 properties.insert(attrname, attributes.item(i).nodeValue());
965             kDebug() << attrname << " = " << attributes.item(i).nodeValue();
966         }
967         clip->setProperties(properties);
968         emit addProjectClip(clip, false);
969     }
970     if (orig != QDomElement()) {
971         QMap<QString, QString> meta;
972         QDomNode m = orig.firstChild();
973         while (!m.isNull()) {
974             QString name = m.toElement().attribute("name");
975             if (name.startsWith("meta.attr")) {
976                 meta.insert(name.section('.', 2, 3), m.firstChild().nodeValue());
977             }
978             m = m.nextSibling();
979         }
980         if (!meta.isEmpty()) {
981             if (clip == NULL) clip = m_clipManager->getClipById(clipId);
982             if (clip) clip->setMetadata(meta);
983         }
984     }
985 }
986
987 void KdenliveDoc::deleteProjectClip(QList <QString> ids)
988 {
989     for (int i = 0; i < ids.size(); ++i) {
990         emit deleteTimelineClip(ids.at(i));
991         m_clipManager->slotDeleteClip(ids.at(i));
992     }
993     setModified(true);
994 }
995
996 void KdenliveDoc::deleteClip(const QString &clipId)
997 {
998     emit signalDeleteProjectClip(clipId);
999     m_clipManager->deleteClip(clipId);
1000 }
1001
1002 void KdenliveDoc::slotAddClipList(const KUrl::List urls, const QString group, const QString &groupId)
1003 {
1004     m_clipManager->slotAddClipList(urls, group, groupId);
1005     emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1006     setModified(true);
1007 }
1008
1009
1010 void KdenliveDoc::slotAddClipFile(const KUrl url, const QString group, const QString &groupId)
1011 {
1012     //kDebug() << "/////////  DOCUM, ADD CLP: " << url;
1013     m_clipManager->slotAddClipFile(url, group, groupId);
1014     emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1015     setModified(true);
1016 }
1017
1018 const QString KdenliveDoc::getFreeClipId()
1019 {
1020     return QString::number(m_clipManager->getFreeClipId());
1021 }
1022
1023 DocClipBase *KdenliveDoc::getBaseClip(const QString &clipId)
1024 {
1025     return m_clipManager->getClipById(clipId);
1026 }
1027
1028 void KdenliveDoc::slotCreateTextClip(QString /*group*/, const QString &/*groupId*/)
1029 {
1030     QString titlesFolder = projectFolder().path() + "/titles/";
1031     KStandardDirs::makeDir(titlesFolder);
1032     TitleWidget *dia_ui = new TitleWidget(KUrl(), titlesFolder, m_render, kapp->activeWindow());
1033     if (dia_ui->exec() == QDialog::Accepted) {
1034         QStringList titleInfo = TitleWidget::getFreeTitleInfo(projectFolder());
1035         QImage pix = dia_ui->renderedPixmap();
1036         pix.save(titleInfo.at(1));
1037         //dia_ui->saveTitle(path + ".kdenlivetitle");
1038         m_clipManager->slotAddTextClipFile(titleInfo.at(0), titleInfo.at(1), dia_ui->xml().toString(), QString(), QString());
1039         setModified(true);
1040     }
1041     delete dia_ui;
1042 }
1043
1044 int KdenliveDoc::tracksCount() const
1045 {
1046     return m_tracksList.count();
1047 }
1048
1049 TrackInfo KdenliveDoc::trackInfoAt(int ix) const
1050 {
1051     return m_tracksList.at(ix);
1052 }
1053
1054 void KdenliveDoc::switchTrackAudio(int ix, bool hide)
1055 {
1056     m_tracksList[ix].isMute = hide; // !m_tracksList.at(ix).isMute;
1057 }
1058
1059 void KdenliveDoc::switchTrackLock(int ix, bool lock)
1060 {
1061     m_tracksList[ix].isLocked = lock;
1062 }
1063
1064 bool KdenliveDoc::isTrackLocked(int ix) const
1065 {
1066     return m_tracksList.at(ix).isLocked;
1067 }
1068
1069 void KdenliveDoc::switchTrackVideo(int ix, bool hide)
1070 {
1071     m_tracksList[ix].isBlind = hide; // !m_tracksList.at(ix).isBlind;
1072 }
1073
1074 void KdenliveDoc::insertTrack(int ix, TrackInfo type)
1075 {
1076     if (ix == -1) m_tracksList << type;
1077     else m_tracksList.insert(ix, type);
1078 }
1079
1080 void KdenliveDoc::deleteTrack(int ix)
1081 {
1082     m_tracksList.removeAt(ix);
1083 }
1084
1085 void KdenliveDoc::setTrackType(int ix, TrackInfo type)
1086 {
1087     m_tracksList[ix].type = type.type;
1088     m_tracksList[ix].isMute = type.isMute;
1089     m_tracksList[ix].isBlind = type.isBlind;
1090     m_tracksList[ix].isLocked = type.isLocked;
1091 }
1092
1093 const QList <TrackInfo> KdenliveDoc::tracksList() const
1094 {
1095     return m_tracksList;
1096 }
1097
1098 QPoint KdenliveDoc::getTracksCount() const
1099 {
1100     int audio = 0;
1101     int video = 0;
1102     foreach(const TrackInfo &info, m_tracksList) {
1103         if (info.type == VIDEOTRACK) video++;
1104         else audio++;
1105     }
1106     return QPoint(video, audio);
1107 }
1108
1109 void KdenliveDoc::cachePixmap(const QString &fileId, const QPixmap &pix) const
1110 {
1111     pix.save(m_projectFolder.path() + "/thumbs/" + fileId + ".png");
1112 }
1113
1114 QString KdenliveDoc::getLadspaFile() const
1115 {
1116     int ct = 0;
1117     QString counter = QString::number(ct).rightJustified(5, '0', false);
1118     while (QFile::exists(m_projectFolder.path() + "/ladspa/" + counter + ".ladspa")) {
1119         ct++;
1120         counter = QString::number(ct).rightJustified(5, '0', false);
1121     }
1122     return m_projectFolder.path() + "/ladspa/" + counter + ".ladspa";
1123 }
1124
1125 bool KdenliveDoc::checkDocumentClips(QDomNodeList infoproducers)
1126 {
1127     int clipType;
1128     QDomElement e;
1129     QString id;
1130     QString resource;
1131     QList <QDomElement> missingClips;
1132     for (int i = 0; i < infoproducers.count(); i++) {
1133         e = infoproducers.item(i).toElement();
1134         clipType = e.attribute("type").toInt();
1135         if (clipType == TEXT || clipType == COLOR) continue;
1136         id = e.attribute("id");
1137         resource = e.attribute("resource");
1138         if (clipType == SLIDESHOW) resource = KUrl(resource).directory();
1139         if (!KIO::NetAccess::exists(KUrl(resource), KIO::NetAccess::SourceSide, 0)) {
1140             // Missing clip found
1141             missingClips.append(e);
1142         }
1143     }
1144     if (missingClips.isEmpty()) return true;
1145     DocumentChecker d(missingClips, m_document);
1146     return (d.exec() == QDialog::Accepted);
1147 }
1148
1149
1150 #include "kdenlivedoc.moc"
1151