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
264 QDomDocument KdenliveDoc::createEmptyDocument(int videotracks, int audiotracks)
266 TrackInfo videoTrack;
267 videoTrack.type = VIDEOTRACK;
268 videoTrack.isMute = false;
269 videoTrack.isBlind = false;
270 videoTrack.isLocked = false;
272 TrackInfo audioTrack;
273 audioTrack.type = AUDIOTRACK;
274 audioTrack.isMute = false;
275 audioTrack.isBlind = true;
276 audioTrack.isLocked = false;
278 m_tracksList.clear();
280 for (int i = 0; i < audiotracks; i++) {
281 m_tracksList.append(audioTrack);
283 for (int i = 0; i < videotracks; i++) {
284 m_tracksList.append(videoTrack);
286 return createEmptyDocument(m_tracksList);
289 QDomDocument KdenliveDoc::createEmptyDocument(QList <TrackInfo> tracks)
291 // Creating new document
293 QDomElement mlt = doc.createElement("mlt");
294 doc.appendChild(mlt);
297 // Create black producer
298 // For some unknown reason, we have to build the black producer here and not in renderer.cpp, otherwise
299 // the composite transitions with the black track are corrupted.
300 QDomElement blk = doc.createElement("producer");
301 blk.setAttribute("in", 0);
302 blk.setAttribute("out", 500);
303 blk.setAttribute("id", "black");
305 QDomElement property = doc.createElement("property");
306 property.setAttribute("name", "mlt_type");
307 QDomText value = doc.createTextNode("producer");
308 property.appendChild(value);
309 blk.appendChild(property);
311 property = doc.createElement("property");
312 property.setAttribute("name", "aspect_ratio");
313 value = doc.createTextNode(QString::number(0.0));
314 property.appendChild(value);
315 blk.appendChild(property);
317 property = doc.createElement("property");
318 property.setAttribute("name", "length");
319 value = doc.createTextNode(QString::number(15000));
320 property.appendChild(value);
321 blk.appendChild(property);
323 property = doc.createElement("property");
324 property.setAttribute("name", "eof");
325 value = doc.createTextNode("pause");
326 property.appendChild(value);
327 blk.appendChild(property);
329 property = doc.createElement("property");
330 property.setAttribute("name", "resource");
331 value = doc.createTextNode("black");
332 property.appendChild(value);
333 blk.appendChild(property);
335 property = doc.createElement("property");
336 property.setAttribute("name", "mlt_service");
337 value = doc.createTextNode("colour");
338 property.appendChild(value);
339 blk.appendChild(property);
341 mlt.appendChild(blk);
344 QDomElement tractor = doc.createElement("tractor");
345 tractor.setAttribute("id", "maintractor");
346 QDomElement multitrack = doc.createElement("multitrack");
347 QDomElement playlist = doc.createElement("playlist");
348 playlist.setAttribute("id", "black_track");
349 mlt.appendChild(playlist);
351 QDomElement blank0 = doc.createElement("entry");
352 blank0.setAttribute("in", "0");
353 blank0.setAttribute("out", "0");
354 blank0.setAttribute("producer", "black");
355 playlist.appendChild(blank0);
358 int total = tracks.count() + 1;
360 for (int i = 1; i < total; i++) {
361 QDomElement playlist = doc.createElement("playlist");
362 playlist.setAttribute("id", "playlist" + QString::number(i));
363 mlt.appendChild(playlist);
366 QDomElement track0 = doc.createElement("track");
367 track0.setAttribute("producer", "black_track");
368 tractor.appendChild(track0);
370 // create audio tracks
371 for (int i = 1; i < total; i++) {
372 QDomElement track = doc.createElement("track");
373 track.setAttribute("producer", "playlist" + QString::number(i));
374 if (tracks.at(i - 1).type == AUDIOTRACK)
375 track.setAttribute("hide", "video");
376 else if (tracks.at(i - 1).isBlind)
377 track.setAttribute("hide", "video");
378 if (tracks.at(i - 1).isMute)
379 track.setAttribute("hide", "audio");
380 tractor.appendChild(track);
383 for (int i = 2; i < total ; i++) {
384 QDomElement transition = doc.createElement("transition");
385 transition.setAttribute("always_active", "1");
387 QDomElement property = doc.createElement("property");
388 property.setAttribute("name", "a_track");
389 QDomText value = doc.createTextNode(QString::number(1));
390 property.appendChild(value);
391 transition.appendChild(property);
393 property = doc.createElement("property");
394 property.setAttribute("name", "b_track");
395 value = doc.createTextNode(QString::number(i));
396 property.appendChild(value);
397 transition.appendChild(property);
399 property = doc.createElement("property");
400 property.setAttribute("name", "mlt_service");
401 value = doc.createTextNode("mix");
402 property.appendChild(value);
403 transition.appendChild(property);
405 property = doc.createElement("property");
406 property.setAttribute("name", "combine");
407 value = doc.createTextNode("1");
408 property.appendChild(value);
409 transition.appendChild(property);
411 property = doc.createElement("property");
412 property.setAttribute("name", "internal_added");
413 value = doc.createTextNode("237");
414 property.appendChild(value);
415 transition.appendChild(property);
416 tractor.appendChild(transition);
418 mlt.appendChild(tractor);
423 void KdenliveDoc::syncGuides(QList <Guide *> guides)
426 QDomElement guideNode = m_guidesXml.createElement("guides");
427 m_guidesXml.appendChild(guideNode);
430 for (int i = 0; i < guides.count(); i++) {
431 e = m_guidesXml.createElement("guide");
432 e.setAttribute("time", guides.at(i)->position().ms() / 1000);
433 e.setAttribute("comment", guides.at(i)->label());
434 guideNode.appendChild(e);
437 emit guidesUpdated();
440 QDomElement KdenliveDoc::guidesXml() const
442 return m_guidesXml.documentElement();
445 void KdenliveDoc::slotAutoSave()
447 if (m_render && m_autosave) {
448 if (!m_autosave->isOpen() && !m_autosave->open(QIODevice::ReadWrite)) {
449 // show error: could not open the autosave file
450 kDebug() << "ERROR; CANNOT CREATE AUTOSAVE FILE";
452 kDebug() << "// AUTOSAVE FILE: " << m_autosave->fileName();
454 if (KdenliveSettings::dropbframes()) {
455 KdenliveSettings::setDropbframes(false);
456 m_clipManager->updatePreviewSettings();
457 doc = m_render->sceneList();
458 KdenliveSettings::setDropbframes(true);
459 m_clipManager->updatePreviewSettings();
460 } else doc = m_render->sceneList();
461 saveSceneList(m_autosave->fileName(), doc);
465 void KdenliveDoc::setZoom(int horizontal, int vertical)
467 m_documentProperties["zoom"] = QString::number(horizontal);
468 m_documentProperties["verticalzoom"] = QString::number(vertical);
471 QPoint KdenliveDoc::zoom() const
473 return QPoint(m_documentProperties.value("zoom").toInt(), m_documentProperties.value("verticalzoom").toInt());
476 void KdenliveDoc::setZone(int start, int end)
478 m_documentProperties["zonein"] = QString::number(start);
479 m_documentProperties["zoneout"] = QString::number(end);
482 QPoint KdenliveDoc::zone() const
484 return QPoint(m_documentProperties.value("zonein").toInt(), m_documentProperties.value("zoneout").toInt());
487 bool KdenliveDoc::saveSceneList(const QString &path, const QString &scene)
489 QDomDocument sceneList;
490 sceneList.setContent(scene, true);
491 QDomElement mlt = sceneList.firstChildElement("mlt");
492 QDomElement addedXml = sceneList.createElement("kdenlivedoc");
493 mlt.appendChild(addedXml);
495 QDomElement markers = sceneList.createElement("markers");
496 addedXml.setAttribute("version", DOCUMENTVERSION);
497 addedXml.setAttribute("kdenliveversion", VERSION);
498 addedXml.setAttribute("profile", profilePath());
499 addedXml.setAttribute("projectfolder", m_projectFolder.path());
501 QDomElement docproperties = sceneList.createElement("documentproperties");
502 QMapIterator<QString, QString> i(m_documentProperties);
503 while (i.hasNext()) {
505 docproperties.setAttribute(i.key(), i.value());
507 docproperties.setAttribute("position", m_render->seekPosition().frames(m_fps));
508 addedXml.appendChild(docproperties);
511 QDomElement profileinfo = sceneList.createElement("profileinfo");
512 profileinfo.setAttribute("description", m_profile.description);
513 profileinfo.setAttribute("frame_rate_num", m_profile.frame_rate_num);
514 profileinfo.setAttribute("frame_rate_den", m_profile.frame_rate_den);
515 profileinfo.setAttribute("width", m_profile.width);
516 profileinfo.setAttribute("height", m_profile.height);
517 profileinfo.setAttribute("progressive", m_profile.progressive);
518 profileinfo.setAttribute("sample_aspect_num", m_profile.sample_aspect_num);
519 profileinfo.setAttribute("sample_aspect_den", m_profile.sample_aspect_den);
520 profileinfo.setAttribute("display_aspect_num", m_profile.display_aspect_num);
521 profileinfo.setAttribute("display_aspect_den", m_profile.display_aspect_den);
522 addedXml.appendChild(profileinfo);
525 QDomElement tracksinfo = sceneList.createElement("tracksinfo");
526 foreach(const TrackInfo &info, m_tracksList) {
527 QDomElement trackinfo = sceneList.createElement("trackinfo");
528 if (info.type == AUDIOTRACK) trackinfo.setAttribute("type", "audio");
529 trackinfo.setAttribute("mute", info.isMute);
530 trackinfo.setAttribute("blind", info.isBlind);
531 trackinfo.setAttribute("locked", info.isLocked);
532 trackinfo.setAttribute("trackname", info.trackName);
533 tracksinfo.appendChild(trackinfo);
535 addedXml.appendChild(tracksinfo);
537 // save project folders
538 QMap <QString, QString> folderlist = m_clipManager->documentFolderList();
540 QMapIterator<QString, QString> f(folderlist);
541 while (f.hasNext()) {
543 QDomElement folder = sceneList.createElement("folder");
544 folder.setAttribute("id", f.key());
545 folder.setAttribute("name", f.value());
546 addedXml.appendChild(folder);
549 // Save project clips
551 QList <DocClipBase*> list = m_clipManager->documentClipList();
552 for (int i = 0; i < list.count(); i++) {
553 e = list.at(i)->toXML();
554 e.setTagName("kdenlive_producer");
555 addedXml.appendChild(sceneList.importNode(e, true));
556 QList < CommentedTime > marks = list.at(i)->commentedSnapMarkers();
557 for (int j = 0; j < marks.count(); j++) {
558 QDomElement marker = sceneList.createElement("marker");
559 marker.setAttribute("time", marks.at(j).time().ms() / 1000);
560 marker.setAttribute("comment", marks.at(j).comment());
561 marker.setAttribute("id", e.attribute("id"));
562 markers.appendChild(marker);
565 addedXml.appendChild(markers);
568 if (!m_guidesXml.isNull()) addedXml.appendChild(sceneList.importNode(m_guidesXml.documentElement(), true));
571 addedXml.appendChild(sceneList.importNode(m_clipManager->groupsXml(), true));
573 //wes.appendChild(doc.importNode(kdenliveData, true));
576 if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
577 kWarning() << "////// ERROR writing to file: " << path;
578 KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1", path));
582 file.write(sceneList.toString().toUtf8());
583 if (file.error() != QFile::NoError) {
584 KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1", path));
592 ClipManager *KdenliveDoc::clipManager()
594 return m_clipManager;
597 KUrl KdenliveDoc::projectFolder() const
599 //if (m_projectFolder.isEmpty()) return KUrl(KStandardDirs::locateLocal("appdata", "/projects/"));
600 return m_projectFolder;
603 void KdenliveDoc::setProjectFolder(KUrl url)
605 if (url == m_projectFolder) return;
607 KStandardDirs::makeDir(url.path());
608 KStandardDirs::makeDir(url.path(KUrl::AddTrailingSlash) + "titles/");
609 KStandardDirs::makeDir(url.path(KUrl::AddTrailingSlash) + "thumbs/");
610 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);
611 m_projectFolder = url;
614 void KdenliveDoc::moveProjectData(KUrl url)
616 QList <DocClipBase*> list = m_clipManager->documentClipList();
617 //TODO: Also move ladspa effects files
618 for (int i = 0; i < list.count(); i++) {
619 DocClipBase *clip = list.at(i);
620 if (clip->clipType() == TEXT) {
621 // the image for title clip must be moved
622 KUrl oldUrl = clip->fileURL();
623 KUrl newUrl = KUrl(url.path(KUrl::AddTrailingSlash) + "titles/" + oldUrl.fileName());
624 KIO::Job *job = KIO::copy(oldUrl, newUrl);
625 if (KIO::NetAccess::synchronousRun(job, 0)) clip->setProperty("resource", newUrl.path());
627 QString hash = clip->getClipHash();
628 KUrl oldVideoThumbUrl = KUrl(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".png");
629 KUrl oldAudioThumbUrl = KUrl(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".thumb");
630 if (KIO::NetAccess::exists(oldVideoThumbUrl, KIO::NetAccess::SourceSide, 0)) {
631 KUrl newUrl = KUrl(url.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".png");
632 KIO::Job *job = KIO::copy(oldVideoThumbUrl, newUrl);
633 KIO::NetAccess::synchronousRun(job, 0);
635 if (KIO::NetAccess::exists(oldAudioThumbUrl, KIO::NetAccess::SourceSide, 0)) {
636 KUrl newUrl = KUrl(url.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".thumb");
637 KIO::Job *job = KIO::copy(oldAudioThumbUrl, newUrl);
638 if (KIO::NetAccess::synchronousRun(job, 0)) clip->refreshThumbUrl();
643 const QString &KdenliveDoc::profilePath() const
645 return m_profile.path;
648 MltVideoProfile KdenliveDoc::mltProfile() const
653 bool KdenliveDoc::setProfilePath(QString path)
655 if (path.isEmpty()) path = KdenliveSettings::default_profile();
656 if (path.isEmpty()) path = "dv_pal";
657 m_profile = ProfilesDialog::getVideoProfile(path);
658 bool current_fps = m_fps;
659 if (m_profile.path.isEmpty()) {
660 // Profile not found, use embedded profile
661 QDomElement profileInfo = m_document.elementsByTagName("profileinfo").at(0).toElement();
662 if (profileInfo.isNull()) {
663 KMessageBox::information(kapp->activeWindow(), i18n("Project profile was not found, using default profile."), i18n("Missing Profile"));
664 m_profile = ProfilesDialog::getVideoProfile(KdenliveSettings::default_profile());
666 m_profile.description = profileInfo.attribute("description");
667 m_profile.frame_rate_num = profileInfo.attribute("frame_rate_num").toInt();
668 m_profile.frame_rate_den = profileInfo.attribute("frame_rate_den").toInt();
669 m_profile.width = profileInfo.attribute("width").toInt();
670 m_profile.height = profileInfo.attribute("height").toInt();
671 m_profile.progressive = profileInfo.attribute("progressive").toInt();
672 m_profile.sample_aspect_num = profileInfo.attribute("sample_aspect_num").toInt();
673 m_profile.sample_aspect_den = profileInfo.attribute("sample_aspect_den").toInt();
674 m_profile.display_aspect_num = profileInfo.attribute("display_aspect_num").toInt();
675 m_profile.display_aspect_den = profileInfo.attribute("display_aspect_den").toInt();
676 QString existing = ProfilesDialog::existingProfile(m_profile);
677 if (!existing.isEmpty()) {
678 m_profile = ProfilesDialog::getVideoProfile(existing);
679 KMessageBox::information(kapp->activeWindow(), i18n("Project profile not found, replacing with existing one: %1", m_profile.description), i18n("Missing Profile"));
681 QString newDesc = m_profile.description;
683 while (ok && (newDesc.isEmpty() || ProfilesDialog::existingProfileDescription(newDesc))) {
684 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);
687 // User canceled, use default profile
688 m_profile = ProfilesDialog::getVideoProfile(KdenliveSettings::default_profile());
690 if (newDesc != m_profile.description) {
691 // Profile description existed, was replaced by new one
692 m_profile.description = newDesc;
694 KMessageBox::information(kapp->activeWindow(), i18n("Project profile was not found, it will be added to your system now."), i18n("Missing Profile"));
696 ProfilesDialog::saveProfile(m_profile);
703 KdenliveSettings::setProject_display_ratio((double) m_profile.display_aspect_num / m_profile.display_aspect_den);
704 m_fps = (double) m_profile.frame_rate_num / m_profile.frame_rate_den;
705 KdenliveSettings::setProject_fps(m_fps);
706 m_width = m_profile.width;
707 m_height = m_profile.height;
708 kDebug() << "Kdenlive document, init timecode from path: " << path << ", " << m_fps;
709 if (m_fps == 30000.0 / 1001.0) m_timecode.setFormat(m_fps, true);
710 else m_timecode.setFormat(m_fps);
711 return (current_fps != m_fps);
714 double KdenliveDoc::dar()
716 return (double) m_profile.display_aspect_num / m_profile.display_aspect_den;
719 void KdenliveDoc::setThumbsProgress(const QString &message, int progress)
721 emit progressInfo(message, progress);
724 void KdenliveDoc::loadingProgressed()
726 m_documentLoadingProgress += m_documentLoadingStep;
727 emit progressInfo(QString(), (int) m_documentLoadingProgress);
730 QUndoStack *KdenliveDoc::commandStack()
732 return m_commandStack;
736 void KdenliveDoc::setRenderer(Render *render) {
737 if (m_render) return;
739 emit progressInfo(i18n("Loading playlist..."), 0);
740 //qApp->processEvents();
742 m_render->setSceneList(m_document.toString(), m_startPos);
743 kDebug() << "// SETTING SCENE LIST:\n\n" << m_document.toString();
746 emit progressInfo(QString(), -1);
749 void KdenliveDoc::checkProjectClips()
751 kDebug() << "+++++++++++++ + + + + CHK PCLIPS";
752 if (m_render == NULL) return;
753 m_clipManager->resetProducersList(m_render->producersList());
756 void KdenliveDoc::updatePreviewSettings()
758 m_clipManager->updatePreviewSettings();
759 m_render->updatePreviewSettings();
760 QList <Mlt::Producer *> prods = m_render->producersList();
761 m_clipManager->resetProducersList(m_render->producersList());
766 Render *KdenliveDoc::renderer()
771 void KdenliveDoc::updateClip(const QString id)
773 emit updateClipDisplay(id);
776 int KdenliveDoc::getFramePos(QString duration)
778 return m_timecode.getFrameCount(duration);
781 QString KdenliveDoc::producerName(const QString &id)
783 QString result = "unnamed";
784 QDomNodeList prods = producersList();
785 int ct = prods.count();
786 for (int i = 0; i < ct ; i++) {
787 QDomElement e = prods.item(i).toElement();
788 if (e.attribute("id") != "black" && e.attribute("id") == id) {
789 result = e.attribute("name");
790 if (result.isEmpty()) result = KUrl(e.attribute("resource")).fileName();
797 QDomDocument KdenliveDoc::toXml()
802 Timecode KdenliveDoc::timecode() const
807 QDomNodeList KdenliveDoc::producersList()
809 return m_document.elementsByTagName("producer");
812 double KdenliveDoc::projectDuration() const
815 return GenTime(m_render->getLength(), m_fps).ms() / 1000;
820 double KdenliveDoc::fps() const
825 int KdenliveDoc::width() const
830 int KdenliveDoc::height() const
835 KUrl KdenliveDoc::url() const
840 void KdenliveDoc::setUrl(KUrl url)
845 void KdenliveDoc::setModified(bool mod)
847 if (!m_url.isEmpty() && mod && KdenliveSettings::crashrecovery()) {
848 m_autoSaveTimer->start(3000);
850 if (mod == m_modified) return;
852 emit docModified(m_modified);
855 bool KdenliveDoc::isModified() const
860 const QString KdenliveDoc::description() const
863 return i18n("Untitled") + " / " + m_profile.description;
865 return m_url.fileName() + " / " + m_profile.description;
868 void KdenliveDoc::addClip(QDomElement elem, QString clipId, bool createClipItem)
870 const QString producerId = clipId.section('_', 0, 0);
871 DocClipBase *clip = m_clipManager->getClipById(producerId);
874 elem.setAttribute("id", producerId);
875 QString path = elem.attribute("resource");
877 if (elem.attribute("type").toInt() == SLIDESHOW) {
878 extension = KUrl(path).fileName();
879 path = KUrl(path).directory();
882 if (path.isEmpty() == false && QFile::exists(path) == false && elem.attribute("type").toInt() != TEXT && !elem.hasAttribute("placeholder")) {
883 kDebug() << "// FOUND MISSING CLIP: " << path << ", TYPE: " << elem.attribute("type").toInt();
884 const QString size = elem.attribute("file_size");
885 const QString hash = elem.attribute("file_hash");
887 int action = KMessageBox::No;
888 if (!size.isEmpty() && !hash.isEmpty()) {
889 if (!m_searchFolder.isEmpty()) newpath = searchFileRecursively(m_searchFolder, size, hash);
890 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")));
892 if (elem.attribute("type").toInt() == SLIDESHOW) {
893 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")));
894 if (res == KMessageBox::Yes)
895 newpath = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow(), i18n("Looking for %1", path));
897 // Abort project loading
901 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")));
902 if (res == KMessageBox::Yes)
903 newpath = KFileDialog::getOpenFileName(KUrl("kfiledialog:///clipfolder"), QString(), kapp->activeWindow(), i18n("Looking for %1", path));
905 // Abort project loading
910 if (action == KMessageBox::Yes) {
911 kDebug() << "// ASKED FOR SRCH CLIP: " << clipId;
912 m_searchFolder = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow());
913 if (!m_searchFolder.isEmpty()) {
914 newpath = searchFileRecursively(QDir(m_searchFolder), size, hash);
916 } else if (action == KMessageBox::Cancel) {
917 m_abortLoading = true;
919 } else if (action == KMessageBox::No) {
920 // Keep clip as placeHolder
921 elem.setAttribute("placeholder", '1');
923 if (!newpath.isEmpty()) {
924 if (elem.attribute("type").toInt() == SLIDESHOW) newpath.append('/' + extension);
925 elem.setAttribute("resource", newpath);
926 setNewClipResource(clipId, newpath);
930 clip = new DocClipBase(m_clipManager, elem, producerId);
931 m_clipManager->addClip(clip);
934 if (createClipItem) {
935 emit addProjectClip(clip);
936 //qApp->processEvents();
941 void KdenliveDoc::setNewClipResource(const QString &id, const QString &path)
943 QDomNodeList prods = m_document.elementsByTagName("producer");
944 int maxprod = prods.count();
945 for (int i = 0; i < maxprod; i++) {
946 QDomNode m = prods.at(i);
947 QString prodId = m.toElement().attribute("id");
948 if (prodId == id || prodId.startsWith(id + '_')) {
949 QDomNodeList params = m.childNodes();
950 for (int j = 0; j < params.count(); j++) {
951 QDomElement e = params.item(j).toElement();
952 if (e.attribute("name") == "resource") {
953 e.firstChild().setNodeValue(path);
961 QString KdenliveDoc::searchFileRecursively(const QDir &dir, const QString &matchSize, const QString &matchHash) const
963 QString foundFileName;
966 QStringList filesAndDirs = dir.entryList(QDir::Files | QDir::Readable);
967 for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
968 QFile file(dir.absoluteFilePath(filesAndDirs.at(i)));
969 if (file.open(QIODevice::ReadOnly)) {
970 if (QString::number(file.size()) == matchSize) {
972 * 1 MB = 1 second per 450 files (or faster)
973 * 10 MB = 9 seconds per 450 files (or faster)
975 if (file.size() > 1000000*2) {
976 fileData = file.read(1000000);
977 if (file.seek(file.size() - 1000000))
978 fileData.append(file.readAll());
980 fileData = file.readAll();
982 fileHash = QCryptographicHash::hash(fileData, QCryptographicHash::Md5);
983 if (QString(fileHash.toHex()) == matchHash)
984 return file.fileName();
987 kDebug() << filesAndDirs.at(i) << file.size() << fileHash.toHex();
989 filesAndDirs = dir.entryList(QDir::Dirs | QDir::Readable | QDir::Executable | QDir::NoDotAndDotDot);
990 for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
991 foundFileName = searchFileRecursively(dir.absoluteFilePath(filesAndDirs.at(i)), matchSize, matchHash);
992 if (!foundFileName.isEmpty())
995 return foundFileName;
998 void KdenliveDoc::addClipInfo(QDomElement elem, QDomElement orig, QString clipId)
1000 DocClipBase *clip = m_clipManager->getClipById(clipId);
1002 addClip(elem, clipId, false);
1004 QMap <QString, QString> properties;
1005 QDomNamedNodeMap attributes = elem.attributes();
1007 for (int i = 0; i < attributes.count(); i++) {
1008 attrname = attributes.item(i).nodeName();
1009 if (attrname != "resource")
1010 properties.insert(attrname, attributes.item(i).nodeValue());
1011 kDebug() << attrname << " = " << attributes.item(i).nodeValue();
1013 clip->setProperties(properties);
1014 emit addProjectClip(clip, false);
1016 if (orig != QDomElement()) {
1017 QMap<QString, QString> meta;
1018 QDomNode m = orig.firstChild();
1019 while (!m.isNull()) {
1020 QString name = m.toElement().attribute("name");
1021 if (name.startsWith("meta.attr")) {
1022 meta.insert(name.section('.', 2, 3), m.firstChild().nodeValue());
1024 m = m.nextSibling();
1026 if (!meta.isEmpty()) {
1027 if (clip == NULL) clip = m_clipManager->getClipById(clipId);
1028 if (clip) clip->setMetadata(meta);
1033 void KdenliveDoc::deleteProjectClip(QList <QString> ids)
1035 for (int i = 0; i < ids.size(); ++i) {
1036 emit deleteTimelineClip(ids.at(i));
1037 m_clipManager->slotDeleteClip(ids.at(i));
1042 void KdenliveDoc::deleteClip(const QString &clipId)
1044 emit signalDeleteProjectClip(clipId);
1047 void KdenliveDoc::slotAddClipList(const KUrl::List urls, const QString group, const QString &groupId)
1049 m_clipManager->slotAddClipList(urls, group, groupId);
1050 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1055 void KdenliveDoc::slotAddClipFile(const KUrl url, const QString group, const QString &groupId)
1057 m_clipManager->slotAddClipFile(url, group, groupId);
1058 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1062 const QString KdenliveDoc::getFreeClipId()
1064 return QString::number(m_clipManager->getFreeClipId());
1067 DocClipBase *KdenliveDoc::getBaseClip(const QString &clipId)
1069 return m_clipManager->getClipById(clipId);
1072 void KdenliveDoc::slotCreateColorClip(const QString &name, const QString &color, const QString &duration, QString group, const QString &groupId)
1074 m_clipManager->slotAddColorClipFile(name, color, duration, group, groupId);
1076 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1079 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)
1081 m_clipManager->slotAddSlideshowClipFile(name, path, count, duration, loop, fade, luma_duration, luma_file, softness, group, groupId);
1083 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1086 void KdenliveDoc::slotCreateTextClip(QString group, const QString &groupId, const QString &templatePath)
1088 QString titlesFolder = projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
1089 KStandardDirs::makeDir(titlesFolder);
1090 TitleWidget *dia_ui = new TitleWidget(templatePath, m_timecode, titlesFolder, m_render, kapp->activeWindow());
1091 if (dia_ui->exec() == QDialog::Accepted) {
1092 m_clipManager->slotAddTextClipFile(i18n("Title clip"), dia_ui->duration(), dia_ui->xml().toString(), group, groupId);
1094 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1099 void KdenliveDoc::slotCreateTextTemplateClip(QString group, const QString &groupId, KUrl path)
1101 QString titlesFolder = projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
1102 if (path.isEmpty()) {
1103 path = KFileDialog::getOpenUrl(KUrl(titlesFolder), "*.kdenlivetitle", kapp->activeWindow(), i18n("Enter Template Path"));
1106 if (path.isEmpty()) return;
1108 //TODO: rewrite with new title system (just set resource)
1109 m_clipManager->slotAddTextTemplateClip(i18n("Template title clip"), path, group, groupId);
1111 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1114 int KdenliveDoc::tracksCount() const
1116 return m_tracksList.count();
1119 TrackInfo KdenliveDoc::trackInfoAt(int ix) const
1121 return m_tracksList.at(ix);
1124 void KdenliveDoc::switchTrackAudio(int ix, bool hide)
1126 m_tracksList[ix].isMute = hide; // !m_tracksList.at(ix).isMute;
1129 void KdenliveDoc::switchTrackLock(int ix, bool lock)
1131 m_tracksList[ix].isLocked = lock;
1134 bool KdenliveDoc::isTrackLocked(int ix) const
1136 return m_tracksList.at(ix).isLocked;
1139 void KdenliveDoc::switchTrackVideo(int ix, bool hide)
1141 m_tracksList[ix].isBlind = hide; // !m_tracksList.at(ix).isBlind;
1144 void KdenliveDoc::insertTrack(int ix, TrackInfo type)
1146 if (ix == -1) m_tracksList << type;
1147 else m_tracksList.insert(ix, type);
1150 void KdenliveDoc::deleteTrack(int ix)
1152 m_tracksList.removeAt(ix);
1155 void KdenliveDoc::setTrackType(int ix, TrackInfo type)
1157 m_tracksList[ix].type = type.type;
1158 m_tracksList[ix].isMute = type.isMute;
1159 m_tracksList[ix].isBlind = type.isBlind;
1160 m_tracksList[ix].isLocked = type.isLocked;
1161 m_tracksList[ix].trackName = type.trackName;
1164 const QList <TrackInfo> KdenliveDoc::tracksList() const
1166 return m_tracksList;
1169 QPoint KdenliveDoc::getTracksCount() const
1173 foreach(const TrackInfo &info, m_tracksList) {
1174 if (info.type == VIDEOTRACK) video++;
1177 return QPoint(video, audio);
1180 void KdenliveDoc::cachePixmap(const QString &fileId, const QPixmap &pix) const
1182 pix.save(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + fileId + ".png");
1185 QString KdenliveDoc::getLadspaFile() const
1188 QString counter = QString::number(ct).rightJustified(5, '0', false);
1189 while (QFile::exists(m_projectFolder.path(KUrl::AddTrailingSlash) + "ladspa/" + counter + ".ladspa")) {
1191 counter = QString::number(ct).rightJustified(5, '0', false);
1193 return m_projectFolder.path(KUrl::AddTrailingSlash) + "ladspa/" + counter + ".ladspa";
1196 bool KdenliveDoc::checkDocumentClips(QDomNodeList infoproducers)
1202 QList <QDomElement> missingClips;
1203 for (int i = 0; i < infoproducers.count(); i++) {
1204 e = infoproducers.item(i).toElement();
1205 clipType = e.attribute("type").toInt();
1206 if (clipType == COLOR) continue;
1207 if (clipType == TEXT) {
1208 //TODO: Check is clip template is missing (xmltemplate) or hash changed
1211 id = e.attribute("id");
1212 resource = e.attribute("resource");
1213 if (clipType == SLIDESHOW) resource = KUrl(resource).directory();
1214 if (!KIO::NetAccess::exists(KUrl(resource), KIO::NetAccess::SourceSide, 0)) {
1215 // Missing clip found
1216 missingClips.append(e);
1218 // Check if the clip has changed
1219 if (clipType != SLIDESHOW && e.hasAttribute("file_hash")) {
1220 if (e.attribute("file_hash") != DocClipBase::getHash(e.attribute("resource")))
1221 e.removeAttribute("file_hash");
1225 if (missingClips.isEmpty()) return true;
1226 DocumentChecker d(missingClips, m_document);
1227 return (d.exec() == QDialog::Accepted);
1230 void KdenliveDoc::setDocumentProperty(const QString &name, const QString &value)
1232 m_documentProperties[name] = value;
1235 const QString KdenliveDoc::getDocumentProperty(const QString &name) const
1237 return m_documentProperties.value(name);
1240 #include "kdenlivedoc.moc"