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["zonein"] = "0";
70 m_documentProperties["zoneout"] = "100";
74 success = KIO::NetAccess::download(url.path(), tmpFile, parent);
75 if (!success) // The file cannot be opened
76 KMessageBox::error(parent, KIO::NetAccess::lastErrorString());
80 success = m_document.setContent(&file, false, &errorMsg);
82 KIO::NetAccess::removeTempFile(tmpFile);
83 if (!success) // It is corrupted
84 KMessageBox::error(parent, errorMsg);
86 DocumentValidator validator(m_document);
87 success = validator.isProject();
88 if (!success) // It is not a project file
89 parent->slotGotProgressInfo(i18n("File %1 is not a Kdenlive project file.", m_url.path()), 100);
92 * Validate the file against the current version (upgrade
93 * and recover it if needed). It is NOT a passive operation
95 // TODO: backup the document or alert the user?
96 success = validator.validate(DOCUMENTVERSION);
97 if (success) { // Let the validator handle error messages
98 setModified(validator.isModified());
99 QDomElement mlt = m_document.firstChildElement("mlt");
100 QDomElement infoXml = mlt.firstChildElement("kdenlivedoc");
102 profileName = infoXml.attribute("profile");
103 m_projectFolder = 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 kDebug() << "Reading file: " << url.path() << ", found clips: " << producers.count();
201 } else setProfilePath(profileName);
203 // Something went wrong, or a new file was requested: create a new project
206 m_document = createEmptyDocument(tracks.x(), tracks.y());
209 // Set the video profile (empty == default)
211 // Make sure the project folder is usable
212 if (m_projectFolder.isEmpty() || !KIO::NetAccess::exists(m_projectFolder.path(), KIO::NetAccess::DestinationSide, parent)) {
213 KMessageBox::information(parent, i18n("Document project folder is invalid, setting it to the default one: %1", KdenliveSettings::defaultprojectfolder()));
214 m_projectFolder = KUrl(KdenliveSettings::defaultprojectfolder());
217 // Make sure that the necessary folders exist
218 KStandardDirs::makeDir(m_projectFolder.path() + "/titles/");
219 KStandardDirs::makeDir(m_projectFolder.path() + "/thumbs/");
220 KStandardDirs::makeDir(m_projectFolder.path() + "/ladspa/");
222 kDebug() << "Kdenlive document, init timecode: " << m_fps;
223 if (m_fps == 30000.0 / 1001.0) m_timecode.setFormat(30, true);
224 else m_timecode.setFormat((int) m_fps);
226 //kDebug() << "// SETTING SCENE LIST:\n\n" << m_document.toString();
227 connect(m_autoSaveTimer, SIGNAL(timeout()), this, SLOT(slotAutoSave()));
230 KdenliveDoc::~KdenliveDoc()
232 delete m_commandStack;
233 delete m_clipManager;
234 delete m_autoSaveTimer;
236 if (!m_autosave->fileName().isEmpty()) m_autosave->remove();
241 void KdenliveDoc::setSceneList()
243 m_render->setSceneList(m_document.toString(), m_documentProperties.value("position").toInt());
244 m_documentProperties.remove("position");
245 // m_document xml is now useless, clear it
250 QDomDocument KdenliveDoc::createEmptyDocument(const int videotracks, const int audiotracks)
252 // Creating new document
254 QDomElement mlt = doc.createElement("mlt");
255 doc.appendChild(mlt);
258 TrackInfo videoTrack;
259 videoTrack.type = VIDEOTRACK;
260 videoTrack.isMute = false;
261 videoTrack.isBlind = false;
262 videoTrack.isLocked = false;
264 TrackInfo audioTrack;
265 audioTrack.type = AUDIOTRACK;
266 audioTrack.isMute = false;
267 audioTrack.isBlind = true;
268 audioTrack.isLocked = false;
270 QDomElement tractor = doc.createElement("tractor");
271 tractor.setAttribute("id", "maintractor");
272 QDomElement multitrack = doc.createElement("multitrack");
273 QDomElement playlist = doc.createElement("playlist");
274 playlist.setAttribute("id", "black_track");
275 mlt.appendChild(playlist);
279 int total = audiotracks + videotracks + 1;
281 for (int i = 1; i < total; i++) {
282 QDomElement playlist = doc.createElement("playlist");
283 playlist.setAttribute("id", "playlist" + QString::number(i));
284 mlt.appendChild(playlist);
287 QDomElement track0 = doc.createElement("track");
288 track0.setAttribute("producer", "black_track");
289 tractor.appendChild(track0);
291 // create audio tracks
292 for (int i = 1; i < audiotracks + 1; i++) {
293 QDomElement track = doc.createElement("track");
294 track.setAttribute("producer", "playlist" + QString::number(i));
295 track.setAttribute("hide", "video");
296 tractor.appendChild(track);
297 m_tracksList.append(audioTrack);
300 // create video tracks
301 for (int i = audiotracks + 1; i < total; i++) {
302 QDomElement track = doc.createElement("track");
303 track.setAttribute("producer", "playlist" + QString::number(i));
304 tractor.appendChild(track);
305 m_tracksList.append(videoTrack);
308 for (int i = 2; i < total ; i++) {
309 QDomElement transition = doc.createElement("transition");
310 transition.setAttribute("always_active", "1");
312 QDomElement property = doc.createElement("property");
313 property.setAttribute("name", "a_track");
314 QDomText value = doc.createTextNode(QString::number(1));
315 property.appendChild(value);
316 transition.appendChild(property);
318 property = doc.createElement("property");
319 property.setAttribute("name", "b_track");
320 value = doc.createTextNode(QString::number(i));
321 property.appendChild(value);
322 transition.appendChild(property);
324 property = doc.createElement("property");
325 property.setAttribute("name", "mlt_service");
326 value = doc.createTextNode("mix");
327 property.appendChild(value);
328 transition.appendChild(property);
330 property = doc.createElement("property");
331 property.setAttribute("name", "combine");
332 value = doc.createTextNode("1");
333 property.appendChild(value);
334 transition.appendChild(property);
336 property = doc.createElement("property");
337 property.setAttribute("name", "internal_added");
338 value = doc.createTextNode("237");
339 property.appendChild(value);
340 transition.appendChild(property);
341 tractor.appendChild(transition);
343 mlt.appendChild(tractor);
348 void KdenliveDoc::syncGuides(QList <Guide *> guides)
351 QDomElement guideNode = m_guidesXml.createElement("guides");
352 m_guidesXml.appendChild(guideNode);
355 for (int i = 0; i < guides.count(); i++) {
356 e = m_guidesXml.createElement("guide");
357 e.setAttribute("time", guides.at(i)->position().ms() / 1000);
358 e.setAttribute("comment", guides.at(i)->label());
359 guideNode.appendChild(e);
362 emit guidesUpdated();
365 QDomElement KdenliveDoc::guidesXml() const
367 return m_guidesXml.documentElement();
370 void KdenliveDoc::slotAutoSave()
372 if (m_render && m_autosave) {
373 if (!m_autosave->isOpen() && !m_autosave->open(QIODevice::ReadWrite)) {
374 // show error: could not open the autosave file
375 kDebug() << "ERROR; CANNOT CREATE AUTOSAVE FILE";
377 kDebug() << "// AUTOSAVE FILE: " << m_autosave->fileName();
379 if (KdenliveSettings::dropbframes()) {
380 KdenliveSettings::setDropbframes(false);
381 m_clipManager->updatePreviewSettings();
382 doc = m_render->sceneList();
383 KdenliveSettings::setDropbframes(true);
384 m_clipManager->updatePreviewSettings();
385 } else doc = m_render->sceneList();
386 saveSceneList(m_autosave->fileName(), doc);
390 void KdenliveDoc::setZoom(int factor)
392 m_documentProperties["zoom"] = QString::number(factor);
395 int KdenliveDoc::zoom() const
397 return m_documentProperties.value("zoom").toInt();
400 void KdenliveDoc::setZone(int start, int end)
402 m_documentProperties["zonein"] = QString::number(start);
403 m_documentProperties["zoneout"] = QString::number(end);
406 QPoint KdenliveDoc::zone() const
408 return QPoint(m_documentProperties.value("zonein").toInt(), m_documentProperties.value("zoneout").toInt());
411 bool KdenliveDoc::saveSceneList(const QString &path, const QString &scene)
413 QDomDocument sceneList;
414 sceneList.setContent(scene, true);
415 QDomElement mlt = sceneList.firstChildElement("mlt");
416 QDomElement addedXml = sceneList.createElement("kdenlivedoc");
417 mlt.appendChild(addedXml);
419 QDomElement markers = sceneList.createElement("markers");
420 addedXml.setAttribute("version", DOCUMENTVERSION);
421 addedXml.setAttribute("kdenliveversion", VERSION);
422 addedXml.setAttribute("profile", profilePath());
423 addedXml.setAttribute("projectfolder", m_projectFolder.path());
425 QDomElement docproperties = sceneList.createElement("documentproperties");
426 QMapIterator<QString, QString> i(m_documentProperties);
427 while (i.hasNext()) {
429 docproperties.setAttribute(i.key(), i.value());
431 docproperties.setAttribute("position", m_render->seekPosition().frames(m_fps));
432 addedXml.appendChild(docproperties);
435 QDomElement profileinfo = sceneList.createElement("profileinfo");
436 profileinfo.setAttribute("description", m_profile.description);
437 profileinfo.setAttribute("frame_rate_num", m_profile.frame_rate_num);
438 profileinfo.setAttribute("frame_rate_den", m_profile.frame_rate_den);
439 profileinfo.setAttribute("width", m_profile.width);
440 profileinfo.setAttribute("height", m_profile.height);
441 profileinfo.setAttribute("progressive", m_profile.progressive);
442 profileinfo.setAttribute("sample_aspect_num", m_profile.sample_aspect_num);
443 profileinfo.setAttribute("sample_aspect_den", m_profile.sample_aspect_den);
444 profileinfo.setAttribute("display_aspect_num", m_profile.display_aspect_num);
445 profileinfo.setAttribute("display_aspect_den", m_profile.display_aspect_den);
446 addedXml.appendChild(profileinfo);
449 QDomElement tracksinfo = sceneList.createElement("tracksinfo");
450 foreach(const TrackInfo &info, m_tracksList) {
451 QDomElement trackinfo = sceneList.createElement("trackinfo");
452 if (info.type == AUDIOTRACK) trackinfo.setAttribute("type", "audio");
453 trackinfo.setAttribute("mute", info.isMute);
454 trackinfo.setAttribute("blind", info.isBlind);
455 trackinfo.setAttribute("locked", info.isLocked);
456 tracksinfo.appendChild(trackinfo);
458 addedXml.appendChild(tracksinfo);
460 // save project folders
461 QMap <QString, QString> folderlist = m_clipManager->documentFolderList();
463 QMapIterator<QString, QString> f(folderlist);
464 while (f.hasNext()) {
466 QDomElement folder = sceneList.createElement("folder");
467 folder.setAttribute("id", f.key());
468 folder.setAttribute("name", f.value());
469 addedXml.appendChild(folder);
472 // Save project clips
474 QList <DocClipBase*> list = m_clipManager->documentClipList();
475 for (int i = 0; i < list.count(); i++) {
476 e = list.at(i)->toXML();
477 e.setTagName("kdenlive_producer");
478 addedXml.appendChild(sceneList.importNode(e, true));
479 QList < CommentedTime > marks = list.at(i)->commentedSnapMarkers();
480 for (int j = 0; j < marks.count(); j++) {
481 QDomElement marker = sceneList.createElement("marker");
482 marker.setAttribute("time", marks.at(j).time().ms() / 1000);
483 marker.setAttribute("comment", marks.at(j).comment());
484 marker.setAttribute("id", e.attribute("id"));
485 markers.appendChild(marker);
488 addedXml.appendChild(markers);
491 if (!m_guidesXml.isNull()) addedXml.appendChild(sceneList.importNode(m_guidesXml.documentElement(), true));
494 addedXml.appendChild(sceneList.importNode(m_clipManager->groupsXml(), true));
496 //wes.appendChild(doc.importNode(kdenliveData, true));
499 if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
500 kWarning() << "////// ERROR writing to file: " << path;
501 KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1", path));
505 file.write(sceneList.toString().toUtf8());
506 if (file.error() != QFile::NoError) {
507 KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1", path));
515 ClipManager *KdenliveDoc::clipManager()
517 return m_clipManager;
520 KUrl KdenliveDoc::projectFolder() const
522 //if (m_projectFolder.isEmpty()) return KUrl(KStandardDirs::locateLocal("appdata", "/projects/"));
523 return m_projectFolder;
526 void KdenliveDoc::setProjectFolder(KUrl url)
528 if (url == m_projectFolder) return;
530 KStandardDirs::makeDir(url.path());
531 KStandardDirs::makeDir(url.path() + "/titles/");
532 KStandardDirs::makeDir(url.path() + "/thumbs/");
533 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);
534 m_projectFolder = url;
537 void KdenliveDoc::moveProjectData(KUrl url)
539 QList <DocClipBase*> list = m_clipManager->documentClipList();
540 //TODO: Also move ladspa effects files
541 for (int i = 0; i < list.count(); i++) {
542 DocClipBase *clip = list.at(i);
543 if (clip->clipType() == TEXT) {
544 // the image for title clip must be moved
545 KUrl oldUrl = clip->fileURL();
546 KUrl newUrl = KUrl(url.path() + "/titles/" + oldUrl.fileName());
547 KIO::Job *job = KIO::copy(oldUrl, newUrl);
548 if (KIO::NetAccess::synchronousRun(job, 0)) clip->setProperty("resource", newUrl.path());
550 QString hash = clip->getClipHash();
551 KUrl oldVideoThumbUrl = KUrl(m_projectFolder.path() + "/thumbs/" + hash + ".png");
552 KUrl oldAudioThumbUrl = KUrl(m_projectFolder.path() + "/thumbs/" + hash + ".thumb");
553 if (KIO::NetAccess::exists(oldVideoThumbUrl, KIO::NetAccess::SourceSide, 0)) {
554 KUrl newUrl = KUrl(url.path() + "/thumbs/" + hash + ".png");
555 KIO::Job *job = KIO::copy(oldVideoThumbUrl, newUrl);
556 KIO::NetAccess::synchronousRun(job, 0);
558 if (KIO::NetAccess::exists(oldAudioThumbUrl, KIO::NetAccess::SourceSide, 0)) {
559 KUrl newUrl = KUrl(url.path() + "/thumbs/" + hash + ".thumb");
560 KIO::Job *job = KIO::copy(oldAudioThumbUrl, newUrl);
561 if (KIO::NetAccess::synchronousRun(job, 0)) clip->refreshThumbUrl();
566 const QString &KdenliveDoc::profilePath() const
568 return m_profile.path;
571 MltVideoProfile KdenliveDoc::mltProfile() const
576 void KdenliveDoc::setProfilePath(QString path)
578 if (path.isEmpty()) path = KdenliveSettings::default_profile();
579 if (path.isEmpty()) path = "dv_pal";
580 m_profile = ProfilesDialog::getVideoProfile(path);
581 if (m_profile.path.isEmpty()) {
582 // Profile not found, use embedded profile
583 QDomElement profileInfo = m_document.elementsByTagName("profileinfo").at(0).toElement();
584 if (profileInfo.isNull()) {
585 KMessageBox::information(kapp->activeWindow(), i18n("Project profile was not found, using default profile."), i18n("Missing Profile"));
586 m_profile = ProfilesDialog::getVideoProfile(KdenliveSettings::default_profile());
588 m_profile.description = profileInfo.attribute("description");
589 m_profile.frame_rate_num = profileInfo.attribute("frame_rate_num").toInt();
590 m_profile.frame_rate_den = profileInfo.attribute("frame_rate_den").toInt();
591 m_profile.width = profileInfo.attribute("width").toInt();
592 m_profile.height = profileInfo.attribute("height").toInt();
593 m_profile.progressive = profileInfo.attribute("progressive").toInt();
594 m_profile.sample_aspect_num = profileInfo.attribute("sample_aspect_num").toInt();
595 m_profile.sample_aspect_den = profileInfo.attribute("sample_aspect_den").toInt();
596 m_profile.display_aspect_num = profileInfo.attribute("display_aspect_num").toInt();
597 m_profile.display_aspect_den = profileInfo.attribute("display_aspect_den").toInt();
598 QString existing = ProfilesDialog::existingProfile(m_profile);
599 if (!existing.isEmpty()) {
600 m_profile = ProfilesDialog::getVideoProfile(existing);
601 KMessageBox::information(kapp->activeWindow(), i18n("Project profile not found, replacing with existing one: %1", m_profile.description), i18n("Missing Profile"));
603 QString newDesc = m_profile.description;
605 while (ok && (newDesc.isEmpty() || ProfilesDialog::existingProfileDescription(newDesc))) {
606 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);
609 // User canceled, use default profile
610 m_profile = ProfilesDialog::getVideoProfile(KdenliveSettings::default_profile());
612 if (newDesc != m_profile.description) {
613 // Profile description existed, was replaced by new one
614 m_profile.description = newDesc;
616 KMessageBox::information(kapp->activeWindow(), i18n("Project profile was not found, it will be added to your system now."), i18n("Missing Profile"));
618 ProfilesDialog::saveProfile(m_profile);
625 KdenliveSettings::setProject_display_ratio((double) m_profile.display_aspect_num / m_profile.display_aspect_den);
626 m_fps = (double) m_profile.frame_rate_num / m_profile.frame_rate_den;
627 KdenliveSettings::setProject_fps(m_fps);
628 m_width = m_profile.width;
629 m_height = m_profile.height;
630 kDebug() << "Kdenlive document, init timecode from path: " << path << ", " << m_fps;
631 if (m_fps == 30000.0 / 1001.0) m_timecode.setFormat(30, true);
632 else m_timecode.setFormat((int) m_fps);
635 double KdenliveDoc::dar()
637 return (double) m_profile.display_aspect_num / m_profile.display_aspect_den;
640 void KdenliveDoc::setThumbsProgress(const QString &message, int progress)
642 emit progressInfo(message, progress);
645 void KdenliveDoc::loadingProgressed()
647 m_documentLoadingProgress += m_documentLoadingStep;
648 emit progressInfo(QString(), (int) m_documentLoadingProgress);
651 QUndoStack *KdenliveDoc::commandStack()
653 return m_commandStack;
657 void KdenliveDoc::setRenderer(Render *render) {
658 if (m_render) return;
660 emit progressInfo(i18n("Loading playlist..."), 0);
661 //qApp->processEvents();
663 m_render->setSceneList(m_document.toString(), m_startPos);
664 kDebug() << "// SETTING SCENE LIST:\n\n" << m_document.toString();
667 emit progressInfo(QString(), -1);
670 void KdenliveDoc::checkProjectClips()
672 kDebug() << "+++++++++++++ + + + + CHK PCLIPS";
673 if (m_render == NULL) return;
674 m_clipManager->resetProducersList(m_render->producersList());
678 QList <Mlt::Producer *> prods = m_render->producersList();
682 for (int i = 0; i < prods.count(); i++) {
683 id = prods.at(i)->get("id");
684 prodId = id.section('_', 0, 0);
685 prodTrack = id.section('_', 1, 1);
686 DocClipBase *clip = m_clipManager->getClipById(prodId);
687 if (clip) clip->setProducer(prods.at(i));
688 if (clip && clip->clipType() == TEXT && !QFile::exists(clip->fileURL().path())) {
689 // regenerate text clip image if required
690 //kDebug() << "// TITLE: " << clip->getProperty("titlename") << " Preview file: " << clip->getProperty("resource") << " DOES NOT EXIST";
691 QString titlename = clip->getProperty("name");
692 QString titleresource;
693 if (titlename.isEmpty()) {
694 QStringList titleInfo = TitleWidget::getFreeTitleInfo(projectFolder());
695 titlename = titleInfo.at(0);
696 titleresource = titleInfo.at(1);
697 clip->setProperty("name", titlename);
698 kDebug() << "// New title set to: " << titlename;
700 titleresource = TitleWidget::getFreeTitleInfo(projectFolder()).at(1);
701 //titleresource = TitleWidget::getTitleResourceFromName(projectFolder(), titlename);
703 TitleWidget *dia_ui = new TitleWidget(KUrl(), KUrl(titleresource).directory(), m_render, kapp->activeWindow());
705 doc.setContent(clip->getProperty("xmldata"));
707 QImage pix = dia_ui->renderedPixmap();
708 pix.save(titleresource);
709 clip->setProperty("resource", titleresource);
711 clip->producer()->set("force_reload", 1);
716 void KdenliveDoc::updatePreviewSettings()
718 m_clipManager->updatePreviewSettings();
719 m_render->updatePreviewSettings();
720 m_clipManager->resetProducersList(m_render->producersList());
724 Render *KdenliveDoc::renderer()
729 void KdenliveDoc::updateClip(const QString &id)
731 emit updateClipDisplay(id);
734 int KdenliveDoc::getFramePos(QString duration)
736 return m_timecode.getFrameCount(duration, m_fps);
739 QString KdenliveDoc::producerName(const QString &id)
741 QString result = "unnamed";
742 QDomNodeList prods = producersList();
743 int ct = prods.count();
744 for (int i = 0; i < ct ; i++) {
745 QDomElement e = prods.item(i).toElement();
746 if (e.attribute("id") != "black" && e.attribute("id") == id) {
747 result = e.attribute("name");
748 if (result.isEmpty()) result = KUrl(e.attribute("resource")).fileName();
755 QDomDocument KdenliveDoc::toXml()
760 Timecode KdenliveDoc::timecode() const
765 QDomNodeList KdenliveDoc::producersList()
767 return m_document.elementsByTagName("producer");
770 double KdenliveDoc::projectDuration() const
773 return GenTime(m_render->getLength(), m_fps).ms() / 1000;
778 double KdenliveDoc::fps() const
783 int KdenliveDoc::width() const
788 int KdenliveDoc::height() const
793 KUrl KdenliveDoc::url() const
798 void KdenliveDoc::setUrl(KUrl url)
803 void KdenliveDoc::setModified(bool mod)
805 if (!m_url.isEmpty() && mod && KdenliveSettings::crashrecovery()) {
806 m_autoSaveTimer->start(3000);
808 if (mod == m_modified) return;
810 emit docModified(m_modified);
813 bool KdenliveDoc::isModified() const
818 const QString KdenliveDoc::description() const
821 return i18n("Untitled") + " / " + m_profile.description;
823 return m_url.fileName() + " / " + m_profile.description;
826 void KdenliveDoc::addClip(QDomElement elem, QString clipId, bool createClipItem)
828 const QString producerId = clipId.section('_', 0, 0);
829 DocClipBase *clip = m_clipManager->getClipById(producerId);
832 elem.setAttribute("id", producerId);
833 QString path = elem.attribute("resource");
835 if (elem.attribute("type").toInt() == SLIDESHOW) {
836 extension = KUrl(path).fileName();
837 path = KUrl(path).directory();
838 } else if (elem.attribute("type").toInt() == TEXT && QFile::exists(path) == false) {
839 kDebug() << "// TITLE: " << elem.attribute("name") << " Preview file: " << elem.attribute("resource") << " DOES NOT EXIST";
840 QString titlename = elem.attribute("name");
841 QString titleresource;
842 if (titlename.isEmpty()) {
843 QStringList titleInfo = TitleWidget::getFreeTitleInfo(projectFolder());
844 titlename = titleInfo.at(0);
845 titleresource = titleInfo.at(1);
846 elem.setAttribute("name", titlename);
847 kDebug() << "// New title set to: " << titlename;
849 titleresource = TitleWidget::getFreeTitleInfo(projectFolder()).at(1);
850 //titleresource = TitleWidget::getTitleResourceFromName(projectFolder(), titlename);
852 TitleWidget *dia_ui = new TitleWidget(KUrl(), KUrl(titleresource).directory(), m_render, kapp->activeWindow());
854 doc.setContent(elem.attribute("xmldata"));
856 QImage pix = dia_ui->renderedPixmap();
857 pix.save(titleresource);
858 elem.setAttribute("resource", titleresource);
859 setNewClipResource(clipId, titleresource);
863 if (path.isEmpty() == false && QFile::exists(path) == false && elem.attribute("type").toInt() != TEXT && !elem.hasAttribute("placeholder")) {
864 kDebug() << "// FOUND MISSING CLIP: " << path << ", TYPE: " << elem.attribute("type").toInt();
865 const QString size = elem.attribute("file_size");
866 const QString hash = elem.attribute("file_hash");
868 int action = KMessageBox::No;
869 if (!size.isEmpty() && !hash.isEmpty()) {
870 if (!m_searchFolder.isEmpty()) newpath = searchFileRecursively(m_searchFolder, size, hash);
871 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")));
873 if (elem.attribute("type").toInt() == SLIDESHOW) {
874 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")));
875 if (res == KMessageBox::Yes)
876 newpath = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow(), i18n("Looking for %1", path));
878 // Abort project loading
882 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")));
883 if (res == KMessageBox::Yes)
884 newpath = KFileDialog::getOpenFileName(KUrl("kfiledialog:///clipfolder"), QString(), kapp->activeWindow(), i18n("Looking for %1", path));
886 // Abort project loading
891 if (action == KMessageBox::Yes) {
892 kDebug() << "// ASKED FOR SRCH CLIP: " << clipId;
893 m_searchFolder = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow());
894 if (!m_searchFolder.isEmpty()) {
895 newpath = searchFileRecursively(QDir(m_searchFolder), size, hash);
897 } else if (action == KMessageBox::Cancel) {
898 m_abortLoading = true;
900 } else if (action == KMessageBox::No) {
901 // Keep clip as placeHolder
902 elem.setAttribute("placeholder", '1');
904 if (!newpath.isEmpty()) {
905 if (elem.attribute("type").toInt() == SLIDESHOW) newpath.append('/' + extension);
906 elem.setAttribute("resource", newpath);
907 setNewClipResource(clipId, newpath);
911 clip = new DocClipBase(m_clipManager, elem, producerId);
912 m_clipManager->addClip(clip);
915 if (createClipItem) {
916 emit addProjectClip(clip);
917 qApp->processEvents();
918 m_render->getFileProperties(clip->toXML(), clip->getId(), false);
923 void KdenliveDoc::setNewClipResource(const QString &id, const QString &path)
925 QDomNodeList prods = m_document.elementsByTagName("producer");
926 int maxprod = prods.count();
927 for (int i = 0; i < maxprod; i++) {
928 QDomNode m = prods.at(i);
929 QString prodId = m.toElement().attribute("id");
930 if (prodId == id || prodId.startsWith(id + '_')) {
931 QDomNodeList params = m.childNodes();
932 for (int j = 0; j < params.count(); j++) {
933 QDomElement e = params.item(j).toElement();
934 if (e.attribute("name") == "resource") {
935 e.firstChild().setNodeValue(path);
943 QString KdenliveDoc::searchFileRecursively(const QDir &dir, const QString &matchSize, const QString &matchHash) const
945 QString foundFileName;
948 QStringList filesAndDirs = dir.entryList(QDir::Files | QDir::Readable);
949 for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
950 QFile file(dir.absoluteFilePath(filesAndDirs.at(i)));
951 if (file.open(QIODevice::ReadOnly)) {
952 if (QString::number(file.size()) == matchSize) {
954 * 1 MB = 1 second per 450 files (or faster)
955 * 10 MB = 9 seconds per 450 files (or faster)
957 if (file.size() > 1000000*2) {
958 fileData = file.read(1000000);
959 if (file.seek(file.size() - 1000000))
960 fileData.append(file.readAll());
962 fileData = file.readAll();
964 fileHash = QCryptographicHash::hash(fileData, QCryptographicHash::Md5);
965 if (QString(fileHash.toHex()) == matchHash)
966 return file.fileName();
969 kDebug() << filesAndDirs.at(i) << file.size() << fileHash.toHex();
971 filesAndDirs = dir.entryList(QDir::Dirs | QDir::Readable | QDir::Executable | QDir::NoDotAndDotDot);
972 for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
973 foundFileName = searchFileRecursively(dir.absoluteFilePath(filesAndDirs.at(i)), matchSize, matchHash);
974 if (!foundFileName.isEmpty())
977 return foundFileName;
980 void KdenliveDoc::addClipInfo(QDomElement elem, QDomElement orig, QString clipId)
982 DocClipBase *clip = m_clipManager->getClipById(clipId);
984 addClip(elem, clipId, false);
986 QMap <QString, QString> properties;
987 QDomNamedNodeMap attributes = elem.attributes();
989 for (int i = 0; i < attributes.count(); i++) {
990 attrname = attributes.item(i).nodeName();
991 if (attrname != "resource")
992 properties.insert(attrname, attributes.item(i).nodeValue());
993 kDebug() << attrname << " = " << attributes.item(i).nodeValue();
995 clip->setProperties(properties);
996 emit addProjectClip(clip, false);
998 if (orig != QDomElement()) {
999 QMap<QString, QString> meta;
1000 QDomNode m = orig.firstChild();
1001 while (!m.isNull()) {
1002 QString name = m.toElement().attribute("name");
1003 if (name.startsWith("meta.attr")) {
1004 meta.insert(name.section('.', 2, 3), m.firstChild().nodeValue());
1006 m = m.nextSibling();
1008 if (!meta.isEmpty()) {
1009 if (clip == NULL) clip = m_clipManager->getClipById(clipId);
1010 if (clip) clip->setMetadata(meta);
1015 void KdenliveDoc::deleteProjectClip(QList <QString> ids)
1017 for (int i = 0; i < ids.size(); ++i) {
1018 emit deleteTimelineClip(ids.at(i));
1019 m_clipManager->slotDeleteClip(ids.at(i));
1024 void KdenliveDoc::deleteClip(const QString &clipId)
1026 emit signalDeleteProjectClip(clipId);
1027 m_clipManager->deleteClip(clipId);
1030 void KdenliveDoc::slotAddClipList(const KUrl::List urls, const QString group, const QString &groupId)
1032 m_clipManager->slotAddClipList(urls, group, groupId);
1033 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1038 void KdenliveDoc::slotAddClipFile(const KUrl url, const QString group, const QString &groupId)
1040 m_clipManager->slotAddClipFile(url, group, groupId);
1041 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1045 const QString KdenliveDoc::getFreeClipId()
1047 return QString::number(m_clipManager->getFreeClipId());
1050 DocClipBase *KdenliveDoc::getBaseClip(const QString &clipId)
1052 return m_clipManager->getClipById(clipId);
1055 void KdenliveDoc::slotCreateColorClip(const QString &name, const QString &color, const QString &duration, QString group, const QString &groupId)
1057 m_clipManager->slotAddColorClipFile(name, color, duration, group, groupId);
1059 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1062 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)
1064 m_clipManager->slotAddSlideshowClipFile(name, path, count, duration, loop, fade, luma_duration, luma_file, softness, group, groupId);
1066 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1069 void KdenliveDoc::slotCreateTextClip(QString group, const QString &groupId, const QString &templatePath)
1071 QString titlesFolder = projectFolder().path() + "/titles/";
1072 KStandardDirs::makeDir(titlesFolder);
1073 TitleWidget *dia_ui = new TitleWidget(templatePath, titlesFolder, m_render, kapp->activeWindow());
1074 if (dia_ui->exec() == QDialog::Accepted) {
1075 QStringList titleInfo = TitleWidget::getFreeTitleInfo(projectFolder());
1076 QImage pix = dia_ui->renderedPixmap();
1077 pix.save(titleInfo.at(1));
1078 //dia_ui->saveTitle(path + ".kdenlivetitle");
1079 m_clipManager->slotAddTextClipFile(titleInfo.at(0), titleInfo.at(1), dia_ui->xml().toString(), group, groupId);
1081 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1086 void KdenliveDoc::slotCreateTextTemplateClip(QString group, const QString &groupId, KUrl path)
1088 QString titlesFolder = projectFolder().path() + "/titles/";
1089 if (path.isEmpty()) {
1090 path = KFileDialog::getOpenUrl(KUrl(titlesFolder), "*.kdenlivetitle", kapp->activeWindow(), i18n("Enter Template Path"));
1093 if (path.isEmpty()) return;
1095 QStringList titleInfo = TitleWidget::getFreeTitleInfo(projectFolder());
1097 TitleWidget *dia_ui = new TitleWidget(path, titlesFolder, m_render, kapp->activeWindow());
1098 QImage pix = dia_ui->renderedPixmap();
1099 pix.save(titleInfo.at(1));
1101 m_clipManager->slotAddTextTemplateClip(titleInfo.at(0), titleInfo.at(1), path, group, groupId);
1103 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1106 int KdenliveDoc::tracksCount() const
1108 return m_tracksList.count();
1111 TrackInfo KdenliveDoc::trackInfoAt(int ix) const
1113 return m_tracksList.at(ix);
1116 void KdenliveDoc::switchTrackAudio(int ix, bool hide)
1118 m_tracksList[ix].isMute = hide; // !m_tracksList.at(ix).isMute;
1121 void KdenliveDoc::switchTrackLock(int ix, bool lock)
1123 m_tracksList[ix].isLocked = lock;
1126 bool KdenliveDoc::isTrackLocked(int ix) const
1128 return m_tracksList.at(ix).isLocked;
1131 void KdenliveDoc::switchTrackVideo(int ix, bool hide)
1133 m_tracksList[ix].isBlind = hide; // !m_tracksList.at(ix).isBlind;
1136 void KdenliveDoc::insertTrack(int ix, TrackInfo type)
1138 if (ix == -1) m_tracksList << type;
1139 else m_tracksList.insert(ix, type);
1142 void KdenliveDoc::deleteTrack(int ix)
1144 m_tracksList.removeAt(ix);
1147 void KdenliveDoc::setTrackType(int ix, TrackInfo type)
1149 m_tracksList[ix].type = type.type;
1150 m_tracksList[ix].isMute = type.isMute;
1151 m_tracksList[ix].isBlind = type.isBlind;
1152 m_tracksList[ix].isLocked = type.isLocked;
1155 const QList <TrackInfo> KdenliveDoc::tracksList() const
1157 return m_tracksList;
1160 QPoint KdenliveDoc::getTracksCount() const
1164 foreach(const TrackInfo &info, m_tracksList) {
1165 if (info.type == VIDEOTRACK) video++;
1168 return QPoint(video, audio);
1171 void KdenliveDoc::cachePixmap(const QString &fileId, const QPixmap &pix) const
1173 pix.save(m_projectFolder.path() + "/thumbs/" + fileId + ".png");
1176 QString KdenliveDoc::getLadspaFile() const
1179 QString counter = QString::number(ct).rightJustified(5, '0', false);
1180 while (QFile::exists(m_projectFolder.path() + "/ladspa/" + counter + ".ladspa")) {
1182 counter = QString::number(ct).rightJustified(5, '0', false);
1184 return m_projectFolder.path() + "/ladspa/" + counter + ".ladspa";
1187 bool KdenliveDoc::checkDocumentClips(QDomNodeList infoproducers)
1193 QList <QDomElement> missingClips;
1194 for (int i = 0; i < infoproducers.count(); i++) {
1195 e = infoproducers.item(i).toElement();
1196 clipType = e.attribute("type").toInt();
1197 if (clipType == TEXT || clipType == COLOR) continue;
1198 id = e.attribute("id");
1199 resource = e.attribute("resource");
1200 if (clipType == SLIDESHOW) resource = KUrl(resource).directory();
1201 if (!KIO::NetAccess::exists(KUrl(resource), KIO::NetAccess::SourceSide, 0)) {
1202 // Missing clip found
1203 missingClips.append(e);
1206 if (missingClips.isEmpty()) return true;
1207 DocumentChecker d(missingClips, m_document);
1208 return (d.exec() == QDialog::Accepted);
1211 void KdenliveDoc::setDocumentProperty(const QString &name, const QString &value)
1213 m_documentProperties[name] = value;
1216 const QString KdenliveDoc::getDocumentProperty(const QString &name) const
1218 return m_documentProperties.value(name);
1221 #include "kdenlivedoc.moc"