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);
84 if (!success) // It is corrupted
85 KMessageBox::error(parent, errorMsg);
87 DocumentValidator validator(m_document);
88 success = validator.isProject();
89 if (!success) // It is not a project file
90 parent->slotGotProgressInfo(i18n("File %1 is not a Kdenlive project file.", m_url.path()), 100);
93 * Validate the file against the current version (upgrade
94 * and recover it if needed). It is NOT a passive operation
96 // TODO: backup the document or alert the user?
97 success = validator.validate(DOCUMENTVERSION);
98 if (success) { // Let the validator handle error messages
99 QDomElement mlt = m_document.firstChildElement("mlt");
100 QDomElement infoXml = mlt.firstChildElement("kdenlivedoc");
102 profileName = infoXml.attribute("profile");
103 m_projectFolder = KUrl(infoXml.attribute("projectfolder"));
104 QDomElement docproperties = infoXml.firstChildElement("documentproperties");
105 QDomNamedNodeMap props = docproperties.attributes();
106 for (int i = 0; i < props.count(); i++) {
107 m_documentProperties.insert(props.item(i).nodeName(), props.item(i).nodeValue());
111 QDomElement tracksinfo = infoXml.firstChildElement("tracksinfo");
112 TrackInfo projectTrack;
113 if (!tracksinfo.isNull()) {
114 QDomNodeList trackslist = tracksinfo.childNodes();
115 int maxchild = trackslist.count();
116 for (int k = 0; k < maxchild; k++) {
117 e = trackslist.at(k).toElement();
118 if (e.tagName() == "trackinfo") {
119 if (e.attribute("type") == "audio") projectTrack.type = AUDIOTRACK;
120 else projectTrack.type = VIDEOTRACK;
121 projectTrack.isMute = e.attribute("mute").toInt();
122 projectTrack.isBlind = e.attribute("blind").toInt();
123 projectTrack.isLocked = e.attribute("locked").toInt();
124 m_tracksList.append(projectTrack);
127 mlt.removeChild(tracksinfo);
129 QDomNodeList producers = m_document.elementsByTagName("producer");
130 QDomNodeList infoproducers = m_document.elementsByTagName("kdenlive_producer");
131 if (checkDocumentClips(infoproducers) == false) m_abortLoading = true;
132 const int max = producers.count();
133 const int infomax = infoproducers.count();
135 QDomNodeList folders = m_document.elementsByTagName("folder");
136 for (int i = 0; i < folders.count(); i++) {
137 e = folders.item(i).cloneNode().toElement();
138 m_clipManager->addFolder(e.attribute("id"), e.attribute("name"));
142 m_documentLoadingStep = 100.0 / (max + infomax + m_document.elementsByTagName("entry").count());
143 parent->slotGotProgressInfo(i18n("Loading project clips"), (int) m_documentLoadingProgress);
147 for (int i = 0; i < infomax && !m_abortLoading; i++) {
148 e = infoproducers.item(i).cloneNode().toElement();
149 if (m_documentLoadingStep > 0) {
150 m_documentLoadingProgress += m_documentLoadingStep;
151 parent->slotGotProgressInfo(QString(), (int) m_documentLoadingProgress);
152 //qApp->processEvents();
154 QString prodId = e.attribute("id");
155 if (!e.isNull() && prodId != "black" && !prodId.startsWith("slowmotion") && !m_abortLoading) {
156 e.setTagName("producer");
157 // Get MLT's original producer properties
159 for (int j = 0; j < max; j++) {
160 QDomElement o = producers.item(j).cloneNode().toElement();
161 QString origId = o.attribute("id").section('_', 0, 0);
162 if (origId == prodId) {
167 addClipInfo(e, orig, prodId);
168 kDebug() << "// KDENLIVE PRODUCER: " << prodId;
171 if (m_abortLoading) {
172 //parent->slotGotProgressInfo(i18n("File %1 is not a Kdenlive project file."), 100);
173 emit resetProjectList();
174 m_documentProperties.remove("position");
176 m_tracksList.clear();
177 kWarning() << "Aborted loading of: " << url.path();
178 m_document = createEmptyDocument(KdenliveSettings::videotracks(), KdenliveSettings::audiotracks());
179 setProfilePath(KdenliveSettings::default_profile());
180 m_clipManager->clear();
182 QDomElement markers = infoXml.firstChildElement("markers");
183 if (!markers.isNull()) {
184 QDomNodeList markerslist = markers.childNodes();
185 int maxchild = markerslist.count();
186 for (int k = 0; k < maxchild; k++) {
187 e = markerslist.at(k).toElement();
188 if (e.tagName() == "marker") {
189 m_clipManager->getClipById(e.attribute("id"))->addSnapMarker(GenTime(e.attribute("time").toDouble()), e.attribute("comment"));
192 infoXml.removeChild(markers);
194 setProfilePath(profileName);
195 setModified(validator.isModified());
196 kDebug() << "Reading file: " << url.path() << ", found clips: " << producers.count();
202 } else setProfilePath(profileName);
204 // Something went wrong, or a new file was requested: create a new project
206 setProfilePath(QString());
208 m_document = createEmptyDocument(tracks.x(), tracks.y());
211 // Set the video profile (empty == default)
213 // Make sure the project folder is usable
214 if (m_projectFolder.isEmpty() || !KIO::NetAccess::exists(m_projectFolder.path(), KIO::NetAccess::DestinationSide, parent)) {
215 KMessageBox::information(parent, i18n("Document project folder is invalid, setting it to the default one: %1", KdenliveSettings::defaultprojectfolder()));
216 m_projectFolder = KUrl(KdenliveSettings::defaultprojectfolder());
219 // Make sure that the necessary folders exist
220 KStandardDirs::makeDir(m_projectFolder.path(KUrl::AddTrailingSlash) + "titles/");
221 KStandardDirs::makeDir(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/");
222 KStandardDirs::makeDir(m_projectFolder.path(KUrl::AddTrailingSlash) + "ladspa/");
224 kDebug() << "Kdenlive document, init timecode: " << m_fps;
225 if (m_fps == 30000.0 / 1001.0) m_timecode.setFormat(30, true);
226 else m_timecode.setFormat((int)(m_fps + 0.5));
228 //kDebug() << "// SETTING SCENE LIST:\n\n" << m_document.toString();
229 connect(m_autoSaveTimer, SIGNAL(timeout()), this, SLOT(slotAutoSave()));
232 KdenliveDoc::~KdenliveDoc()
234 m_autoSaveTimer->stop();
235 delete m_commandStack;
236 kDebug() << "// DEL CLP MAN";
237 delete m_clipManager;
238 kDebug() << "// DEL CLP MAN done";
239 delete m_autoSaveTimer;
241 if (!m_autosave->fileName().isEmpty()) m_autosave->remove();
246 int KdenliveDoc::setSceneList()
248 if (m_render->setSceneList(m_document.toString(), m_documentProperties.value("position").toInt()) == -1) {
249 // INVALID MLT Consumer, something is wrong
252 m_documentProperties.remove("position");
253 // m_document xml is now useless, clear it
259 QDomDocument KdenliveDoc::createEmptyDocument(const int videotracks, const int audiotracks)
261 // Creating new document
263 QDomElement mlt = doc.createElement("mlt");
264 doc.appendChild(mlt);
267 TrackInfo videoTrack;
268 videoTrack.type = VIDEOTRACK;
269 videoTrack.isMute = false;
270 videoTrack.isBlind = false;
271 videoTrack.isLocked = false;
273 TrackInfo audioTrack;
274 audioTrack.type = AUDIOTRACK;
275 audioTrack.isMute = false;
276 audioTrack.isBlind = true;
277 audioTrack.isLocked = false;
279 QDomElement tractor = doc.createElement("tractor");
280 tractor.setAttribute("id", "maintractor");
281 QDomElement multitrack = doc.createElement("multitrack");
282 QDomElement playlist = doc.createElement("playlist");
283 playlist.setAttribute("id", "black_track");
284 mlt.appendChild(playlist);
288 int total = audiotracks + videotracks + 1;
290 for (int i = 1; i < total; i++) {
291 QDomElement playlist = doc.createElement("playlist");
292 playlist.setAttribute("id", "playlist" + QString::number(i));
293 mlt.appendChild(playlist);
296 QDomElement track0 = doc.createElement("track");
297 track0.setAttribute("producer", "black_track");
298 tractor.appendChild(track0);
300 // create audio tracks
301 for (int i = 1; i < audiotracks + 1; i++) {
302 QDomElement track = doc.createElement("track");
303 track.setAttribute("producer", "playlist" + QString::number(i));
304 track.setAttribute("hide", "video");
305 tractor.appendChild(track);
306 m_tracksList.append(audioTrack);
309 // create video tracks
310 for (int i = audiotracks + 1; i < total; i++) {
311 QDomElement track = doc.createElement("track");
312 track.setAttribute("producer", "playlist" + QString::number(i));
313 tractor.appendChild(track);
314 m_tracksList.append(videoTrack);
317 for (int i = 2; i < total ; i++) {
318 QDomElement transition = doc.createElement("transition");
319 transition.setAttribute("always_active", "1");
321 QDomElement property = doc.createElement("property");
322 property.setAttribute("name", "a_track");
323 QDomText value = doc.createTextNode(QString::number(1));
324 property.appendChild(value);
325 transition.appendChild(property);
327 property = doc.createElement("property");
328 property.setAttribute("name", "b_track");
329 value = doc.createTextNode(QString::number(i));
330 property.appendChild(value);
331 transition.appendChild(property);
333 property = doc.createElement("property");
334 property.setAttribute("name", "mlt_service");
335 value = doc.createTextNode("mix");
336 property.appendChild(value);
337 transition.appendChild(property);
339 property = doc.createElement("property");
340 property.setAttribute("name", "combine");
341 value = doc.createTextNode("1");
342 property.appendChild(value);
343 transition.appendChild(property);
345 property = doc.createElement("property");
346 property.setAttribute("name", "internal_added");
347 value = doc.createTextNode("237");
348 property.appendChild(value);
349 transition.appendChild(property);
350 tractor.appendChild(transition);
352 mlt.appendChild(tractor);
357 void KdenliveDoc::syncGuides(QList <Guide *> guides)
360 QDomElement guideNode = m_guidesXml.createElement("guides");
361 m_guidesXml.appendChild(guideNode);
364 for (int i = 0; i < guides.count(); i++) {
365 e = m_guidesXml.createElement("guide");
366 e.setAttribute("time", guides.at(i)->position().ms() / 1000);
367 e.setAttribute("comment", guides.at(i)->label());
368 guideNode.appendChild(e);
371 emit guidesUpdated();
374 QDomElement KdenliveDoc::guidesXml() const
376 return m_guidesXml.documentElement();
379 void KdenliveDoc::slotAutoSave()
381 if (m_render && m_autosave) {
382 if (!m_autosave->isOpen() && !m_autosave->open(QIODevice::ReadWrite)) {
383 // show error: could not open the autosave file
384 kDebug() << "ERROR; CANNOT CREATE AUTOSAVE FILE";
386 kDebug() << "// AUTOSAVE FILE: " << m_autosave->fileName();
388 if (KdenliveSettings::dropbframes()) {
389 KdenliveSettings::setDropbframes(false);
390 m_clipManager->updatePreviewSettings();
391 doc = m_render->sceneList();
392 KdenliveSettings::setDropbframes(true);
393 m_clipManager->updatePreviewSettings();
394 } else doc = m_render->sceneList();
395 saveSceneList(m_autosave->fileName(), doc);
399 void KdenliveDoc::setZoom(int horizontal, int vertical)
401 m_documentProperties["zoom"] = QString::number(horizontal);
402 m_documentProperties["verticalzoom"] = QString::number(vertical);
405 QPoint KdenliveDoc::zoom() const
407 return QPoint(m_documentProperties.value("zoom").toInt(), m_documentProperties.value("verticalzoom").toInt());
410 void KdenliveDoc::setZone(int start, int end)
412 m_documentProperties["zonein"] = QString::number(start);
413 m_documentProperties["zoneout"] = QString::number(end);
416 QPoint KdenliveDoc::zone() const
418 return QPoint(m_documentProperties.value("zonein").toInt(), m_documentProperties.value("zoneout").toInt());
421 bool KdenliveDoc::saveSceneList(const QString &path, const QString &scene)
423 QDomDocument sceneList;
424 sceneList.setContent(scene, true);
425 QDomElement mlt = sceneList.firstChildElement("mlt");
426 QDomElement addedXml = sceneList.createElement("kdenlivedoc");
427 mlt.appendChild(addedXml);
429 QDomElement markers = sceneList.createElement("markers");
430 addedXml.setAttribute("version", DOCUMENTVERSION);
431 addedXml.setAttribute("kdenliveversion", VERSION);
432 addedXml.setAttribute("profile", profilePath());
433 addedXml.setAttribute("projectfolder", m_projectFolder.path());
435 QDomElement docproperties = sceneList.createElement("documentproperties");
436 QMapIterator<QString, QString> i(m_documentProperties);
437 while (i.hasNext()) {
439 docproperties.setAttribute(i.key(), i.value());
441 docproperties.setAttribute("position", m_render->seekPosition().frames(m_fps));
442 addedXml.appendChild(docproperties);
445 QDomElement profileinfo = sceneList.createElement("profileinfo");
446 profileinfo.setAttribute("description", m_profile.description);
447 profileinfo.setAttribute("frame_rate_num", m_profile.frame_rate_num);
448 profileinfo.setAttribute("frame_rate_den", m_profile.frame_rate_den);
449 profileinfo.setAttribute("width", m_profile.width);
450 profileinfo.setAttribute("height", m_profile.height);
451 profileinfo.setAttribute("progressive", m_profile.progressive);
452 profileinfo.setAttribute("sample_aspect_num", m_profile.sample_aspect_num);
453 profileinfo.setAttribute("sample_aspect_den", m_profile.sample_aspect_den);
454 profileinfo.setAttribute("display_aspect_num", m_profile.display_aspect_num);
455 profileinfo.setAttribute("display_aspect_den", m_profile.display_aspect_den);
456 addedXml.appendChild(profileinfo);
459 QDomElement tracksinfo = sceneList.createElement("tracksinfo");
460 foreach(const TrackInfo &info, m_tracksList) {
461 QDomElement trackinfo = sceneList.createElement("trackinfo");
462 if (info.type == AUDIOTRACK) trackinfo.setAttribute("type", "audio");
463 trackinfo.setAttribute("mute", info.isMute);
464 trackinfo.setAttribute("blind", info.isBlind);
465 trackinfo.setAttribute("locked", info.isLocked);
466 tracksinfo.appendChild(trackinfo);
468 addedXml.appendChild(tracksinfo);
470 // save project folders
471 QMap <QString, QString> folderlist = m_clipManager->documentFolderList();
473 QMapIterator<QString, QString> f(folderlist);
474 while (f.hasNext()) {
476 QDomElement folder = sceneList.createElement("folder");
477 folder.setAttribute("id", f.key());
478 folder.setAttribute("name", f.value());
479 addedXml.appendChild(folder);
482 // Save project clips
484 QList <DocClipBase*> list = m_clipManager->documentClipList();
485 for (int i = 0; i < list.count(); i++) {
486 e = list.at(i)->toXML();
487 e.setTagName("kdenlive_producer");
488 addedXml.appendChild(sceneList.importNode(e, true));
489 QList < CommentedTime > marks = list.at(i)->commentedSnapMarkers();
490 for (int j = 0; j < marks.count(); j++) {
491 QDomElement marker = sceneList.createElement("marker");
492 marker.setAttribute("time", marks.at(j).time().ms() / 1000);
493 marker.setAttribute("comment", marks.at(j).comment());
494 marker.setAttribute("id", e.attribute("id"));
495 markers.appendChild(marker);
498 addedXml.appendChild(markers);
501 if (!m_guidesXml.isNull()) addedXml.appendChild(sceneList.importNode(m_guidesXml.documentElement(), true));
504 addedXml.appendChild(sceneList.importNode(m_clipManager->groupsXml(), true));
506 //wes.appendChild(doc.importNode(kdenliveData, true));
509 if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
510 kWarning() << "////// ERROR writing to file: " << path;
511 KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1", path));
515 file.write(sceneList.toString().toUtf8());
516 if (file.error() != QFile::NoError) {
517 KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1", path));
525 ClipManager *KdenliveDoc::clipManager()
527 return m_clipManager;
530 KUrl KdenliveDoc::projectFolder() const
532 //if (m_projectFolder.isEmpty()) return KUrl(KStandardDirs::locateLocal("appdata", "/projects/"));
533 return m_projectFolder;
536 void KdenliveDoc::setProjectFolder(KUrl url)
538 if (url == m_projectFolder) return;
540 KStandardDirs::makeDir(url.path());
541 KStandardDirs::makeDir(url.path(KUrl::AddTrailingSlash) + "titles/");
542 KStandardDirs::makeDir(url.path(KUrl::AddTrailingSlash) + "thumbs/");
543 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);
544 m_projectFolder = url;
547 void KdenliveDoc::moveProjectData(KUrl url)
549 QList <DocClipBase*> list = m_clipManager->documentClipList();
550 //TODO: Also move ladspa effects files
551 for (int i = 0; i < list.count(); i++) {
552 DocClipBase *clip = list.at(i);
553 if (clip->clipType() == TEXT) {
554 // the image for title clip must be moved
555 KUrl oldUrl = clip->fileURL();
556 KUrl newUrl = KUrl(url.path(KUrl::AddTrailingSlash) + "titles/" + oldUrl.fileName());
557 KIO::Job *job = KIO::copy(oldUrl, newUrl);
558 if (KIO::NetAccess::synchronousRun(job, 0)) clip->setProperty("resource", newUrl.path());
560 QString hash = clip->getClipHash();
561 KUrl oldVideoThumbUrl = KUrl(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".png");
562 KUrl oldAudioThumbUrl = KUrl(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".thumb");
563 if (KIO::NetAccess::exists(oldVideoThumbUrl, KIO::NetAccess::SourceSide, 0)) {
564 KUrl newUrl = KUrl(url.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".png");
565 KIO::Job *job = KIO::copy(oldVideoThumbUrl, newUrl);
566 KIO::NetAccess::synchronousRun(job, 0);
568 if (KIO::NetAccess::exists(oldAudioThumbUrl, KIO::NetAccess::SourceSide, 0)) {
569 KUrl newUrl = KUrl(url.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".thumb");
570 KIO::Job *job = KIO::copy(oldAudioThumbUrl, newUrl);
571 if (KIO::NetAccess::synchronousRun(job, 0)) clip->refreshThumbUrl();
576 const QString &KdenliveDoc::profilePath() const
578 return m_profile.path;
581 MltVideoProfile KdenliveDoc::mltProfile() const
586 void KdenliveDoc::setProfilePath(QString path)
588 if (path.isEmpty()) path = KdenliveSettings::default_profile();
589 if (path.isEmpty()) path = "dv_pal";
590 m_profile = ProfilesDialog::getVideoProfile(path);
591 if (m_profile.path.isEmpty()) {
592 // Profile not found, use embedded profile
593 QDomElement profileInfo = m_document.elementsByTagName("profileinfo").at(0).toElement();
594 if (profileInfo.isNull()) {
595 KMessageBox::information(kapp->activeWindow(), i18n("Project profile was not found, using default profile."), i18n("Missing Profile"));
596 m_profile = ProfilesDialog::getVideoProfile(KdenliveSettings::default_profile());
598 m_profile.description = profileInfo.attribute("description");
599 m_profile.frame_rate_num = profileInfo.attribute("frame_rate_num").toInt();
600 m_profile.frame_rate_den = profileInfo.attribute("frame_rate_den").toInt();
601 m_profile.width = profileInfo.attribute("width").toInt();
602 m_profile.height = profileInfo.attribute("height").toInt();
603 m_profile.progressive = profileInfo.attribute("progressive").toInt();
604 m_profile.sample_aspect_num = profileInfo.attribute("sample_aspect_num").toInt();
605 m_profile.sample_aspect_den = profileInfo.attribute("sample_aspect_den").toInt();
606 m_profile.display_aspect_num = profileInfo.attribute("display_aspect_num").toInt();
607 m_profile.display_aspect_den = profileInfo.attribute("display_aspect_den").toInt();
608 QString existing = ProfilesDialog::existingProfile(m_profile);
609 if (!existing.isEmpty()) {
610 m_profile = ProfilesDialog::getVideoProfile(existing);
611 KMessageBox::information(kapp->activeWindow(), i18n("Project profile not found, replacing with existing one: %1", m_profile.description), i18n("Missing Profile"));
613 QString newDesc = m_profile.description;
615 while (ok && (newDesc.isEmpty() || ProfilesDialog::existingProfileDescription(newDesc))) {
616 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);
619 // User canceled, use default profile
620 m_profile = ProfilesDialog::getVideoProfile(KdenliveSettings::default_profile());
622 if (newDesc != m_profile.description) {
623 // Profile description existed, was replaced by new one
624 m_profile.description = newDesc;
626 KMessageBox::information(kapp->activeWindow(), i18n("Project profile was not found, it will be added to your system now."), i18n("Missing Profile"));
628 ProfilesDialog::saveProfile(m_profile);
635 KdenliveSettings::setProject_display_ratio((double) m_profile.display_aspect_num / m_profile.display_aspect_den);
636 m_fps = (double) m_profile.frame_rate_num / m_profile.frame_rate_den;
637 KdenliveSettings::setProject_fps(m_fps);
638 m_width = m_profile.width;
639 m_height = m_profile.height;
640 kDebug() << "Kdenlive document, init timecode from path: " << path << ", " << m_fps;
641 if (m_fps == 30000.0 / 1001.0) m_timecode.setFormat(30, true);
642 else m_timecode.setFormat((int)(m_fps + 0.5));
645 double KdenliveDoc::dar()
647 return (double) m_profile.display_aspect_num / m_profile.display_aspect_den;
650 void KdenliveDoc::setThumbsProgress(const QString &message, int progress)
652 emit progressInfo(message, progress);
655 void KdenliveDoc::loadingProgressed()
657 m_documentLoadingProgress += m_documentLoadingStep;
658 emit progressInfo(QString(), (int) m_documentLoadingProgress);
661 QUndoStack *KdenliveDoc::commandStack()
663 return m_commandStack;
667 void KdenliveDoc::setRenderer(Render *render) {
668 if (m_render) return;
670 emit progressInfo(i18n("Loading playlist..."), 0);
671 //qApp->processEvents();
673 m_render->setSceneList(m_document.toString(), m_startPos);
674 kDebug() << "// SETTING SCENE LIST:\n\n" << m_document.toString();
677 emit progressInfo(QString(), -1);
680 void KdenliveDoc::checkProjectClips()
682 kDebug() << "+++++++++++++ + + + + CHK PCLIPS";
683 if (m_render == NULL) return;
684 m_clipManager->resetProducersList(m_render->producersList());
687 void KdenliveDoc::updatePreviewSettings()
689 m_clipManager->updatePreviewSettings();
690 m_render->updatePreviewSettings();
691 m_clipManager->resetProducersList(m_render->producersList());
695 Render *KdenliveDoc::renderer()
700 void KdenliveDoc::updateClip(const QString &id)
702 emit updateClipDisplay(id);
705 int KdenliveDoc::getFramePos(QString duration)
707 return m_timecode.getFrameCount(duration, m_fps);
710 QString KdenliveDoc::producerName(const QString &id)
712 QString result = "unnamed";
713 QDomNodeList prods = producersList();
714 int ct = prods.count();
715 for (int i = 0; i < ct ; i++) {
716 QDomElement e = prods.item(i).toElement();
717 if (e.attribute("id") != "black" && e.attribute("id") == id) {
718 result = e.attribute("name");
719 if (result.isEmpty()) result = KUrl(e.attribute("resource")).fileName();
726 QDomDocument KdenliveDoc::toXml()
731 Timecode KdenliveDoc::timecode() const
736 QDomNodeList KdenliveDoc::producersList()
738 return m_document.elementsByTagName("producer");
741 double KdenliveDoc::projectDuration() const
744 return GenTime(m_render->getLength(), m_fps).ms() / 1000;
749 double KdenliveDoc::fps() const
754 int KdenliveDoc::width() const
759 int KdenliveDoc::height() const
764 KUrl KdenliveDoc::url() const
769 void KdenliveDoc::setUrl(KUrl url)
774 void KdenliveDoc::setModified(bool mod)
776 if (!m_url.isEmpty() && mod && KdenliveSettings::crashrecovery()) {
777 m_autoSaveTimer->start(3000);
779 if (mod == m_modified) return;
781 emit docModified(m_modified);
784 bool KdenliveDoc::isModified() const
789 const QString KdenliveDoc::description() const
792 return i18n("Untitled") + " / " + m_profile.description;
794 return m_url.fileName() + " / " + m_profile.description;
797 void KdenliveDoc::addClip(QDomElement elem, QString clipId, bool createClipItem)
799 const QString producerId = clipId.section('_', 0, 0);
800 DocClipBase *clip = m_clipManager->getClipById(producerId);
803 elem.setAttribute("id", producerId);
804 QString path = elem.attribute("resource");
806 if (elem.attribute("type").toInt() == SLIDESHOW) {
807 extension = KUrl(path).fileName();
808 path = KUrl(path).directory();
809 } /*else if (elem.attribute("type").toInt() == TEXT && QFile::exists(path) == false) {
810 kDebug() << "// TITLE: " << elem.attribute("name") << " Preview file: " << elem.attribute("resource") << " DOES NOT EXIST";
811 QString titlename = elem.attribute("name");
812 QString titleresource;
813 if (titlename.isEmpty()) {
814 QStringList titleInfo = TitleWidget::getFreeTitleInfo(projectFolder());
815 titlename = titleInfo.at(0);
816 titleresource = titleInfo.at(1);
817 elem.setAttribute("name", titlename);
818 kDebug() << "// New title set to: " << titlename;
820 titleresource = TitleWidget::getFreeTitleInfo(projectFolder()).at(1);
821 //titleresource = TitleWidget::getTitleResourceFromName(projectFolder(), titlename);
823 TitleWidget *dia_ui = new TitleWidget(KUrl(), KUrl(titleresource).directory(), m_render, kapp->activeWindow());
825 doc.setContent(elem.attribute("xmldata"));
827 QImage pix = dia_ui->renderedPixmap();
828 pix.save(titleresource);
829 elem.setAttribute("resource", titleresource);
830 setNewClipResource(clipId, titleresource);
834 if (path.isEmpty() == false && QFile::exists(path) == false && elem.attribute("type").toInt() != TEXT && !elem.hasAttribute("placeholder")) {
835 kDebug() << "// FOUND MISSING CLIP: " << path << ", TYPE: " << elem.attribute("type").toInt();
836 const QString size = elem.attribute("file_size");
837 const QString hash = elem.attribute("file_hash");
839 int action = KMessageBox::No;
840 if (!size.isEmpty() && !hash.isEmpty()) {
841 if (!m_searchFolder.isEmpty()) newpath = searchFileRecursively(m_searchFolder, size, hash);
842 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 if (elem.attribute("type").toInt() == SLIDESHOW) {
845 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")));
846 if (res == KMessageBox::Yes)
847 newpath = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow(), i18n("Looking for %1", path));
849 // Abort project loading
853 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")));
854 if (res == KMessageBox::Yes)
855 newpath = KFileDialog::getOpenFileName(KUrl("kfiledialog:///clipfolder"), QString(), kapp->activeWindow(), i18n("Looking for %1", path));
857 // Abort project loading
862 if (action == KMessageBox::Yes) {
863 kDebug() << "// ASKED FOR SRCH CLIP: " << clipId;
864 m_searchFolder = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow());
865 if (!m_searchFolder.isEmpty()) {
866 newpath = searchFileRecursively(QDir(m_searchFolder), size, hash);
868 } else if (action == KMessageBox::Cancel) {
869 m_abortLoading = true;
871 } else if (action == KMessageBox::No) {
872 // Keep clip as placeHolder
873 elem.setAttribute("placeholder", '1');
875 if (!newpath.isEmpty()) {
876 if (elem.attribute("type").toInt() == SLIDESHOW) newpath.append('/' + extension);
877 elem.setAttribute("resource", newpath);
878 setNewClipResource(clipId, newpath);
882 clip = new DocClipBase(m_clipManager, elem, producerId);
883 m_clipManager->addClip(clip);
886 if (createClipItem) {
887 emit addProjectClip(clip);
888 qApp->processEvents();
889 m_render->getFileProperties(clip->toXML(), clip->getId(), true);
894 void KdenliveDoc::setNewClipResource(const QString &id, const QString &path)
896 QDomNodeList prods = m_document.elementsByTagName("producer");
897 int maxprod = prods.count();
898 for (int i = 0; i < maxprod; i++) {
899 QDomNode m = prods.at(i);
900 QString prodId = m.toElement().attribute("id");
901 if (prodId == id || prodId.startsWith(id + '_')) {
902 QDomNodeList params = m.childNodes();
903 for (int j = 0; j < params.count(); j++) {
904 QDomElement e = params.item(j).toElement();
905 if (e.attribute("name") == "resource") {
906 e.firstChild().setNodeValue(path);
914 QString KdenliveDoc::searchFileRecursively(const QDir &dir, const QString &matchSize, const QString &matchHash) const
916 QString foundFileName;
919 QStringList filesAndDirs = dir.entryList(QDir::Files | QDir::Readable);
920 for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
921 QFile file(dir.absoluteFilePath(filesAndDirs.at(i)));
922 if (file.open(QIODevice::ReadOnly)) {
923 if (QString::number(file.size()) == matchSize) {
925 * 1 MB = 1 second per 450 files (or faster)
926 * 10 MB = 9 seconds per 450 files (or faster)
928 if (file.size() > 1000000*2) {
929 fileData = file.read(1000000);
930 if (file.seek(file.size() - 1000000))
931 fileData.append(file.readAll());
933 fileData = file.readAll();
935 fileHash = QCryptographicHash::hash(fileData, QCryptographicHash::Md5);
936 if (QString(fileHash.toHex()) == matchHash)
937 return file.fileName();
940 kDebug() << filesAndDirs.at(i) << file.size() << fileHash.toHex();
942 filesAndDirs = dir.entryList(QDir::Dirs | QDir::Readable | QDir::Executable | QDir::NoDotAndDotDot);
943 for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
944 foundFileName = searchFileRecursively(dir.absoluteFilePath(filesAndDirs.at(i)), matchSize, matchHash);
945 if (!foundFileName.isEmpty())
948 return foundFileName;
951 void KdenliveDoc::addClipInfo(QDomElement elem, QDomElement orig, QString clipId)
953 DocClipBase *clip = m_clipManager->getClipById(clipId);
955 addClip(elem, clipId, false);
957 QMap <QString, QString> properties;
958 QDomNamedNodeMap attributes = elem.attributes();
960 for (int i = 0; i < attributes.count(); i++) {
961 attrname = attributes.item(i).nodeName();
962 if (attrname != "resource")
963 properties.insert(attrname, attributes.item(i).nodeValue());
964 kDebug() << attrname << " = " << attributes.item(i).nodeValue();
966 clip->setProperties(properties);
967 emit addProjectClip(clip, false);
969 if (orig != QDomElement()) {
970 QMap<QString, QString> meta;
971 QDomNode m = orig.firstChild();
972 while (!m.isNull()) {
973 QString name = m.toElement().attribute("name");
974 if (name.startsWith("meta.attr")) {
975 meta.insert(name.section('.', 2, 3), m.firstChild().nodeValue());
979 if (!meta.isEmpty()) {
980 if (clip == NULL) clip = m_clipManager->getClipById(clipId);
981 if (clip) clip->setMetadata(meta);
986 void KdenliveDoc::deleteProjectClip(QList <QString> ids)
988 for (int i = 0; i < ids.size(); ++i) {
989 emit deleteTimelineClip(ids.at(i));
990 m_clipManager->slotDeleteClip(ids.at(i));
995 void KdenliveDoc::deleteClip(const QString &clipId)
997 emit signalDeleteProjectClip(clipId);
1000 void KdenliveDoc::slotAddClipList(const KUrl::List urls, const QString group, const QString &groupId)
1002 m_clipManager->slotAddClipList(urls, group, groupId);
1003 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1008 void KdenliveDoc::slotAddClipFile(const KUrl url, const QString group, const QString &groupId)
1010 m_clipManager->slotAddClipFile(url, group, groupId);
1011 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1015 const QString KdenliveDoc::getFreeClipId()
1017 return QString::number(m_clipManager->getFreeClipId());
1020 DocClipBase *KdenliveDoc::getBaseClip(const QString &clipId)
1022 return m_clipManager->getClipById(clipId);
1025 void KdenliveDoc::slotCreateColorClip(const QString &name, const QString &color, const QString &duration, QString group, const QString &groupId)
1027 m_clipManager->slotAddColorClipFile(name, color, duration, group, groupId);
1029 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1032 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)
1034 m_clipManager->slotAddSlideshowClipFile(name, path, count, duration, loop, fade, luma_duration, luma_file, softness, group, groupId);
1036 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1039 void KdenliveDoc::slotCreateTextClip(QString group, const QString &groupId, const QString &templatePath)
1041 QString titlesFolder = projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
1042 KStandardDirs::makeDir(titlesFolder);
1043 TitleWidget *dia_ui = new TitleWidget(templatePath, m_timecode, titlesFolder, m_render, kapp->activeWindow());
1044 if (dia_ui->exec() == QDialog::Accepted) {
1045 /*QStringList titleInfo = TitleWidget::getFreeTitleInfo(projectFolder());
1046 QImage pix = dia_ui->renderedPixmap();
1047 pix.save(titleInfo.at(1));*/
1048 //dia_ui->saveTitle(path + ".kdenlivetitle");
1049 m_clipManager->slotAddTextClipFile(i18n("Title clip"), dia_ui->duration(), dia_ui->xml().toString(), group, groupId);
1051 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1056 void KdenliveDoc::slotCreateTextTemplateClip(QString group, const QString &groupId, KUrl path)
1058 QString titlesFolder = projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
1059 if (path.isEmpty()) {
1060 path = KFileDialog::getOpenUrl(KUrl(titlesFolder), "*.kdenlivetitle", kapp->activeWindow(), i18n("Enter Template Path"));
1063 if (path.isEmpty()) return;
1065 QStringList titleInfo = TitleWidget::getFreeTitleInfo(projectFolder(), true);
1067 //TODO: rewrite with new title system (just set resource)
1068 /*TitleWidget *dia_ui = new TitleWidget(path, titlesFolder, m_render, kapp->activeWindow());
1069 QImage pix = dia_ui->renderedPixmap();
1070 pix.save(titleInfo.at(1));
1072 m_clipManager->slotAddTextTemplateClip(titleInfo.at(0), titleInfo.at(1), path, group, groupId);
1073 setModified(true);*/
1074 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1077 int KdenliveDoc::tracksCount() const
1079 return m_tracksList.count();
1082 TrackInfo KdenliveDoc::trackInfoAt(int ix) const
1084 return m_tracksList.at(ix);
1087 void KdenliveDoc::switchTrackAudio(int ix, bool hide)
1089 m_tracksList[ix].isMute = hide; // !m_tracksList.at(ix).isMute;
1092 void KdenliveDoc::switchTrackLock(int ix, bool lock)
1094 m_tracksList[ix].isLocked = lock;
1097 bool KdenliveDoc::isTrackLocked(int ix) const
1099 return m_tracksList.at(ix).isLocked;
1102 void KdenliveDoc::switchTrackVideo(int ix, bool hide)
1104 m_tracksList[ix].isBlind = hide; // !m_tracksList.at(ix).isBlind;
1107 void KdenliveDoc::insertTrack(int ix, TrackInfo type)
1109 if (ix == -1) m_tracksList << type;
1110 else m_tracksList.insert(ix, type);
1113 void KdenliveDoc::deleteTrack(int ix)
1115 m_tracksList.removeAt(ix);
1118 void KdenliveDoc::setTrackType(int ix, TrackInfo type)
1120 m_tracksList[ix].type = type.type;
1121 m_tracksList[ix].isMute = type.isMute;
1122 m_tracksList[ix].isBlind = type.isBlind;
1123 m_tracksList[ix].isLocked = type.isLocked;
1126 const QList <TrackInfo> KdenliveDoc::tracksList() const
1128 return m_tracksList;
1131 QPoint KdenliveDoc::getTracksCount() const
1135 foreach(const TrackInfo &info, m_tracksList) {
1136 if (info.type == VIDEOTRACK) video++;
1139 return QPoint(video, audio);
1142 void KdenliveDoc::cachePixmap(const QString &fileId, const QPixmap &pix) const
1144 pix.save(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + fileId + ".png");
1147 QString KdenliveDoc::getLadspaFile() const
1150 QString counter = QString::number(ct).rightJustified(5, '0', false);
1151 while (QFile::exists(m_projectFolder.path(KUrl::AddTrailingSlash) + "ladspa/" + counter + ".ladspa")) {
1153 counter = QString::number(ct).rightJustified(5, '0', false);
1155 return m_projectFolder.path(KUrl::AddTrailingSlash) + "ladspa/" + counter + ".ladspa";
1158 bool KdenliveDoc::checkDocumentClips(QDomNodeList infoproducers)
1164 QList <QDomElement> missingClips;
1165 for (int i = 0; i < infoproducers.count(); i++) {
1166 e = infoproducers.item(i).toElement();
1167 clipType = e.attribute("type").toInt();
1168 if (clipType == COLOR) continue;
1169 if (clipType == TEXT) {
1170 //TODO: Check is clip template is missing (xmltemplate) or hash changed
1173 id = e.attribute("id");
1174 resource = e.attribute("resource");
1175 if (clipType == SLIDESHOW) resource = KUrl(resource).directory();
1176 if (!KIO::NetAccess::exists(KUrl(resource), KIO::NetAccess::SourceSide, 0)) {
1177 // Missing clip found
1178 missingClips.append(e);
1180 // Check if the clip has changed
1181 if (clipType != SLIDESHOW && e.hasAttribute("file_hash")) {
1182 if (e.attribute("file_hash") != DocClipBase::getHash(e.attribute("resource")))
1183 e.removeAttribute("file_hash");
1187 if (missingClips.isEmpty()) return true;
1188 DocumentChecker d(missingClips, m_document);
1189 return (d.exec() == QDialog::Accepted);
1192 void KdenliveDoc::setDocumentProperty(const QString &name, const QString &value)
1194 m_documentProperties[name] = value;
1197 const QString KdenliveDoc::getDocumentProperty(const QString &name) const
1199 return m_documentProperties.value(name);
1202 #include "kdenlivedoc.moc"