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.83;
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
207 m_document = createEmptyDocument(tracks.x(), tracks.y());
210 // Set the video profile (empty == default)
212 // Make sure the project folder is usable
213 if (m_projectFolder.isEmpty() || !KIO::NetAccess::exists(m_projectFolder.path(), KIO::NetAccess::DestinationSide, parent)) {
214 KMessageBox::information(parent, i18n("Document project folder is invalid, setting it to the default one: %1", KdenliveSettings::defaultprojectfolder()));
215 m_projectFolder = KUrl(KdenliveSettings::defaultprojectfolder());
218 // Make sure that the necessary folders exist
219 KStandardDirs::makeDir(m_projectFolder.path(KUrl::AddTrailingSlash) + "titles/");
220 KStandardDirs::makeDir(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/");
221 KStandardDirs::makeDir(m_projectFolder.path(KUrl::AddTrailingSlash) + "ladspa/");
223 kDebug() << "Kdenlive document, init timecode: " << m_fps;
224 if (m_fps == 30000.0 / 1001.0) m_timecode.setFormat(30, true);
225 else m_timecode.setFormat((int) m_fps);
227 //kDebug() << "// SETTING SCENE LIST:\n\n" << m_document.toString();
228 connect(m_autoSaveTimer, SIGNAL(timeout()), this, SLOT(slotAutoSave()));
231 KdenliveDoc::~KdenliveDoc()
233 delete m_commandStack;
234 delete m_clipManager;
235 delete m_autoSaveTimer;
237 if (!m_autosave->fileName().isEmpty()) m_autosave->remove();
242 int KdenliveDoc::setSceneList()
244 if (m_render->setSceneList(m_document.toString(), m_documentProperties.value("position").toInt()) == -1) {
245 // INVALID MLT Consumer, something is wrong
248 m_documentProperties.remove("position");
249 // m_document xml is now useless, clear it
255 QDomDocument KdenliveDoc::createEmptyDocument(const int videotracks, const int audiotracks)
257 // Creating new document
259 QDomElement mlt = doc.createElement("mlt");
260 doc.appendChild(mlt);
263 TrackInfo videoTrack;
264 videoTrack.type = VIDEOTRACK;
265 videoTrack.isMute = false;
266 videoTrack.isBlind = false;
267 videoTrack.isLocked = false;
269 TrackInfo audioTrack;
270 audioTrack.type = AUDIOTRACK;
271 audioTrack.isMute = false;
272 audioTrack.isBlind = true;
273 audioTrack.isLocked = false;
275 QDomElement tractor = doc.createElement("tractor");
276 tractor.setAttribute("id", "maintractor");
277 QDomElement multitrack = doc.createElement("multitrack");
278 QDomElement playlist = doc.createElement("playlist");
279 playlist.setAttribute("id", "black_track");
280 mlt.appendChild(playlist);
284 int total = audiotracks + videotracks + 1;
286 for (int i = 1; i < total; i++) {
287 QDomElement playlist = doc.createElement("playlist");
288 playlist.setAttribute("id", "playlist" + QString::number(i));
289 mlt.appendChild(playlist);
292 QDomElement track0 = doc.createElement("track");
293 track0.setAttribute("producer", "black_track");
294 tractor.appendChild(track0);
296 // create audio tracks
297 for (int i = 1; i < audiotracks + 1; i++) {
298 QDomElement track = doc.createElement("track");
299 track.setAttribute("producer", "playlist" + QString::number(i));
300 track.setAttribute("hide", "video");
301 tractor.appendChild(track);
302 m_tracksList.append(audioTrack);
305 // create video tracks
306 for (int i = audiotracks + 1; i < total; i++) {
307 QDomElement track = doc.createElement("track");
308 track.setAttribute("producer", "playlist" + QString::number(i));
309 tractor.appendChild(track);
310 m_tracksList.append(videoTrack);
313 for (int i = 2; i < total ; i++) {
314 QDomElement transition = doc.createElement("transition");
315 transition.setAttribute("always_active", "1");
317 QDomElement property = doc.createElement("property");
318 property.setAttribute("name", "a_track");
319 QDomText value = doc.createTextNode(QString::number(1));
320 property.appendChild(value);
321 transition.appendChild(property);
323 property = doc.createElement("property");
324 property.setAttribute("name", "b_track");
325 value = doc.createTextNode(QString::number(i));
326 property.appendChild(value);
327 transition.appendChild(property);
329 property = doc.createElement("property");
330 property.setAttribute("name", "mlt_service");
331 value = doc.createTextNode("mix");
332 property.appendChild(value);
333 transition.appendChild(property);
335 property = doc.createElement("property");
336 property.setAttribute("name", "combine");
337 value = doc.createTextNode("1");
338 property.appendChild(value);
339 transition.appendChild(property);
341 property = doc.createElement("property");
342 property.setAttribute("name", "internal_added");
343 value = doc.createTextNode("237");
344 property.appendChild(value);
345 transition.appendChild(property);
346 tractor.appendChild(transition);
348 mlt.appendChild(tractor);
353 void KdenliveDoc::syncGuides(QList <Guide *> guides)
356 QDomElement guideNode = m_guidesXml.createElement("guides");
357 m_guidesXml.appendChild(guideNode);
360 for (int i = 0; i < guides.count(); i++) {
361 e = m_guidesXml.createElement("guide");
362 e.setAttribute("time", guides.at(i)->position().ms() / 1000);
363 e.setAttribute("comment", guides.at(i)->label());
364 guideNode.appendChild(e);
367 emit guidesUpdated();
370 QDomElement KdenliveDoc::guidesXml() const
372 return m_guidesXml.documentElement();
375 void KdenliveDoc::slotAutoSave()
377 if (m_render && m_autosave) {
378 if (!m_autosave->isOpen() && !m_autosave->open(QIODevice::ReadWrite)) {
379 // show error: could not open the autosave file
380 kDebug() << "ERROR; CANNOT CREATE AUTOSAVE FILE";
382 kDebug() << "// AUTOSAVE FILE: " << m_autosave->fileName();
384 if (KdenliveSettings::dropbframes()) {
385 KdenliveSettings::setDropbframes(false);
386 m_clipManager->updatePreviewSettings();
387 doc = m_render->sceneList();
388 KdenliveSettings::setDropbframes(true);
389 m_clipManager->updatePreviewSettings();
390 } else doc = m_render->sceneList();
391 saveSceneList(m_autosave->fileName(), doc);
395 void KdenliveDoc::setZoom(int horizontal, int vertical)
397 m_documentProperties["zoom"] = QString::number(horizontal);
398 m_documentProperties["verticalzoom"] = QString::number(vertical);
401 QPoint KdenliveDoc::zoom() const
403 return QPoint(m_documentProperties.value("zoom").toInt(), m_documentProperties.value("verticalzoom").toInt());
406 void KdenliveDoc::setZone(int start, int end)
408 m_documentProperties["zonein"] = QString::number(start);
409 m_documentProperties["zoneout"] = QString::number(end);
412 QPoint KdenliveDoc::zone() const
414 return QPoint(m_documentProperties.value("zonein").toInt(), m_documentProperties.value("zoneout").toInt());
417 bool KdenliveDoc::saveSceneList(const QString &path, const QString &scene)
419 QDomDocument sceneList;
420 sceneList.setContent(scene, true);
421 QDomElement mlt = sceneList.firstChildElement("mlt");
422 QDomElement addedXml = sceneList.createElement("kdenlivedoc");
423 mlt.appendChild(addedXml);
425 QDomElement markers = sceneList.createElement("markers");
426 addedXml.setAttribute("version", DOCUMENTVERSION);
427 addedXml.setAttribute("kdenliveversion", VERSION);
428 addedXml.setAttribute("profile", profilePath());
429 addedXml.setAttribute("projectfolder", m_projectFolder.path());
431 QDomElement docproperties = sceneList.createElement("documentproperties");
432 QMapIterator<QString, QString> i(m_documentProperties);
433 while (i.hasNext()) {
435 docproperties.setAttribute(i.key(), i.value());
437 docproperties.setAttribute("position", m_render->seekPosition().frames(m_fps));
438 addedXml.appendChild(docproperties);
441 QDomElement profileinfo = sceneList.createElement("profileinfo");
442 profileinfo.setAttribute("description", m_profile.description);
443 profileinfo.setAttribute("frame_rate_num", m_profile.frame_rate_num);
444 profileinfo.setAttribute("frame_rate_den", m_profile.frame_rate_den);
445 profileinfo.setAttribute("width", m_profile.width);
446 profileinfo.setAttribute("height", m_profile.height);
447 profileinfo.setAttribute("progressive", m_profile.progressive);
448 profileinfo.setAttribute("sample_aspect_num", m_profile.sample_aspect_num);
449 profileinfo.setAttribute("sample_aspect_den", m_profile.sample_aspect_den);
450 profileinfo.setAttribute("display_aspect_num", m_profile.display_aspect_num);
451 profileinfo.setAttribute("display_aspect_den", m_profile.display_aspect_den);
452 addedXml.appendChild(profileinfo);
455 QDomElement tracksinfo = sceneList.createElement("tracksinfo");
456 foreach(const TrackInfo &info, m_tracksList) {
457 QDomElement trackinfo = sceneList.createElement("trackinfo");
458 if (info.type == AUDIOTRACK) trackinfo.setAttribute("type", "audio");
459 trackinfo.setAttribute("mute", info.isMute);
460 trackinfo.setAttribute("blind", info.isBlind);
461 trackinfo.setAttribute("locked", info.isLocked);
462 tracksinfo.appendChild(trackinfo);
464 addedXml.appendChild(tracksinfo);
466 // save project folders
467 QMap <QString, QString> folderlist = m_clipManager->documentFolderList();
469 QMapIterator<QString, QString> f(folderlist);
470 while (f.hasNext()) {
472 QDomElement folder = sceneList.createElement("folder");
473 folder.setAttribute("id", f.key());
474 folder.setAttribute("name", f.value());
475 addedXml.appendChild(folder);
478 // Save project clips
480 QList <DocClipBase*> list = m_clipManager->documentClipList();
481 for (int i = 0; i < list.count(); i++) {
482 e = list.at(i)->toXML();
483 e.setTagName("kdenlive_producer");
484 addedXml.appendChild(sceneList.importNode(e, true));
485 QList < CommentedTime > marks = list.at(i)->commentedSnapMarkers();
486 for (int j = 0; j < marks.count(); j++) {
487 QDomElement marker = sceneList.createElement("marker");
488 marker.setAttribute("time", marks.at(j).time().ms() / 1000);
489 marker.setAttribute("comment", marks.at(j).comment());
490 marker.setAttribute("id", e.attribute("id"));
491 markers.appendChild(marker);
494 addedXml.appendChild(markers);
497 if (!m_guidesXml.isNull()) addedXml.appendChild(sceneList.importNode(m_guidesXml.documentElement(), true));
500 addedXml.appendChild(sceneList.importNode(m_clipManager->groupsXml(), true));
502 //wes.appendChild(doc.importNode(kdenliveData, true));
505 if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
506 kWarning() << "////// ERROR writing to file: " << path;
507 KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1", path));
511 file.write(sceneList.toString().toUtf8());
512 if (file.error() != QFile::NoError) {
513 KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1", path));
521 ClipManager *KdenliveDoc::clipManager()
523 return m_clipManager;
526 KUrl KdenliveDoc::projectFolder() const
528 //if (m_projectFolder.isEmpty()) return KUrl(KStandardDirs::locateLocal("appdata", "/projects/"));
529 return m_projectFolder;
532 void KdenliveDoc::setProjectFolder(KUrl url)
534 if (url == m_projectFolder) return;
536 KStandardDirs::makeDir(url.path());
537 KStandardDirs::makeDir(url.path(KUrl::AddTrailingSlash) + "titles/");
538 KStandardDirs::makeDir(url.path(KUrl::AddTrailingSlash) + "thumbs/");
539 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);
540 m_projectFolder = url;
543 void KdenliveDoc::moveProjectData(KUrl url)
545 QList <DocClipBase*> list = m_clipManager->documentClipList();
546 //TODO: Also move ladspa effects files
547 for (int i = 0; i < list.count(); i++) {
548 DocClipBase *clip = list.at(i);
549 if (clip->clipType() == TEXT) {
550 // the image for title clip must be moved
551 KUrl oldUrl = clip->fileURL();
552 KUrl newUrl = KUrl(url.path(KUrl::AddTrailingSlash) + "titles/" + oldUrl.fileName());
553 KIO::Job *job = KIO::copy(oldUrl, newUrl);
554 if (KIO::NetAccess::synchronousRun(job, 0)) clip->setProperty("resource", newUrl.path());
556 QString hash = clip->getClipHash();
557 KUrl oldVideoThumbUrl = KUrl(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".png");
558 KUrl oldAudioThumbUrl = KUrl(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".thumb");
559 if (KIO::NetAccess::exists(oldVideoThumbUrl, KIO::NetAccess::SourceSide, 0)) {
560 KUrl newUrl = KUrl(url.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".png");
561 KIO::Job *job = KIO::copy(oldVideoThumbUrl, newUrl);
562 KIO::NetAccess::synchronousRun(job, 0);
564 if (KIO::NetAccess::exists(oldAudioThumbUrl, KIO::NetAccess::SourceSide, 0)) {
565 KUrl newUrl = KUrl(url.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".thumb");
566 KIO::Job *job = KIO::copy(oldAudioThumbUrl, newUrl);
567 if (KIO::NetAccess::synchronousRun(job, 0)) clip->refreshThumbUrl();
572 const QString &KdenliveDoc::profilePath() const
574 return m_profile.path;
577 MltVideoProfile KdenliveDoc::mltProfile() const
582 void KdenliveDoc::setProfilePath(QString path)
584 if (path.isEmpty()) path = KdenliveSettings::default_profile();
585 if (path.isEmpty()) path = "dv_pal";
586 m_profile = ProfilesDialog::getVideoProfile(path);
587 if (m_profile.path.isEmpty()) {
588 // Profile not found, use embedded profile
589 QDomElement profileInfo = m_document.elementsByTagName("profileinfo").at(0).toElement();
590 if (profileInfo.isNull()) {
591 KMessageBox::information(kapp->activeWindow(), i18n("Project profile was not found, using default profile."), i18n("Missing Profile"));
592 m_profile = ProfilesDialog::getVideoProfile(KdenliveSettings::default_profile());
594 m_profile.description = profileInfo.attribute("description");
595 m_profile.frame_rate_num = profileInfo.attribute("frame_rate_num").toInt();
596 m_profile.frame_rate_den = profileInfo.attribute("frame_rate_den").toInt();
597 m_profile.width = profileInfo.attribute("width").toInt();
598 m_profile.height = profileInfo.attribute("height").toInt();
599 m_profile.progressive = profileInfo.attribute("progressive").toInt();
600 m_profile.sample_aspect_num = profileInfo.attribute("sample_aspect_num").toInt();
601 m_profile.sample_aspect_den = profileInfo.attribute("sample_aspect_den").toInt();
602 m_profile.display_aspect_num = profileInfo.attribute("display_aspect_num").toInt();
603 m_profile.display_aspect_den = profileInfo.attribute("display_aspect_den").toInt();
604 QString existing = ProfilesDialog::existingProfile(m_profile);
605 if (!existing.isEmpty()) {
606 m_profile = ProfilesDialog::getVideoProfile(existing);
607 KMessageBox::information(kapp->activeWindow(), i18n("Project profile not found, replacing with existing one: %1", m_profile.description), i18n("Missing Profile"));
609 QString newDesc = m_profile.description;
611 while (ok && (newDesc.isEmpty() || ProfilesDialog::existingProfileDescription(newDesc))) {
612 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);
615 // User canceled, use default profile
616 m_profile = ProfilesDialog::getVideoProfile(KdenliveSettings::default_profile());
618 if (newDesc != m_profile.description) {
619 // Profile description existed, was replaced by new one
620 m_profile.description = newDesc;
622 KMessageBox::information(kapp->activeWindow(), i18n("Project profile was not found, it will be added to your system now."), i18n("Missing Profile"));
624 ProfilesDialog::saveProfile(m_profile);
631 KdenliveSettings::setProject_display_ratio((double) m_profile.display_aspect_num / m_profile.display_aspect_den);
632 m_fps = (double) m_profile.frame_rate_num / m_profile.frame_rate_den;
633 KdenliveSettings::setProject_fps(m_fps);
634 m_width = m_profile.width;
635 m_height = m_profile.height;
636 kDebug() << "Kdenlive document, init timecode from path: " << path << ", " << m_fps;
637 if (m_fps == 30000.0 / 1001.0) m_timecode.setFormat(30, true);
638 else m_timecode.setFormat((int) m_fps);
641 double KdenliveDoc::dar()
643 return (double) m_profile.display_aspect_num / m_profile.display_aspect_den;
646 void KdenliveDoc::setThumbsProgress(const QString &message, int progress)
648 emit progressInfo(message, progress);
651 void KdenliveDoc::loadingProgressed()
653 m_documentLoadingProgress += m_documentLoadingStep;
654 emit progressInfo(QString(), (int) m_documentLoadingProgress);
657 QUndoStack *KdenliveDoc::commandStack()
659 return m_commandStack;
663 void KdenliveDoc::setRenderer(Render *render) {
664 if (m_render) return;
666 emit progressInfo(i18n("Loading playlist..."), 0);
667 //qApp->processEvents();
669 m_render->setSceneList(m_document.toString(), m_startPos);
670 kDebug() << "// SETTING SCENE LIST:\n\n" << m_document.toString();
673 emit progressInfo(QString(), -1);
676 void KdenliveDoc::checkProjectClips()
678 kDebug() << "+++++++++++++ + + + + CHK PCLIPS";
679 if (m_render == NULL) return;
680 m_clipManager->resetProducersList(m_render->producersList());
683 void KdenliveDoc::updatePreviewSettings()
685 m_clipManager->updatePreviewSettings();
686 m_render->updatePreviewSettings();
687 m_clipManager->resetProducersList(m_render->producersList());
691 Render *KdenliveDoc::renderer()
696 void KdenliveDoc::updateClip(const QString &id)
698 emit updateClipDisplay(id);
701 int KdenliveDoc::getFramePos(QString duration)
703 return m_timecode.getFrameCount(duration, m_fps);
706 QString KdenliveDoc::producerName(const QString &id)
708 QString result = "unnamed";
709 QDomNodeList prods = producersList();
710 int ct = prods.count();
711 for (int i = 0; i < ct ; i++) {
712 QDomElement e = prods.item(i).toElement();
713 if (e.attribute("id") != "black" && e.attribute("id") == id) {
714 result = e.attribute("name");
715 if (result.isEmpty()) result = KUrl(e.attribute("resource")).fileName();
722 QDomDocument KdenliveDoc::toXml()
727 Timecode KdenliveDoc::timecode() const
732 QDomNodeList KdenliveDoc::producersList()
734 return m_document.elementsByTagName("producer");
737 double KdenliveDoc::projectDuration() const
740 return GenTime(m_render->getLength(), m_fps).ms() / 1000;
745 double KdenliveDoc::fps() const
750 int KdenliveDoc::width() const
755 int KdenliveDoc::height() const
760 KUrl KdenliveDoc::url() const
765 void KdenliveDoc::setUrl(KUrl url)
770 void KdenliveDoc::setModified(bool mod)
772 if (!m_url.isEmpty() && mod && KdenliveSettings::crashrecovery()) {
773 m_autoSaveTimer->start(3000);
775 if (mod == m_modified) return;
777 emit docModified(m_modified);
780 bool KdenliveDoc::isModified() const
785 const QString KdenliveDoc::description() const
788 return i18n("Untitled") + " / " + m_profile.description;
790 return m_url.fileName() + " / " + m_profile.description;
793 void KdenliveDoc::addClip(QDomElement elem, QString clipId, bool createClipItem)
795 const QString producerId = clipId.section('_', 0, 0);
796 DocClipBase *clip = m_clipManager->getClipById(producerId);
799 elem.setAttribute("id", producerId);
800 QString path = elem.attribute("resource");
802 if (elem.attribute("type").toInt() == SLIDESHOW) {
803 extension = KUrl(path).fileName();
804 path = KUrl(path).directory();
805 } else if (elem.attribute("type").toInt() == TEXT && QFile::exists(path) == false) {
806 kDebug() << "// TITLE: " << elem.attribute("name") << " Preview file: " << elem.attribute("resource") << " DOES NOT EXIST";
807 QString titlename = elem.attribute("name");
808 QString titleresource;
809 if (titlename.isEmpty()) {
810 QStringList titleInfo = TitleWidget::getFreeTitleInfo(projectFolder());
811 titlename = titleInfo.at(0);
812 titleresource = titleInfo.at(1);
813 elem.setAttribute("name", titlename);
814 kDebug() << "// New title set to: " << titlename;
816 titleresource = TitleWidget::getFreeTitleInfo(projectFolder()).at(1);
817 //titleresource = TitleWidget::getTitleResourceFromName(projectFolder(), titlename);
819 TitleWidget *dia_ui = new TitleWidget(KUrl(), KUrl(titleresource).directory(), m_render, kapp->activeWindow());
821 doc.setContent(elem.attribute("xmldata"));
823 QImage pix = dia_ui->renderedPixmap();
824 pix.save(titleresource);
825 elem.setAttribute("resource", titleresource);
826 setNewClipResource(clipId, titleresource);
830 if (path.isEmpty() == false && QFile::exists(path) == false && elem.attribute("type").toInt() != TEXT && !elem.hasAttribute("placeholder")) {
831 kDebug() << "// FOUND MISSING CLIP: " << path << ", TYPE: " << elem.attribute("type").toInt();
832 const QString size = elem.attribute("file_size");
833 const QString hash = elem.attribute("file_hash");
835 int action = KMessageBox::No;
836 if (!size.isEmpty() && !hash.isEmpty()) {
837 if (!m_searchFolder.isEmpty()) newpath = searchFileRecursively(m_searchFolder, size, hash);
838 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")));
840 if (elem.attribute("type").toInt() == SLIDESHOW) {
841 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")));
842 if (res == KMessageBox::Yes)
843 newpath = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow(), i18n("Looking for %1", path));
845 // Abort project loading
849 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")));
850 if (res == KMessageBox::Yes)
851 newpath = KFileDialog::getOpenFileName(KUrl("kfiledialog:///clipfolder"), QString(), kapp->activeWindow(), i18n("Looking for %1", path));
853 // Abort project loading
858 if (action == KMessageBox::Yes) {
859 kDebug() << "// ASKED FOR SRCH CLIP: " << clipId;
860 m_searchFolder = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow());
861 if (!m_searchFolder.isEmpty()) {
862 newpath = searchFileRecursively(QDir(m_searchFolder), size, hash);
864 } else if (action == KMessageBox::Cancel) {
865 m_abortLoading = true;
867 } else if (action == KMessageBox::No) {
868 // Keep clip as placeHolder
869 elem.setAttribute("placeholder", '1');
871 if (!newpath.isEmpty()) {
872 if (elem.attribute("type").toInt() == SLIDESHOW) newpath.append('/' + extension);
873 elem.setAttribute("resource", newpath);
874 setNewClipResource(clipId, newpath);
878 clip = new DocClipBase(m_clipManager, elem, producerId);
879 m_clipManager->addClip(clip);
882 if (createClipItem) {
883 emit addProjectClip(clip);
884 qApp->processEvents();
885 m_render->getFileProperties(clip->toXML(), clip->getId(), true);
890 void KdenliveDoc::setNewClipResource(const QString &id, const QString &path)
892 QDomNodeList prods = m_document.elementsByTagName("producer");
893 int maxprod = prods.count();
894 for (int i = 0; i < maxprod; i++) {
895 QDomNode m = prods.at(i);
896 QString prodId = m.toElement().attribute("id");
897 if (prodId == id || prodId.startsWith(id + '_')) {
898 QDomNodeList params = m.childNodes();
899 for (int j = 0; j < params.count(); j++) {
900 QDomElement e = params.item(j).toElement();
901 if (e.attribute("name") == "resource") {
902 e.firstChild().setNodeValue(path);
910 QString KdenliveDoc::searchFileRecursively(const QDir &dir, const QString &matchSize, const QString &matchHash) const
912 QString foundFileName;
915 QStringList filesAndDirs = dir.entryList(QDir::Files | QDir::Readable);
916 for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
917 QFile file(dir.absoluteFilePath(filesAndDirs.at(i)));
918 if (file.open(QIODevice::ReadOnly)) {
919 if (QString::number(file.size()) == matchSize) {
921 * 1 MB = 1 second per 450 files (or faster)
922 * 10 MB = 9 seconds per 450 files (or faster)
924 if (file.size() > 1000000*2) {
925 fileData = file.read(1000000);
926 if (file.seek(file.size() - 1000000))
927 fileData.append(file.readAll());
929 fileData = file.readAll();
931 fileHash = QCryptographicHash::hash(fileData, QCryptographicHash::Md5);
932 if (QString(fileHash.toHex()) == matchHash)
933 return file.fileName();
936 kDebug() << filesAndDirs.at(i) << file.size() << fileHash.toHex();
938 filesAndDirs = dir.entryList(QDir::Dirs | QDir::Readable | QDir::Executable | QDir::NoDotAndDotDot);
939 for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
940 foundFileName = searchFileRecursively(dir.absoluteFilePath(filesAndDirs.at(i)), matchSize, matchHash);
941 if (!foundFileName.isEmpty())
944 return foundFileName;
947 void KdenliveDoc::addClipInfo(QDomElement elem, QDomElement orig, QString clipId)
949 DocClipBase *clip = m_clipManager->getClipById(clipId);
951 addClip(elem, clipId, false);
953 QMap <QString, QString> properties;
954 QDomNamedNodeMap attributes = elem.attributes();
956 for (int i = 0; i < attributes.count(); i++) {
957 attrname = attributes.item(i).nodeName();
958 if (attrname != "resource")
959 properties.insert(attrname, attributes.item(i).nodeValue());
960 kDebug() << attrname << " = " << attributes.item(i).nodeValue();
962 clip->setProperties(properties);
963 emit addProjectClip(clip, false);
965 if (orig != QDomElement()) {
966 QMap<QString, QString> meta;
967 QDomNode m = orig.firstChild();
968 while (!m.isNull()) {
969 QString name = m.toElement().attribute("name");
970 if (name.startsWith("meta.attr")) {
971 meta.insert(name.section('.', 2, 3), m.firstChild().nodeValue());
975 if (!meta.isEmpty()) {
976 if (clip == NULL) clip = m_clipManager->getClipById(clipId);
977 if (clip) clip->setMetadata(meta);
982 void KdenliveDoc::deleteProjectClip(QList <QString> ids)
984 for (int i = 0; i < ids.size(); ++i) {
985 emit deleteTimelineClip(ids.at(i));
986 m_clipManager->slotDeleteClip(ids.at(i));
991 void KdenliveDoc::deleteClip(const QString &clipId)
993 emit signalDeleteProjectClip(clipId);
994 m_clipManager->deleteClip(clipId);
997 void KdenliveDoc::slotAddClipList(const KUrl::List urls, const QString group, const QString &groupId)
999 m_clipManager->slotAddClipList(urls, group, groupId);
1000 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1005 void KdenliveDoc::slotAddClipFile(const KUrl url, const QString group, const QString &groupId)
1007 m_clipManager->slotAddClipFile(url, group, groupId);
1008 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1012 const QString KdenliveDoc::getFreeClipId()
1014 return QString::number(m_clipManager->getFreeClipId());
1017 DocClipBase *KdenliveDoc::getBaseClip(const QString &clipId)
1019 return m_clipManager->getClipById(clipId);
1022 void KdenliveDoc::slotCreateColorClip(const QString &name, const QString &color, const QString &duration, QString group, const QString &groupId)
1024 m_clipManager->slotAddColorClipFile(name, color, duration, group, groupId);
1026 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1029 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)
1031 m_clipManager->slotAddSlideshowClipFile(name, path, count, duration, loop, fade, luma_duration, luma_file, softness, group, groupId);
1033 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1036 void KdenliveDoc::slotCreateTextClip(QString group, const QString &groupId, const QString &templatePath)
1038 QString titlesFolder = projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
1039 KStandardDirs::makeDir(titlesFolder);
1040 TitleWidget *dia_ui = new TitleWidget(templatePath, titlesFolder, m_render, kapp->activeWindow());
1041 if (dia_ui->exec() == QDialog::Accepted) {
1042 QStringList titleInfo = TitleWidget::getFreeTitleInfo(projectFolder());
1043 QImage pix = dia_ui->renderedPixmap();
1044 pix.save(titleInfo.at(1));
1045 //dia_ui->saveTitle(path + ".kdenlivetitle");
1046 m_clipManager->slotAddTextClipFile(titleInfo.at(0), titleInfo.at(1), dia_ui->xml().toString(), group, groupId);
1048 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1053 void KdenliveDoc::slotCreateTextTemplateClip(QString group, const QString &groupId, KUrl path)
1055 QString titlesFolder = projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
1056 if (path.isEmpty()) {
1057 path = KFileDialog::getOpenUrl(KUrl(titlesFolder), "*.kdenlivetitle", kapp->activeWindow(), i18n("Enter Template Path"));
1060 if (path.isEmpty()) return;
1062 QStringList titleInfo = TitleWidget::getFreeTitleInfo(projectFolder(), true);
1064 TitleWidget *dia_ui = new TitleWidget(path, titlesFolder, m_render, kapp->activeWindow());
1065 QImage pix = dia_ui->renderedPixmap();
1066 pix.save(titleInfo.at(1));
1068 m_clipManager->slotAddTextTemplateClip(titleInfo.at(0), titleInfo.at(1), path, group, groupId);
1070 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1073 int KdenliveDoc::tracksCount() const
1075 return m_tracksList.count();
1078 TrackInfo KdenliveDoc::trackInfoAt(int ix) const
1080 return m_tracksList.at(ix);
1083 void KdenliveDoc::switchTrackAudio(int ix, bool hide)
1085 m_tracksList[ix].isMute = hide; // !m_tracksList.at(ix).isMute;
1088 void KdenliveDoc::switchTrackLock(int ix, bool lock)
1090 m_tracksList[ix].isLocked = lock;
1093 bool KdenliveDoc::isTrackLocked(int ix) const
1095 return m_tracksList.at(ix).isLocked;
1098 void KdenliveDoc::switchTrackVideo(int ix, bool hide)
1100 m_tracksList[ix].isBlind = hide; // !m_tracksList.at(ix).isBlind;
1103 void KdenliveDoc::insertTrack(int ix, TrackInfo type)
1105 if (ix == -1) m_tracksList << type;
1106 else m_tracksList.insert(ix, type);
1109 void KdenliveDoc::deleteTrack(int ix)
1111 m_tracksList.removeAt(ix);
1114 void KdenliveDoc::setTrackType(int ix, TrackInfo type)
1116 m_tracksList[ix].type = type.type;
1117 m_tracksList[ix].isMute = type.isMute;
1118 m_tracksList[ix].isBlind = type.isBlind;
1119 m_tracksList[ix].isLocked = type.isLocked;
1122 const QList <TrackInfo> KdenliveDoc::tracksList() const
1124 return m_tracksList;
1127 QPoint KdenliveDoc::getTracksCount() const
1131 foreach(const TrackInfo &info, m_tracksList) {
1132 if (info.type == VIDEOTRACK) video++;
1135 return QPoint(video, audio);
1138 void KdenliveDoc::cachePixmap(const QString &fileId, const QPixmap &pix) const
1140 pix.save(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + fileId + ".png");
1143 QString KdenliveDoc::getLadspaFile() const
1146 QString counter = QString::number(ct).rightJustified(5, '0', false);
1147 while (QFile::exists(m_projectFolder.path(KUrl::AddTrailingSlash) + "ladspa/" + counter + ".ladspa")) {
1149 counter = QString::number(ct).rightJustified(5, '0', false);
1151 return m_projectFolder.path(KUrl::AddTrailingSlash) + "ladspa/" + counter + ".ladspa";
1154 bool KdenliveDoc::checkDocumentClips(QDomNodeList infoproducers)
1160 QList <QDomElement> missingClips;
1161 for (int i = 0; i < infoproducers.count(); i++) {
1162 e = infoproducers.item(i).toElement();
1163 clipType = e.attribute("type").toInt();
1164 if (clipType == COLOR) continue;
1165 if (clipType == TEXT) {
1166 //TODO: Check is clip template is missing (xmltemplate) or hash changed
1169 id = e.attribute("id");
1170 resource = e.attribute("resource");
1171 if (clipType == SLIDESHOW) resource = KUrl(resource).directory();
1172 if (!KIO::NetAccess::exists(KUrl(resource), KIO::NetAccess::SourceSide, 0)) {
1173 // Missing clip found
1174 missingClips.append(e);
1176 // Check if the clip has changed
1177 if (clipType != SLIDESHOW && e.hasAttribute("file_hash")) {
1178 if (e.attribute("file_hash") != DocClipBase::getHash(e.attribute("resource")))
1179 e.removeAttribute("file_hash");
1183 if (missingClips.isEmpty()) return true;
1184 DocumentChecker d(missingClips, m_document);
1185 return (d.exec() == QDialog::Accepted);
1188 void KdenliveDoc::setDocumentProperty(const QString &name, const QString &value)
1190 m_documentProperties[name] = value;
1193 const QString KdenliveDoc::getDocumentProperty(const QString &name) const
1195 return m_documentProperties.value(name);
1198 #include "kdenlivedoc.moc"