1 /***************************************************************************
2 * Copyright (C) 2007 by Jean-Baptiste Mardelle (jb@kdenlive.org) *
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. *
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. *
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 ***************************************************************************/
21 #include "kdenlivedoc.h"
22 #include "docclipbase.h"
23 #include "profilesdialog.h"
24 #include "kdenlivesettings.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"
34 #include <KStandardDirs>
35 #include <KMessageBox>
37 #include <KFileDialog>
38 #include <KIO/NetAccess>
39 #include <KIO/CopyJob>
40 #include <KApplication>
42 #include <QCryptographicHash>
44 #include <QInputDialog>
46 #include <mlt++/Mlt.h>
48 const double DOCUMENTVERSION = 0.84;
50 KdenliveDoc::KdenliveDoc(const KUrl &url, const KUrl &projectFolder, QUndoGroup *undoGroup, QString profileName, const QPoint tracks, Render *render, MainWindow *parent) :
55 m_commandStack(new QUndoStack(undoGroup)),
57 m_projectFolder(projectFolder),
58 m_documentLoadingStep(0.0),
59 m_documentLoadingProgress(0),
62 m_clipManager = new ClipManager(this);
63 m_autoSaveTimer = new QTimer(this);
64 m_autoSaveTimer->setSingleShot(true);
67 // init default document properties
68 m_documentProperties["zoom"] = "7";
69 m_documentProperties["verticalzoom"] = "1";
70 m_documentProperties["zonein"] = "0";
71 m_documentProperties["zoneout"] = "100";
75 success = KIO::NetAccess::download(url.path(), tmpFile, parent);
76 if (!success) // The file cannot be opened
77 KMessageBox::error(parent, KIO::NetAccess::lastErrorString());
81 success = m_document.setContent(&file, false, &errorMsg);
83 KIO::NetAccess::removeTempFile(tmpFile);
85 if (!success) // It is corrupted
86 KMessageBox::error(parent, errorMsg);
88 DocumentValidator validator(m_document);
89 success = validator.isProject();
90 if (!success) // It is not a project file
91 parent->slotGotProgressInfo(i18n("File %1 is not a Kdenlive project file.", m_url.path()), 100);
94 * Validate the file against the current version (upgrade
95 * and recover it if needed). It is NOT a passive operation
97 // TODO: backup the document or alert the user?
98 success = validator.validate(DOCUMENTVERSION);
99 if (success) { // Let the validator handle error messages
100 QDomElement mlt = m_document.firstChildElement("mlt");
101 QDomElement infoXml = mlt.firstChildElement("kdenlivedoc");
103 profileName = infoXml.attribute("profile");
104 m_projectFolder = KUrl(infoXml.attribute("projectfolder"));
105 QDomElement docproperties = infoXml.firstChildElement("documentproperties");
106 QDomNamedNodeMap props = docproperties.attributes();
107 for (int i = 0; i < props.count(); i++) {
108 m_documentProperties.insert(props.item(i).nodeName(), props.item(i).nodeValue());
112 QDomElement tracksinfo = infoXml.firstChildElement("tracksinfo");
113 TrackInfo projectTrack;
114 if (!tracksinfo.isNull()) {
115 QDomNodeList trackslist = tracksinfo.childNodes();
116 int maxchild = trackslist.count();
117 for (int k = 0; k < maxchild; k++) {
118 e = trackslist.at(k).toElement();
119 if (e.tagName() == "trackinfo") {
120 if (e.attribute("type") == "audio") projectTrack.type = AUDIOTRACK;
121 else projectTrack.type = VIDEOTRACK;
122 projectTrack.isMute = e.attribute("mute").toInt();
123 projectTrack.isBlind = e.attribute("blind").toInt();
124 projectTrack.isLocked = e.attribute("locked").toInt();
125 projectTrack.trackName = e.attribute("trackname");
126 m_tracksList.append(projectTrack);
129 mlt.removeChild(tracksinfo);
131 QDomNodeList producers = m_document.elementsByTagName("producer");
132 QDomNodeList infoproducers = m_document.elementsByTagName("kdenlive_producer");
133 if (checkDocumentClips(infoproducers) == false) m_abortLoading = true;
134 const int max = producers.count();
135 const int infomax = infoproducers.count();
137 QDomNodeList folders = m_document.elementsByTagName("folder");
138 for (int i = 0; i < folders.count(); i++) {
139 e = folders.item(i).cloneNode().toElement();
140 m_clipManager->addFolder(e.attribute("id"), e.attribute("name"));
144 m_documentLoadingStep = 100.0 / (max + infomax + m_document.elementsByTagName("entry").count());
145 parent->slotGotProgressInfo(i18n("Loading project clips"), (int) m_documentLoadingProgress);
149 for (int i = 0; i < infomax && !m_abortLoading; i++) {
150 e = infoproducers.item(i).cloneNode().toElement();
151 if (m_documentLoadingStep > 0) {
152 m_documentLoadingProgress += m_documentLoadingStep;
153 parent->slotGotProgressInfo(QString(), (int) m_documentLoadingProgress);
154 //qApp->processEvents();
156 QString prodId = e.attribute("id");
157 if (!e.isNull() && prodId != "black" && !prodId.startsWith("slowmotion") && !m_abortLoading) {
158 e.setTagName("producer");
159 // Get MLT's original producer properties
161 for (int j = 0; j < max; j++) {
162 QDomElement o = producers.item(j).cloneNode().toElement();
163 QString origId = o.attribute("id").section('_', 0, 0);
164 if (origId == prodId) {
169 addClipInfo(e, orig, prodId);
170 kDebug() << "// KDENLIVE PRODUCER: " << prodId;
173 if (m_abortLoading) {
174 //parent->slotGotProgressInfo(i18n("File %1 is not a Kdenlive project file."), 100);
175 emit resetProjectList();
176 m_documentProperties.remove("position");
178 m_tracksList.clear();
179 kWarning() << "Aborted loading of: " << url.path();
180 m_document = createEmptyDocument(KdenliveSettings::videotracks(), KdenliveSettings::audiotracks());
181 setProfilePath(KdenliveSettings::default_profile());
182 m_clipManager->clear();
184 QDomElement markers = infoXml.firstChildElement("markers");
185 if (!markers.isNull()) {
186 QDomNodeList markerslist = markers.childNodes();
187 int maxchild = markerslist.count();
188 for (int k = 0; k < maxchild; k++) {
189 e = markerslist.at(k).toElement();
190 if (e.tagName() == "marker") {
191 m_clipManager->getClipById(e.attribute("id"))->addSnapMarker(GenTime(e.attribute("time").toDouble()), e.attribute("comment"));
194 infoXml.removeChild(markers);
196 setProfilePath(profileName);
197 setModified(validator.isModified());
198 kDebug() << "Reading file: " << url.path() << ", found clips: " << producers.count();
206 // Something went wrong, or a new file was requested: create a new project
208 setProfilePath(profileName);
210 m_document = createEmptyDocument(tracks.x(), tracks.y());
213 KdenliveSettings::setCurrent_profile(profilePath());
215 // Set the video profile (empty == default)
217 // Make sure the project folder is usable
218 if (m_projectFolder.isEmpty() || !KIO::NetAccess::exists(m_projectFolder.path(), KIO::NetAccess::DestinationSide, parent)) {
219 KMessageBox::information(parent, i18n("Document project folder is invalid, setting it to the default one: %1", KdenliveSettings::defaultprojectfolder()));
220 m_projectFolder = KUrl(KdenliveSettings::defaultprojectfolder());
223 // Make sure that the necessary folders exist
224 KStandardDirs::makeDir(m_projectFolder.path(KUrl::AddTrailingSlash) + "titles/");
225 KStandardDirs::makeDir(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/");
226 KStandardDirs::makeDir(m_projectFolder.path(KUrl::AddTrailingSlash) + "ladspa/");
228 kDebug() << "Kdenlive document, init timecode: " << m_fps;
229 if (m_fps == 30000.0 / 1001.0) m_timecode.setFormat(m_fps, true);
230 else m_timecode.setFormat(m_fps);
232 //kDebug() << "// SETTING SCENE LIST:\n\n" << m_document.toString();
233 connect(m_autoSaveTimer, SIGNAL(timeout()), this, SLOT(slotAutoSave()));
236 KdenliveDoc::~KdenliveDoc()
238 m_autoSaveTimer->stop();
239 delete m_commandStack;
240 kDebug() << "// DEL CLP MAN";
241 delete m_clipManager;
242 kDebug() << "// DEL CLP MAN done";
243 delete m_autoSaveTimer;
245 if (!m_autosave->fileName().isEmpty()) m_autosave->remove();
250 int KdenliveDoc::setSceneList()
252 m_render->resetProfile();
253 if (m_render->setSceneList(m_document.toString(), m_documentProperties.value("position").toInt()) == -1) {
254 // INVALID MLT Consumer, something is wrong
257 m_documentProperties.remove("position");
258 // m_document xml is now useless, clear it
263 QDomDocument KdenliveDoc::createEmptyDocument(int videotracks, int audiotracks)
265 TrackInfo videoTrack;
266 videoTrack.type = VIDEOTRACK;
267 videoTrack.isMute = false;
268 videoTrack.isBlind = false;
269 videoTrack.isLocked = false;
271 TrackInfo audioTrack;
272 audioTrack.type = AUDIOTRACK;
273 audioTrack.isMute = false;
274 audioTrack.isBlind = true;
275 audioTrack.isLocked = false;
277 m_tracksList.clear();
279 for (int i = 0; i < audiotracks; i++) {
280 m_tracksList.append(audioTrack);
282 for (int i = 0; i < videotracks; i++) {
283 m_tracksList.append(videoTrack);
285 return createEmptyDocument(m_tracksList);
288 QDomDocument KdenliveDoc::createEmptyDocument(QList <TrackInfo> tracks)
290 // Creating new document
292 QDomElement mlt = doc.createElement("mlt");
293 doc.appendChild(mlt);
296 // Create black producer
297 // For some unknown reason, we have to build the black producer here and not in renderer.cpp, otherwise
298 // the composite transitions with the black track are corrupted.
299 QDomElement blk = doc.createElement("producer");
300 blk.setAttribute("in", 0);
301 blk.setAttribute("out", 500);
302 blk.setAttribute("id", "black");
304 QDomElement property = doc.createElement("property");
305 property.setAttribute("name", "mlt_type");
306 QDomText value = doc.createTextNode("producer");
307 property.appendChild(value);
308 blk.appendChild(property);
310 property = doc.createElement("property");
311 property.setAttribute("name", "aspect_ratio");
312 value = doc.createTextNode(QString::number(0.0));
313 property.appendChild(value);
314 blk.appendChild(property);
316 property = doc.createElement("property");
317 property.setAttribute("name", "length");
318 value = doc.createTextNode(QString::number(15000));
319 property.appendChild(value);
320 blk.appendChild(property);
322 property = doc.createElement("property");
323 property.setAttribute("name", "eof");
324 value = doc.createTextNode("pause");
325 property.appendChild(value);
326 blk.appendChild(property);
328 property = doc.createElement("property");
329 property.setAttribute("name", "resource");
330 value = doc.createTextNode("black");
331 property.appendChild(value);
332 blk.appendChild(property);
334 property = doc.createElement("property");
335 property.setAttribute("name", "mlt_service");
336 value = doc.createTextNode("colour");
337 property.appendChild(value);
338 blk.appendChild(property);
340 mlt.appendChild(blk);
343 QDomElement tractor = doc.createElement("tractor");
344 tractor.setAttribute("id", "maintractor");
345 QDomElement multitrack = doc.createElement("multitrack");
346 QDomElement playlist = doc.createElement("playlist");
347 playlist.setAttribute("id", "black_track");
348 mlt.appendChild(playlist);
350 QDomElement blank0 = doc.createElement("entry");
351 blank0.setAttribute("in", "0");
352 blank0.setAttribute("out", "0");
353 blank0.setAttribute("producer", "black");
354 playlist.appendChild(blank0);
357 int total = tracks.count() + 1;
359 for (int i = 1; i < total; i++) {
360 QDomElement playlist = doc.createElement("playlist");
361 playlist.setAttribute("id", "playlist" + QString::number(i));
362 mlt.appendChild(playlist);
365 QDomElement track0 = doc.createElement("track");
366 track0.setAttribute("producer", "black_track");
367 tractor.appendChild(track0);
369 // create audio tracks
370 for (int i = 1; i < total; i++) {
371 QDomElement track = doc.createElement("track");
372 track.setAttribute("producer", "playlist" + QString::number(i));
373 if (tracks.at(i - 1).type == AUDIOTRACK)
374 track.setAttribute("hide", "video");
375 else if (tracks.at(i - 1).isBlind)
376 track.setAttribute("hide", "video");
377 if (tracks.at(i - 1).isMute)
378 track.setAttribute("hide", "audio");
379 tractor.appendChild(track);
382 for (int i = 2; i < total ; i++) {
383 QDomElement transition = doc.createElement("transition");
384 transition.setAttribute("always_active", "1");
386 QDomElement property = doc.createElement("property");
387 property.setAttribute("name", "a_track");
388 QDomText value = doc.createTextNode(QString::number(1));
389 property.appendChild(value);
390 transition.appendChild(property);
392 property = doc.createElement("property");
393 property.setAttribute("name", "b_track");
394 value = doc.createTextNode(QString::number(i));
395 property.appendChild(value);
396 transition.appendChild(property);
398 property = doc.createElement("property");
399 property.setAttribute("name", "mlt_service");
400 value = doc.createTextNode("mix");
401 property.appendChild(value);
402 transition.appendChild(property);
404 property = doc.createElement("property");
405 property.setAttribute("name", "combine");
406 value = doc.createTextNode("1");
407 property.appendChild(value);
408 transition.appendChild(property);
410 property = doc.createElement("property");
411 property.setAttribute("name", "internal_added");
412 value = doc.createTextNode("237");
413 property.appendChild(value);
414 transition.appendChild(property);
415 tractor.appendChild(transition);
417 mlt.appendChild(tractor);
422 void KdenliveDoc::syncGuides(QList <Guide *> guides)
425 QDomElement guideNode = m_guidesXml.createElement("guides");
426 m_guidesXml.appendChild(guideNode);
429 for (int i = 0; i < guides.count(); i++) {
430 e = m_guidesXml.createElement("guide");
431 e.setAttribute("time", guides.at(i)->position().ms() / 1000);
432 e.setAttribute("comment", guides.at(i)->label());
433 guideNode.appendChild(e);
436 emit guidesUpdated();
439 QDomElement KdenliveDoc::guidesXml() const
441 return m_guidesXml.documentElement();
444 void KdenliveDoc::slotAutoSave()
446 if (m_render && m_autosave) {
447 if (!m_autosave->isOpen() && !m_autosave->open(QIODevice::ReadWrite)) {
448 // show error: could not open the autosave file
449 kDebug() << "ERROR; CANNOT CREATE AUTOSAVE FILE";
451 kDebug() << "// AUTOSAVE FILE: " << m_autosave->fileName();
453 if (KdenliveSettings::dropbframes()) {
454 KdenliveSettings::setDropbframes(false);
455 m_clipManager->updatePreviewSettings();
456 doc = m_render->sceneList();
457 KdenliveSettings::setDropbframes(true);
458 m_clipManager->updatePreviewSettings();
459 } else doc = m_render->sceneList();
460 saveSceneList(m_autosave->fileName(), doc);
464 void KdenliveDoc::setZoom(int horizontal, int vertical)
466 m_documentProperties["zoom"] = QString::number(horizontal);
467 m_documentProperties["verticalzoom"] = QString::number(vertical);
470 QPoint KdenliveDoc::zoom() const
472 return QPoint(m_documentProperties.value("zoom").toInt(), m_documentProperties.value("verticalzoom").toInt());
475 void KdenliveDoc::setZone(int start, int end)
477 m_documentProperties["zonein"] = QString::number(start);
478 m_documentProperties["zoneout"] = QString::number(end);
481 QPoint KdenliveDoc::zone() const
483 return QPoint(m_documentProperties.value("zonein").toInt(), m_documentProperties.value("zoneout").toInt());
486 bool KdenliveDoc::saveSceneList(const QString &path, const QString &scene)
488 QDomDocument sceneList;
489 sceneList.setContent(scene, true);
490 QDomElement mlt = sceneList.firstChildElement("mlt");
491 QDomElement addedXml = sceneList.createElement("kdenlivedoc");
492 mlt.appendChild(addedXml);
494 QDomElement markers = sceneList.createElement("markers");
495 addedXml.setAttribute("version", DOCUMENTVERSION);
496 addedXml.setAttribute("kdenliveversion", VERSION);
497 addedXml.setAttribute("profile", profilePath());
498 addedXml.setAttribute("projectfolder", m_projectFolder.path());
500 QDomElement docproperties = sceneList.createElement("documentproperties");
501 QMapIterator<QString, QString> i(m_documentProperties);
502 while (i.hasNext()) {
504 docproperties.setAttribute(i.key(), i.value());
506 docproperties.setAttribute("position", m_render->seekPosition().frames(m_fps));
507 addedXml.appendChild(docproperties);
510 QDomElement profileinfo = sceneList.createElement("profileinfo");
511 profileinfo.setAttribute("description", m_profile.description);
512 profileinfo.setAttribute("frame_rate_num", m_profile.frame_rate_num);
513 profileinfo.setAttribute("frame_rate_den", m_profile.frame_rate_den);
514 profileinfo.setAttribute("width", m_profile.width);
515 profileinfo.setAttribute("height", m_profile.height);
516 profileinfo.setAttribute("progressive", m_profile.progressive);
517 profileinfo.setAttribute("sample_aspect_num", m_profile.sample_aspect_num);
518 profileinfo.setAttribute("sample_aspect_den", m_profile.sample_aspect_den);
519 profileinfo.setAttribute("display_aspect_num", m_profile.display_aspect_num);
520 profileinfo.setAttribute("display_aspect_den", m_profile.display_aspect_den);
521 addedXml.appendChild(profileinfo);
524 QDomElement tracksinfo = sceneList.createElement("tracksinfo");
525 foreach(const TrackInfo &info, m_tracksList) {
526 QDomElement trackinfo = sceneList.createElement("trackinfo");
527 if (info.type == AUDIOTRACK) trackinfo.setAttribute("type", "audio");
528 trackinfo.setAttribute("mute", info.isMute);
529 trackinfo.setAttribute("blind", info.isBlind);
530 trackinfo.setAttribute("locked", info.isLocked);
531 trackinfo.setAttribute("trackname", info.trackName);
532 tracksinfo.appendChild(trackinfo);
534 addedXml.appendChild(tracksinfo);
536 // save project folders
537 QMap <QString, QString> folderlist = m_clipManager->documentFolderList();
539 QMapIterator<QString, QString> f(folderlist);
540 while (f.hasNext()) {
542 QDomElement folder = sceneList.createElement("folder");
543 folder.setAttribute("id", f.key());
544 folder.setAttribute("name", f.value());
545 addedXml.appendChild(folder);
548 // Save project clips
550 QList <DocClipBase*> list = m_clipManager->documentClipList();
551 for (int i = 0; i < list.count(); i++) {
552 e = list.at(i)->toXML();
553 e.setTagName("kdenlive_producer");
554 addedXml.appendChild(sceneList.importNode(e, true));
555 QList < CommentedTime > marks = list.at(i)->commentedSnapMarkers();
556 for (int j = 0; j < marks.count(); j++) {
557 QDomElement marker = sceneList.createElement("marker");
558 marker.setAttribute("time", marks.at(j).time().ms() / 1000);
559 marker.setAttribute("comment", marks.at(j).comment());
560 marker.setAttribute("id", e.attribute("id"));
561 markers.appendChild(marker);
564 addedXml.appendChild(markers);
567 if (!m_guidesXml.isNull()) addedXml.appendChild(sceneList.importNode(m_guidesXml.documentElement(), true));
570 addedXml.appendChild(sceneList.importNode(m_clipManager->groupsXml(), true));
572 //wes.appendChild(doc.importNode(kdenliveData, true));
575 if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
576 kWarning() << "////// ERROR writing to file: " << path;
577 KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1", path));
581 file.write(sceneList.toString().toUtf8());
582 if (file.error() != QFile::NoError) {
583 KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1", path));
591 ClipManager *KdenliveDoc::clipManager()
593 return m_clipManager;
596 KUrl KdenliveDoc::projectFolder() const
598 //if (m_projectFolder.isEmpty()) return KUrl(KStandardDirs::locateLocal("appdata", "/projects/"));
599 return m_projectFolder;
602 void KdenliveDoc::setProjectFolder(KUrl url)
604 if (url == m_projectFolder) return;
606 KStandardDirs::makeDir(url.path());
607 KStandardDirs::makeDir(url.path(KUrl::AddTrailingSlash) + "titles/");
608 KStandardDirs::makeDir(url.path(KUrl::AddTrailingSlash) + "thumbs/");
609 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);
610 m_projectFolder = url;
613 void KdenliveDoc::moveProjectData(KUrl url)
615 QList <DocClipBase*> list = m_clipManager->documentClipList();
616 //TODO: Also move ladspa effects files
617 for (int i = 0; i < list.count(); i++) {
618 DocClipBase *clip = list.at(i);
619 if (clip->clipType() == TEXT) {
620 // the image for title clip must be moved
621 KUrl oldUrl = clip->fileURL();
622 KUrl newUrl = KUrl(url.path(KUrl::AddTrailingSlash) + "titles/" + oldUrl.fileName());
623 KIO::Job *job = KIO::copy(oldUrl, newUrl);
624 if (KIO::NetAccess::synchronousRun(job, 0)) clip->setProperty("resource", newUrl.path());
626 QString hash = clip->getClipHash();
627 KUrl oldVideoThumbUrl = KUrl(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".png");
628 KUrl oldAudioThumbUrl = KUrl(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".thumb");
629 if (KIO::NetAccess::exists(oldVideoThumbUrl, KIO::NetAccess::SourceSide, 0)) {
630 KUrl newUrl = KUrl(url.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".png");
631 KIO::Job *job = KIO::copy(oldVideoThumbUrl, newUrl);
632 KIO::NetAccess::synchronousRun(job, 0);
634 if (KIO::NetAccess::exists(oldAudioThumbUrl, KIO::NetAccess::SourceSide, 0)) {
635 KUrl newUrl = KUrl(url.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".thumb");
636 KIO::Job *job = KIO::copy(oldAudioThumbUrl, newUrl);
637 if (KIO::NetAccess::synchronousRun(job, 0)) clip->refreshThumbUrl();
642 const QString &KdenliveDoc::profilePath() const
644 return m_profile.path;
647 MltVideoProfile KdenliveDoc::mltProfile() const
652 bool KdenliveDoc::setProfilePath(QString path)
654 if (path.isEmpty()) path = KdenliveSettings::default_profile();
655 if (path.isEmpty()) path = "dv_pal";
656 m_profile = ProfilesDialog::getVideoProfile(path);
657 bool current_fps = m_fps;
658 if (m_profile.path.isEmpty()) {
659 // Profile not found, use embedded profile
660 QDomElement profileInfo = m_document.elementsByTagName("profileinfo").at(0).toElement();
661 if (profileInfo.isNull()) {
662 KMessageBox::information(kapp->activeWindow(), i18n("Project profile was not found, using default profile."), i18n("Missing Profile"));
663 m_profile = ProfilesDialog::getVideoProfile(KdenliveSettings::default_profile());
665 m_profile.description = profileInfo.attribute("description");
666 m_profile.frame_rate_num = profileInfo.attribute("frame_rate_num").toInt();
667 m_profile.frame_rate_den = profileInfo.attribute("frame_rate_den").toInt();
668 m_profile.width = profileInfo.attribute("width").toInt();
669 m_profile.height = profileInfo.attribute("height").toInt();
670 m_profile.progressive = profileInfo.attribute("progressive").toInt();
671 m_profile.sample_aspect_num = profileInfo.attribute("sample_aspect_num").toInt();
672 m_profile.sample_aspect_den = profileInfo.attribute("sample_aspect_den").toInt();
673 m_profile.display_aspect_num = profileInfo.attribute("display_aspect_num").toInt();
674 m_profile.display_aspect_den = profileInfo.attribute("display_aspect_den").toInt();
675 QString existing = ProfilesDialog::existingProfile(m_profile);
676 if (!existing.isEmpty()) {
677 m_profile = ProfilesDialog::getVideoProfile(existing);
678 KMessageBox::information(kapp->activeWindow(), i18n("Project profile not found, replacing with existing one: %1", m_profile.description), i18n("Missing Profile"));
680 QString newDesc = m_profile.description;
682 while (ok && (newDesc.isEmpty() || ProfilesDialog::existingProfileDescription(newDesc))) {
683 newDesc = QInputDialog::getText(kapp->activeWindow(), i18n("Existing Profile"), i18n("Your project uses an unknown profile.\nIt uses an existing profile name: %1.\nPlease choose a new name to save it", newDesc), QLineEdit::Normal, newDesc, &ok);
686 // User canceled, use default profile
687 m_profile = ProfilesDialog::getVideoProfile(KdenliveSettings::default_profile());
689 if (newDesc != m_profile.description) {
690 // Profile description existed, was replaced by new one
691 m_profile.description = newDesc;
693 KMessageBox::information(kapp->activeWindow(), i18n("Project profile was not found, it will be added to your system now."), i18n("Missing Profile"));
695 ProfilesDialog::saveProfile(m_profile);
702 KdenliveSettings::setProject_display_ratio((double) m_profile.display_aspect_num / m_profile.display_aspect_den);
703 m_fps = (double) m_profile.frame_rate_num / m_profile.frame_rate_den;
704 KdenliveSettings::setProject_fps(m_fps);
705 m_width = m_profile.width;
706 m_height = m_profile.height;
707 kDebug() << "Kdenlive document, init timecode from path: " << path << ", " << m_fps;
708 if (m_fps == 30000.0 / 1001.0) m_timecode.setFormat(m_fps, true);
709 else m_timecode.setFormat(m_fps);
710 return (current_fps != m_fps);
713 double KdenliveDoc::dar()
715 return (double) m_profile.display_aspect_num / m_profile.display_aspect_den;
718 void KdenliveDoc::setThumbsProgress(const QString &message, int progress)
720 emit progressInfo(message, progress);
723 void KdenliveDoc::loadingProgressed()
725 m_documentLoadingProgress += m_documentLoadingStep;
726 emit progressInfo(QString(), (int) m_documentLoadingProgress);
729 QUndoStack *KdenliveDoc::commandStack()
731 return m_commandStack;
735 void KdenliveDoc::setRenderer(Render *render) {
736 if (m_render) return;
738 emit progressInfo(i18n("Loading playlist..."), 0);
739 //qApp->processEvents();
741 m_render->setSceneList(m_document.toString(), m_startPos);
742 kDebug() << "// SETTING SCENE LIST:\n\n" << m_document.toString();
745 emit progressInfo(QString(), -1);
748 void KdenliveDoc::checkProjectClips()
750 kDebug() << "+++++++++++++ + + + + CHK PCLIPS";
751 if (m_render == NULL) return;
752 m_clipManager->resetProducersList(m_render->producersList());
755 void KdenliveDoc::updatePreviewSettings()
757 m_clipManager->updatePreviewSettings();
758 m_render->updatePreviewSettings();
759 QList <Mlt::Producer *> prods = m_render->producersList();
760 m_clipManager->resetProducersList(m_render->producersList());
765 Render *KdenliveDoc::renderer()
770 void KdenliveDoc::updateClip(const QString id)
772 emit updateClipDisplay(id);
775 int KdenliveDoc::getFramePos(QString duration)
777 return m_timecode.getFrameCount(duration);
780 QString KdenliveDoc::producerName(const QString &id)
782 QString result = "unnamed";
783 QDomNodeList prods = producersList();
784 int ct = prods.count();
785 for (int i = 0; i < ct ; i++) {
786 QDomElement e = prods.item(i).toElement();
787 if (e.attribute("id") != "black" && e.attribute("id") == id) {
788 result = e.attribute("name");
789 if (result.isEmpty()) result = KUrl(e.attribute("resource")).fileName();
796 QDomDocument KdenliveDoc::toXml()
801 Timecode KdenliveDoc::timecode() const
806 QDomNodeList KdenliveDoc::producersList()
808 return m_document.elementsByTagName("producer");
811 double KdenliveDoc::projectDuration() const
814 return GenTime(m_render->getLength(), m_fps).ms() / 1000;
819 double KdenliveDoc::fps() const
824 int KdenliveDoc::width() const
829 int KdenliveDoc::height() const
834 KUrl KdenliveDoc::url() const
839 void KdenliveDoc::setUrl(KUrl url)
844 void KdenliveDoc::setModified(bool mod)
846 if (!m_url.isEmpty() && mod && KdenliveSettings::crashrecovery()) {
847 m_autoSaveTimer->start(3000);
849 if (mod == m_modified) return;
851 emit docModified(m_modified);
854 bool KdenliveDoc::isModified() const
859 const QString KdenliveDoc::description() const
862 return i18n("Untitled") + " / " + m_profile.description;
864 return m_url.fileName() + " / " + m_profile.description;
867 void KdenliveDoc::addClip(QDomElement elem, QString clipId, bool createClipItem)
869 const QString producerId = clipId.section('_', 0, 0);
870 DocClipBase *clip = m_clipManager->getClipById(producerId);
873 elem.setAttribute("id", producerId);
874 QString path = elem.attribute("resource");
876 if (elem.attribute("type").toInt() == SLIDESHOW) {
877 extension = KUrl(path).fileName();
878 path = KUrl(path).directory();
881 if (path.isEmpty() == false && QFile::exists(path) == false && elem.attribute("type").toInt() != TEXT && !elem.hasAttribute("placeholder")) {
882 kDebug() << "// FOUND MISSING CLIP: " << path << ", TYPE: " << elem.attribute("type").toInt();
883 const QString size = elem.attribute("file_size");
884 const QString hash = elem.attribute("file_hash");
886 int action = KMessageBox::No;
887 if (!size.isEmpty() && !hash.isEmpty()) {
888 if (!m_searchFolder.isEmpty()) newpath = searchFileRecursively(m_searchFolder, size, hash);
889 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")));
891 if (elem.attribute("type").toInt() == SLIDESHOW) {
892 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")));
893 if (res == KMessageBox::Yes)
894 newpath = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow(), i18n("Looking for %1", path));
896 // Abort project loading
900 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")));
901 if (res == KMessageBox::Yes)
902 newpath = KFileDialog::getOpenFileName(KUrl("kfiledialog:///clipfolder"), QString(), kapp->activeWindow(), i18n("Looking for %1", path));
904 // Abort project loading
909 if (action == KMessageBox::Yes) {
910 kDebug() << "// ASKED FOR SRCH CLIP: " << clipId;
911 m_searchFolder = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow());
912 if (!m_searchFolder.isEmpty()) {
913 newpath = searchFileRecursively(QDir(m_searchFolder), size, hash);
915 } else if (action == KMessageBox::Cancel) {
916 m_abortLoading = true;
918 } else if (action == KMessageBox::No) {
919 // Keep clip as placeHolder
920 elem.setAttribute("placeholder", '1');
922 if (!newpath.isEmpty()) {
923 if (elem.attribute("type").toInt() == SLIDESHOW) newpath.append('/' + extension);
924 elem.setAttribute("resource", newpath);
925 setNewClipResource(clipId, newpath);
929 clip = new DocClipBase(m_clipManager, elem, producerId);
930 m_clipManager->addClip(clip);
933 if (createClipItem) {
934 emit addProjectClip(clip);
935 //qApp->processEvents();
940 void KdenliveDoc::setNewClipResource(const QString &id, const QString &path)
942 QDomNodeList prods = m_document.elementsByTagName("producer");
943 int maxprod = prods.count();
944 for (int i = 0; i < maxprod; i++) {
945 QDomNode m = prods.at(i);
946 QString prodId = m.toElement().attribute("id");
947 if (prodId == id || prodId.startsWith(id + '_')) {
948 QDomNodeList params = m.childNodes();
949 for (int j = 0; j < params.count(); j++) {
950 QDomElement e = params.item(j).toElement();
951 if (e.attribute("name") == "resource") {
952 e.firstChild().setNodeValue(path);
960 QString KdenliveDoc::searchFileRecursively(const QDir &dir, const QString &matchSize, const QString &matchHash) const
962 QString foundFileName;
965 QStringList filesAndDirs = dir.entryList(QDir::Files | QDir::Readable);
966 for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
967 QFile file(dir.absoluteFilePath(filesAndDirs.at(i)));
968 if (file.open(QIODevice::ReadOnly)) {
969 if (QString::number(file.size()) == matchSize) {
971 * 1 MB = 1 second per 450 files (or faster)
972 * 10 MB = 9 seconds per 450 files (or faster)
974 if (file.size() > 1000000*2) {
975 fileData = file.read(1000000);
976 if (file.seek(file.size() - 1000000))
977 fileData.append(file.readAll());
979 fileData = file.readAll();
981 fileHash = QCryptographicHash::hash(fileData, QCryptographicHash::Md5);
982 if (QString(fileHash.toHex()) == matchHash)
983 return file.fileName();
986 kDebug() << filesAndDirs.at(i) << file.size() << fileHash.toHex();
988 filesAndDirs = dir.entryList(QDir::Dirs | QDir::Readable | QDir::Executable | QDir::NoDotAndDotDot);
989 for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
990 foundFileName = searchFileRecursively(dir.absoluteFilePath(filesAndDirs.at(i)), matchSize, matchHash);
991 if (!foundFileName.isEmpty())
994 return foundFileName;
997 void KdenliveDoc::addClipInfo(QDomElement elem, QDomElement orig, QString clipId)
999 DocClipBase *clip = m_clipManager->getClipById(clipId);
1001 addClip(elem, clipId, false);
1003 QMap <QString, QString> properties;
1004 QDomNamedNodeMap attributes = elem.attributes();
1006 for (int i = 0; i < attributes.count(); i++) {
1007 attrname = attributes.item(i).nodeName();
1008 if (attrname != "resource")
1009 properties.insert(attrname, attributes.item(i).nodeValue());
1010 kDebug() << attrname << " = " << attributes.item(i).nodeValue();
1012 clip->setProperties(properties);
1013 emit addProjectClip(clip, false);
1015 if (orig != QDomElement()) {
1016 QMap<QString, QString> meta;
1017 QDomNode m = orig.firstChild();
1018 while (!m.isNull()) {
1019 QString name = m.toElement().attribute("name");
1020 if (name.startsWith("meta.attr")) {
1021 meta.insert(name.section('.', 2, 3), m.firstChild().nodeValue());
1023 m = m.nextSibling();
1025 if (!meta.isEmpty()) {
1026 if (clip == NULL) clip = m_clipManager->getClipById(clipId);
1027 if (clip) clip->setMetadata(meta);
1032 void KdenliveDoc::deleteProjectClip(QStringList ids)
1034 for (int i = 0; i < ids.size(); ++i) {
1035 emit deleteTimelineClip(ids.at(i));
1037 m_clipManager->slotDeleteClips(ids);
1041 void KdenliveDoc::deleteClip(const QString &clipId)
1043 emit signalDeleteProjectClip(clipId);
1046 void KdenliveDoc::slotAddClipList(const KUrl::List urls, const QString group, const QString &groupId)
1048 m_clipManager->slotAddClipList(urls, group, groupId);
1049 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1054 void KdenliveDoc::slotAddClipFile(const KUrl url, const QString group, const QString &groupId)
1056 m_clipManager->slotAddClipFile(url, group, groupId);
1057 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1061 const QString KdenliveDoc::getFreeClipId()
1063 return QString::number(m_clipManager->getFreeClipId());
1066 DocClipBase *KdenliveDoc::getBaseClip(const QString &clipId)
1068 return m_clipManager->getClipById(clipId);
1071 void KdenliveDoc::slotCreateColorClip(const QString &name, const QString &color, const QString &duration, QString group, const QString &groupId)
1073 m_clipManager->slotAddColorClipFile(name, color, duration, group, groupId);
1075 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1078 void KdenliveDoc::slotCreateSlideshowClipFile(const QString name, const QString path, int count, const QString duration, const bool loop, const bool fade, const QString &luma_duration, const QString &luma_file, const int softness, QString group, const QString &groupId)
1080 m_clipManager->slotAddSlideshowClipFile(name, path, count, duration, loop, fade, luma_duration, luma_file, softness, group, groupId);
1082 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1085 void KdenliveDoc::slotCreateTextClip(QString group, const QString &groupId, const QString &templatePath)
1087 QString titlesFolder = projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
1088 KStandardDirs::makeDir(titlesFolder);
1089 TitleWidget *dia_ui = new TitleWidget(templatePath, m_timecode, titlesFolder, m_render, kapp->activeWindow());
1090 if (dia_ui->exec() == QDialog::Accepted) {
1091 m_clipManager->slotAddTextClipFile(i18n("Title clip"), dia_ui->duration(), dia_ui->xml().toString(), group, groupId);
1093 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1098 void KdenliveDoc::slotCreateTextTemplateClip(QString group, const QString &groupId, KUrl path)
1100 QString titlesFolder = projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
1101 if (path.isEmpty()) {
1102 path = KFileDialog::getOpenUrl(KUrl(titlesFolder), "*.kdenlivetitle", kapp->activeWindow(), i18n("Enter Template Path"));
1105 if (path.isEmpty()) return;
1107 //TODO: rewrite with new title system (just set resource)
1108 m_clipManager->slotAddTextTemplateClip(i18n("Template title clip"), path, group, groupId);
1110 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1113 int KdenliveDoc::tracksCount() const
1115 return m_tracksList.count();
1118 TrackInfo KdenliveDoc::trackInfoAt(int ix) const
1120 return m_tracksList.at(ix);
1123 void KdenliveDoc::switchTrackAudio(int ix, bool hide)
1125 m_tracksList[ix].isMute = hide; // !m_tracksList.at(ix).isMute;
1128 void KdenliveDoc::switchTrackLock(int ix, bool lock)
1130 m_tracksList[ix].isLocked = lock;
1133 bool KdenliveDoc::isTrackLocked(int ix) const
1135 return m_tracksList.at(ix).isLocked;
1138 void KdenliveDoc::switchTrackVideo(int ix, bool hide)
1140 m_tracksList[ix].isBlind = hide; // !m_tracksList.at(ix).isBlind;
1143 void KdenliveDoc::insertTrack(int ix, TrackInfo type)
1145 if (ix == -1) m_tracksList << type;
1146 else m_tracksList.insert(ix, type);
1149 void KdenliveDoc::deleteTrack(int ix)
1151 m_tracksList.removeAt(ix);
1154 void KdenliveDoc::setTrackType(int ix, TrackInfo type)
1156 m_tracksList[ix].type = type.type;
1157 m_tracksList[ix].isMute = type.isMute;
1158 m_tracksList[ix].isBlind = type.isBlind;
1159 m_tracksList[ix].isLocked = type.isLocked;
1160 m_tracksList[ix].trackName = type.trackName;
1163 const QList <TrackInfo> KdenliveDoc::tracksList() const
1165 return m_tracksList;
1168 QPoint KdenliveDoc::getTracksCount() const
1172 foreach(const TrackInfo &info, m_tracksList) {
1173 if (info.type == VIDEOTRACK) video++;
1176 return QPoint(video, audio);
1179 void KdenliveDoc::cachePixmap(const QString &fileId, const QPixmap &pix) const
1181 pix.save(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + fileId + ".png");
1184 QString KdenliveDoc::getLadspaFile() const
1187 QString counter = QString::number(ct).rightJustified(5, '0', false);
1188 while (QFile::exists(m_projectFolder.path(KUrl::AddTrailingSlash) + "ladspa/" + counter + ".ladspa")) {
1190 counter = QString::number(ct).rightJustified(5, '0', false);
1192 return m_projectFolder.path(KUrl::AddTrailingSlash) + "ladspa/" + counter + ".ladspa";
1195 bool KdenliveDoc::checkDocumentClips(QDomNodeList infoproducers)
1201 QList <QDomElement> missingClips;
1202 for (int i = 0; i < infoproducers.count(); i++) {
1203 e = infoproducers.item(i).toElement();
1204 clipType = e.attribute("type").toInt();
1205 if (clipType == COLOR) continue;
1206 if (clipType == TEXT) {
1207 //TODO: Check is clip template is missing (xmltemplate) or hash changed
1210 id = e.attribute("id");
1211 resource = e.attribute("resource");
1212 if (clipType == SLIDESHOW) resource = KUrl(resource).directory();
1213 if (!KIO::NetAccess::exists(KUrl(resource), KIO::NetAccess::SourceSide, 0)) {
1214 // Missing clip found
1215 missingClips.append(e);
1217 // Check if the clip has changed
1218 if (clipType != SLIDESHOW && e.hasAttribute("file_hash")) {
1219 if (e.attribute("file_hash") != DocClipBase::getHash(e.attribute("resource")))
1220 e.removeAttribute("file_hash");
1224 if (missingClips.isEmpty()) return true;
1225 DocumentChecker d(missingClips, m_document);
1226 return (d.exec() == QDialog::Accepted);
1229 void KdenliveDoc::setDocumentProperty(const QString &name, const QString &value)
1231 m_documentProperties[name] = value;
1234 const QString KdenliveDoc::getDocumentProperty(const QString &name) const
1236 return m_documentProperties.value(name);
1239 #include "kdenlivedoc.moc"