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>
45 #include <QDomImplementation>
47 #include <mlt++/Mlt.h>
49 const double DOCUMENTVERSION = 0.85;
51 KdenliveDoc::KdenliveDoc(const KUrl &url, const KUrl &projectFolder, QUndoGroup *undoGroup, QString profileName, const QPoint tracks, Render *render, MainWindow *parent) :
56 m_commandStack(new QUndoStack(undoGroup)),
58 m_projectFolder(projectFolder),
61 m_clipManager = new ClipManager(this);
62 m_autoSaveTimer = new QTimer(this);
63 m_autoSaveTimer->setSingleShot(true);
66 // init default document properties
67 m_documentProperties["zoom"] = "7";
68 m_documentProperties["verticalzoom"] = "1";
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 QDomImplementation impl;
81 impl.setInvalidDataPolicy(QDomImplementation::DropInvalidChars);
82 success = m_document.setContent(&file, false, &errorMsg);
84 KIO::NetAccess::removeTempFile(tmpFile);
86 if (!success) // It is corrupted
87 KMessageBox::error(parent, errorMsg);
89 parent->slotGotProgressInfo(i18n("Validating"), 0);
90 DocumentValidator validator(m_document);
91 success = validator.isProject();
93 // It is not a project file
94 parent->slotGotProgressInfo(i18n("File %1 is not a Kdenlive project file", m_url.path()), 0);
97 * Validate the file against the current version (upgrade
98 * and recover it if needed). It is NOT a passive operation
100 // TODO: backup the document or alert the user?
101 success = validator.validate(DOCUMENTVERSION);
102 if (success) { // Let the validator handle error messages
103 parent->slotGotProgressInfo(i18n("Loading"), 0);
104 QDomElement mlt = m_document.firstChildElement("mlt");
105 QDomElement infoXml = mlt.firstChildElement("kdenlivedoc");
107 profileName = infoXml.attribute("profile");
108 m_projectFolder = KUrl(infoXml.attribute("projectfolder"));
109 QDomElement docproperties = infoXml.firstChildElement("documentproperties");
110 QDomNamedNodeMap props = docproperties.attributes();
111 for (int i = 0; i < props.count(); i++) {
112 m_documentProperties.insert(props.item(i).nodeName(), props.item(i).nodeValue());
116 QDomElement tracksinfo = infoXml.firstChildElement("tracksinfo");
117 TrackInfo projectTrack;
118 if (!tracksinfo.isNull()) {
119 QDomNodeList trackslist = tracksinfo.childNodes();
120 int maxchild = trackslist.count();
121 for (int k = 0; k < maxchild; k++) {
122 e = trackslist.at(k).toElement();
123 if (e.tagName() == "trackinfo") {
124 if (e.attribute("type") == "audio") projectTrack.type = AUDIOTRACK;
125 else projectTrack.type = VIDEOTRACK;
126 projectTrack.isMute = e.attribute("mute").toInt();
127 projectTrack.isBlind = e.attribute("blind").toInt();
128 projectTrack.isLocked = e.attribute("locked").toInt();
129 projectTrack.trackName = e.attribute("trackname");
130 m_tracksList.append(projectTrack);
133 mlt.removeChild(tracksinfo);
135 QDomNodeList producers = m_document.elementsByTagName("producer");
136 QDomNodeList infoproducers = m_document.elementsByTagName("kdenlive_producer");
137 parent->slotGotProgressInfo(i18n("Check missing clips"), 0);
138 if (checkDocumentClips(infoproducers) == false) m_abortLoading = true;
139 const int max = producers.count();
140 const int infomax = infoproducers.count();
142 QDomNodeList folders = m_document.elementsByTagName("folder");
143 for (int i = 0; i < folders.count(); i++) {
144 e = folders.item(i).cloneNode().toElement();
145 m_clipManager->addFolder(e.attribute("id"), e.attribute("name"));
148 for (int i = 0; i < infomax && !m_abortLoading; i++) {
149 e = infoproducers.item(i).cloneNode().toElement();
150 QString prodId = e.attribute("id");
151 if (!e.isNull() && prodId != "black" && !prodId.startsWith("slowmotion") && !m_abortLoading) {
152 e.setTagName("producer");
153 // Get MLT's original producer properties
155 for (int j = 0; j < max; j++) {
156 QDomElement o = producers.item(j).cloneNode().toElement();
157 QString origId = o.attribute("id").section('_', 0, 0);
158 if (origId == prodId) {
163 addClipInfo(e, orig, prodId);
166 if (m_abortLoading) {
167 //parent->slotGotProgressInfo(i18n("File %1 is not a Kdenlive project file."), 100);
168 emit resetProjectList();
169 m_documentProperties.remove("position");
171 m_tracksList.clear();
172 kWarning() << "Aborted loading of: " << url.path();
173 m_document = createEmptyDocument(KdenliveSettings::videotracks(), KdenliveSettings::audiotracks());
174 setProfilePath(KdenliveSettings::default_profile());
175 m_clipManager->clear();
177 QDomElement markers = infoXml.firstChildElement("markers");
178 if (!markers.isNull()) {
179 QDomNodeList markerslist = markers.childNodes();
180 int maxchild = markerslist.count();
181 for (int k = 0; k < maxchild; k++) {
182 e = markerslist.at(k).toElement();
183 if (e.tagName() == "marker") {
184 m_clipManager->getClipById(e.attribute("id"))->addSnapMarker(GenTime(e.attribute("time").toDouble()), e.attribute("comment"));
187 infoXml.removeChild(markers);
189 setProfilePath(profileName);
190 setModified(validator.isModified());
191 kDebug() << "Reading file: " << url.path() << ", found clips: " << producers.count();
199 // Something went wrong, or a new file was requested: create a new project
201 setProfilePath(profileName);
203 m_document = createEmptyDocument(tracks.x(), tracks.y());
206 KdenliveSettings::setCurrent_profile(profilePath());
208 // Set the video profile (empty == default)
210 // Make sure the project folder is usable
211 if (m_projectFolder.isEmpty() || !KIO::NetAccess::exists(m_projectFolder.path(), KIO::NetAccess::DestinationSide, parent)) {
212 KMessageBox::information(parent, i18n("Document project folder is invalid, setting it to the default one: %1", KdenliveSettings::defaultprojectfolder()));
213 m_projectFolder = KUrl(KdenliveSettings::defaultprojectfolder());
216 // Make sure that the necessary folders exist
217 KStandardDirs::makeDir(m_projectFolder.path(KUrl::AddTrailingSlash) + "titles/");
218 KStandardDirs::makeDir(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/");
219 KStandardDirs::makeDir(m_projectFolder.path(KUrl::AddTrailingSlash) + "ladspa/");
221 kDebug() << "Kdenlive document, init timecode: " << m_fps;
222 if (m_fps == 30000.0 / 1001.0) m_timecode.setFormat(m_fps, true);
223 else m_timecode.setFormat(m_fps);
225 //kDebug() << "// SETTING SCENE LIST:\n\n" << m_document.toString();
226 connect(m_autoSaveTimer, SIGNAL(timeout()), this, SLOT(slotAutoSave()));
229 KdenliveDoc::~KdenliveDoc()
231 m_autoSaveTimer->stop();
232 delete m_commandStack;
233 kDebug() << "// DEL CLP MAN";
234 delete m_clipManager;
235 kDebug() << "// DEL CLP MAN done";
236 delete m_autoSaveTimer;
238 if (!m_autosave->fileName().isEmpty()) m_autosave->remove();
243 int KdenliveDoc::setSceneList()
245 m_render->resetProfile(KdenliveSettings::current_profile());
246 if (m_render->setSceneList(m_document.toString(), m_documentProperties.value("position").toInt()) == -1) {
247 // INVALID MLT Consumer, something is wrong
250 m_documentProperties.remove("position");
251 // m_document xml is now useless, clear it
256 QDomDocument KdenliveDoc::createEmptyDocument(int videotracks, int audiotracks)
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 m_tracksList.clear();
272 for (int i = 0; i < audiotracks; i++) {
273 m_tracksList.append(audioTrack);
275 for (int i = 0; i < videotracks; i++) {
276 m_tracksList.append(videoTrack);
278 return createEmptyDocument(m_tracksList);
281 QDomDocument KdenliveDoc::createEmptyDocument(QList <TrackInfo> tracks)
283 // Creating new document
285 QDomElement mlt = doc.createElement("mlt");
286 doc.appendChild(mlt);
289 // Create black producer
290 // For some unknown reason, we have to build the black producer here and not in renderer.cpp, otherwise
291 // the composite transitions with the black track are corrupted.
292 QDomElement blk = doc.createElement("producer");
293 blk.setAttribute("in", 0);
294 blk.setAttribute("out", 500);
295 blk.setAttribute("id", "black");
297 QDomElement property = doc.createElement("property");
298 property.setAttribute("name", "mlt_type");
299 QDomText value = doc.createTextNode("producer");
300 property.appendChild(value);
301 blk.appendChild(property);
303 property = doc.createElement("property");
304 property.setAttribute("name", "aspect_ratio");
305 value = doc.createTextNode(QString::number(0.0));
306 property.appendChild(value);
307 blk.appendChild(property);
309 property = doc.createElement("property");
310 property.setAttribute("name", "length");
311 value = doc.createTextNode(QString::number(15000));
312 property.appendChild(value);
313 blk.appendChild(property);
315 property = doc.createElement("property");
316 property.setAttribute("name", "eof");
317 value = doc.createTextNode("pause");
318 property.appendChild(value);
319 blk.appendChild(property);
321 property = doc.createElement("property");
322 property.setAttribute("name", "resource");
323 value = doc.createTextNode("black");
324 property.appendChild(value);
325 blk.appendChild(property);
327 property = doc.createElement("property");
328 property.setAttribute("name", "mlt_service");
329 value = doc.createTextNode("colour");
330 property.appendChild(value);
331 blk.appendChild(property);
333 mlt.appendChild(blk);
336 QDomElement tractor = doc.createElement("tractor");
337 tractor.setAttribute("id", "maintractor");
338 QDomElement multitrack = doc.createElement("multitrack");
339 QDomElement playlist = doc.createElement("playlist");
340 playlist.setAttribute("id", "black_track");
341 mlt.appendChild(playlist);
343 QDomElement blank0 = doc.createElement("entry");
344 blank0.setAttribute("in", "0");
345 blank0.setAttribute("out", "0");
346 blank0.setAttribute("producer", "black");
347 playlist.appendChild(blank0);
350 int total = tracks.count() + 1;
352 for (int i = 1; i < total; i++) {
353 QDomElement playlist = doc.createElement("playlist");
354 playlist.setAttribute("id", "playlist" + QString::number(i));
355 mlt.appendChild(playlist);
358 QDomElement track0 = doc.createElement("track");
359 track0.setAttribute("producer", "black_track");
360 tractor.appendChild(track0);
362 // create audio tracks
363 for (int i = 1; i < total; i++) {
364 QDomElement track = doc.createElement("track");
365 track.setAttribute("producer", "playlist" + QString::number(i));
366 if (tracks.at(i - 1).type == AUDIOTRACK)
367 track.setAttribute("hide", "video");
368 else if (tracks.at(i - 1).isBlind)
369 track.setAttribute("hide", "video");
370 if (tracks.at(i - 1).isMute)
371 track.setAttribute("hide", "audio");
372 tractor.appendChild(track);
375 for (int i = 2; i < total ; i++) {
376 QDomElement transition = doc.createElement("transition");
377 transition.setAttribute("always_active", "1");
379 QDomElement property = doc.createElement("property");
380 property.setAttribute("name", "a_track");
381 QDomText value = doc.createTextNode(QString::number(1));
382 property.appendChild(value);
383 transition.appendChild(property);
385 property = doc.createElement("property");
386 property.setAttribute("name", "b_track");
387 value = doc.createTextNode(QString::number(i));
388 property.appendChild(value);
389 transition.appendChild(property);
391 property = doc.createElement("property");
392 property.setAttribute("name", "mlt_service");
393 value = doc.createTextNode("mix");
394 property.appendChild(value);
395 transition.appendChild(property);
397 property = doc.createElement("property");
398 property.setAttribute("name", "combine");
399 value = doc.createTextNode("1");
400 property.appendChild(value);
401 transition.appendChild(property);
403 property = doc.createElement("property");
404 property.setAttribute("name", "internal_added");
405 value = doc.createTextNode("237");
406 property.appendChild(value);
407 transition.appendChild(property);
408 tractor.appendChild(transition);
410 mlt.appendChild(tractor);
415 void KdenliveDoc::syncGuides(QList <Guide *> guides)
418 QDomElement guideNode = m_guidesXml.createElement("guides");
419 m_guidesXml.appendChild(guideNode);
422 for (int i = 0; i < guides.count(); i++) {
423 e = m_guidesXml.createElement("guide");
424 e.setAttribute("time", guides.at(i)->position().ms() / 1000);
425 e.setAttribute("comment", guides.at(i)->label());
426 guideNode.appendChild(e);
429 emit guidesUpdated();
432 QDomElement KdenliveDoc::guidesXml() const
434 return m_guidesXml.documentElement();
437 void KdenliveDoc::slotAutoSave()
439 if (m_render && m_autosave) {
440 if (!m_autosave->isOpen() && !m_autosave->open(QIODevice::ReadWrite)) {
441 // show error: could not open the autosave file
442 kDebug() << "ERROR; CANNOT CREATE AUTOSAVE FILE";
444 kDebug() << "// AUTOSAVE FILE: " << m_autosave->fileName();
446 if (KdenliveSettings::dropbframes()) {
447 KdenliveSettings::setDropbframes(false);
448 m_clipManager->updatePreviewSettings();
449 doc = m_render->sceneList();
450 KdenliveSettings::setDropbframes(true);
451 m_clipManager->updatePreviewSettings();
452 } else doc = m_render->sceneList();
453 saveSceneList(m_autosave->fileName(), doc);
457 void KdenliveDoc::setZoom(int horizontal, int vertical)
459 m_documentProperties["zoom"] = QString::number(horizontal);
460 m_documentProperties["verticalzoom"] = QString::number(vertical);
463 QPoint KdenliveDoc::zoom() const
465 return QPoint(m_documentProperties.value("zoom").toInt(), m_documentProperties.value("verticalzoom").toInt());
468 void KdenliveDoc::setZone(int start, int end)
470 m_documentProperties["zonein"] = QString::number(start);
471 m_documentProperties["zoneout"] = QString::number(end);
474 QPoint KdenliveDoc::zone() const
476 return QPoint(m_documentProperties.value("zonein").toInt(), m_documentProperties.value("zoneout").toInt());
479 bool KdenliveDoc::saveSceneList(const QString &path, const QString &scene)
481 QDomDocument sceneList;
482 sceneList.setContent(scene, true);
483 QDomElement mlt = sceneList.firstChildElement("mlt");
484 QDomElement addedXml = sceneList.createElement("kdenlivedoc");
485 mlt.appendChild(addedXml);
487 QDomElement markers = sceneList.createElement("markers");
488 addedXml.setAttribute("version", DOCUMENTVERSION);
489 addedXml.setAttribute("kdenliveversion", VERSION);
490 addedXml.setAttribute("profile", profilePath());
491 addedXml.setAttribute("projectfolder", m_projectFolder.path());
493 QDomElement docproperties = sceneList.createElement("documentproperties");
494 QMapIterator<QString, QString> i(m_documentProperties);
495 while (i.hasNext()) {
497 docproperties.setAttribute(i.key(), i.value());
499 docproperties.setAttribute("position", m_render->seekPosition().frames(m_fps));
500 addedXml.appendChild(docproperties);
503 QDomElement profileinfo = sceneList.createElement("profileinfo");
504 profileinfo.setAttribute("description", m_profile.description);
505 profileinfo.setAttribute("frame_rate_num", m_profile.frame_rate_num);
506 profileinfo.setAttribute("frame_rate_den", m_profile.frame_rate_den);
507 profileinfo.setAttribute("width", m_profile.width);
508 profileinfo.setAttribute("height", m_profile.height);
509 profileinfo.setAttribute("progressive", m_profile.progressive);
510 profileinfo.setAttribute("sample_aspect_num", m_profile.sample_aspect_num);
511 profileinfo.setAttribute("sample_aspect_den", m_profile.sample_aspect_den);
512 profileinfo.setAttribute("display_aspect_num", m_profile.display_aspect_num);
513 profileinfo.setAttribute("display_aspect_den", m_profile.display_aspect_den);
514 addedXml.appendChild(profileinfo);
517 QDomElement tracksinfo = sceneList.createElement("tracksinfo");
518 foreach(const TrackInfo &info, m_tracksList) {
519 QDomElement trackinfo = sceneList.createElement("trackinfo");
520 if (info.type == AUDIOTRACK) trackinfo.setAttribute("type", "audio");
521 trackinfo.setAttribute("mute", info.isMute);
522 trackinfo.setAttribute("blind", info.isBlind);
523 trackinfo.setAttribute("locked", info.isLocked);
524 trackinfo.setAttribute("trackname", info.trackName);
525 tracksinfo.appendChild(trackinfo);
527 addedXml.appendChild(tracksinfo);
529 // save project folders
530 QMap <QString, QString> folderlist = m_clipManager->documentFolderList();
532 QMapIterator<QString, QString> f(folderlist);
533 while (f.hasNext()) {
535 QDomElement folder = sceneList.createElement("folder");
536 folder.setAttribute("id", f.key());
537 folder.setAttribute("name", f.value());
538 addedXml.appendChild(folder);
541 // Save project clips
543 QList <DocClipBase*> list = m_clipManager->documentClipList();
544 for (int i = 0; i < list.count(); i++) {
545 e = list.at(i)->toXML();
546 e.setTagName("kdenlive_producer");
547 addedXml.appendChild(sceneList.importNode(e, true));
548 QList < CommentedTime > marks = list.at(i)->commentedSnapMarkers();
549 for (int j = 0; j < marks.count(); j++) {
550 QDomElement marker = sceneList.createElement("marker");
551 marker.setAttribute("time", marks.at(j).time().ms() / 1000);
552 marker.setAttribute("comment", marks.at(j).comment());
553 marker.setAttribute("id", e.attribute("id"));
554 markers.appendChild(marker);
557 addedXml.appendChild(markers);
560 if (!m_guidesXml.isNull()) addedXml.appendChild(sceneList.importNode(m_guidesXml.documentElement(), true));
563 addedXml.appendChild(sceneList.importNode(m_clipManager->groupsXml(), true));
565 //wes.appendChild(doc.importNode(kdenliveData, true));
568 if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
569 kWarning() << "////// ERROR writing to file: " << path;
570 KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1", path));
574 file.write(sceneList.toString().toUtf8());
575 if (file.error() != QFile::NoError) {
576 KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1", path));
584 ClipManager *KdenliveDoc::clipManager()
586 return m_clipManager;
589 KUrl KdenliveDoc::projectFolder() const
591 //if (m_projectFolder.isEmpty()) return KUrl(KStandardDirs::locateLocal("appdata", "/projects/"));
592 return m_projectFolder;
595 void KdenliveDoc::setProjectFolder(KUrl url)
597 if (url == m_projectFolder) return;
599 KStandardDirs::makeDir(url.path());
600 KStandardDirs::makeDir(url.path(KUrl::AddTrailingSlash) + "titles/");
601 KStandardDirs::makeDir(url.path(KUrl::AddTrailingSlash) + "thumbs/");
602 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);
603 m_projectFolder = url;
606 void KdenliveDoc::moveProjectData(KUrl url)
608 QList <DocClipBase*> list = m_clipManager->documentClipList();
609 //TODO: Also move ladspa effects files
610 for (int i = 0; i < list.count(); i++) {
611 DocClipBase *clip = list.at(i);
612 if (clip->clipType() == TEXT) {
613 // the image for title clip must be moved
614 KUrl oldUrl = clip->fileURL();
615 KUrl newUrl = KUrl(url.path(KUrl::AddTrailingSlash) + "titles/" + oldUrl.fileName());
616 KIO::Job *job = KIO::copy(oldUrl, newUrl);
617 if (KIO::NetAccess::synchronousRun(job, 0)) clip->setProperty("resource", newUrl.path());
619 QString hash = clip->getClipHash();
620 KUrl oldVideoThumbUrl = KUrl(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".png");
621 KUrl oldAudioThumbUrl = KUrl(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".thumb");
622 if (KIO::NetAccess::exists(oldVideoThumbUrl, KIO::NetAccess::SourceSide, 0)) {
623 KUrl newUrl = KUrl(url.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".png");
624 KIO::Job *job = KIO::copy(oldVideoThumbUrl, newUrl);
625 KIO::NetAccess::synchronousRun(job, 0);
627 if (KIO::NetAccess::exists(oldAudioThumbUrl, KIO::NetAccess::SourceSide, 0)) {
628 KUrl newUrl = KUrl(url.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".thumb");
629 KIO::Job *job = KIO::copy(oldAudioThumbUrl, newUrl);
630 if (KIO::NetAccess::synchronousRun(job, 0)) clip->refreshThumbUrl();
635 const QString &KdenliveDoc::profilePath() const
637 return m_profile.path;
640 MltVideoProfile KdenliveDoc::mltProfile() const
645 bool KdenliveDoc::setProfilePath(QString path)
647 if (path.isEmpty()) path = KdenliveSettings::default_profile();
648 if (path.isEmpty()) path = "dv_pal";
649 m_profile = ProfilesDialog::getVideoProfile(path);
650 bool current_fps = m_fps;
651 if (m_profile.path.isEmpty()) {
652 // Profile not found, use embedded profile
653 QDomElement profileInfo = m_document.elementsByTagName("profileinfo").at(0).toElement();
654 if (profileInfo.isNull()) {
655 KMessageBox::information(kapp->activeWindow(), i18n("Project profile was not found, using default profile."), i18n("Missing Profile"));
656 m_profile = ProfilesDialog::getVideoProfile(KdenliveSettings::default_profile());
658 m_profile.description = profileInfo.attribute("description");
659 m_profile.frame_rate_num = profileInfo.attribute("frame_rate_num").toInt();
660 m_profile.frame_rate_den = profileInfo.attribute("frame_rate_den").toInt();
661 m_profile.width = profileInfo.attribute("width").toInt();
662 m_profile.height = profileInfo.attribute("height").toInt();
663 m_profile.progressive = profileInfo.attribute("progressive").toInt();
664 m_profile.sample_aspect_num = profileInfo.attribute("sample_aspect_num").toInt();
665 m_profile.sample_aspect_den = profileInfo.attribute("sample_aspect_den").toInt();
666 m_profile.display_aspect_num = profileInfo.attribute("display_aspect_num").toInt();
667 m_profile.display_aspect_den = profileInfo.attribute("display_aspect_den").toInt();
668 QString existing = ProfilesDialog::existingProfile(m_profile);
669 if (!existing.isEmpty()) {
670 m_profile = ProfilesDialog::getVideoProfile(existing);
671 KMessageBox::information(kapp->activeWindow(), i18n("Project profile not found, replacing with existing one: %1", m_profile.description), i18n("Missing Profile"));
673 QString newDesc = m_profile.description;
675 while (ok && (newDesc.isEmpty() || ProfilesDialog::existingProfileDescription(newDesc))) {
676 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);
679 // User canceled, use default profile
680 m_profile = ProfilesDialog::getVideoProfile(KdenliveSettings::default_profile());
682 if (newDesc != m_profile.description) {
683 // Profile description existed, was replaced by new one
684 m_profile.description = newDesc;
686 KMessageBox::information(kapp->activeWindow(), i18n("Project profile was not found, it will be added to your system now."), i18n("Missing Profile"));
688 ProfilesDialog::saveProfile(m_profile);
695 KdenliveSettings::setProject_display_ratio((double) m_profile.display_aspect_num / m_profile.display_aspect_den);
696 m_fps = (double) m_profile.frame_rate_num / m_profile.frame_rate_den;
697 KdenliveSettings::setProject_fps(m_fps);
698 m_width = m_profile.width;
699 m_height = m_profile.height;
700 kDebug() << "Kdenlive document, init timecode from path: " << path << ", " << m_fps;
701 if (m_fps == 30000.0 / 1001.0) m_timecode.setFormat(m_fps, true);
702 else m_timecode.setFormat(m_fps);
703 return (current_fps != m_fps);
706 double KdenliveDoc::dar()
708 return (double) m_profile.display_aspect_num / m_profile.display_aspect_den;
711 void KdenliveDoc::setThumbsProgress(const QString &message, int progress)
713 emit progressInfo(message, progress);
716 QUndoStack *KdenliveDoc::commandStack()
718 return m_commandStack;
722 void KdenliveDoc::setRenderer(Render *render) {
723 if (m_render) return;
725 emit progressInfo(i18n("Loading playlist..."), 0);
726 //qApp->processEvents();
728 m_render->setSceneList(m_document.toString(), m_startPos);
729 kDebug() << "// SETTING SCENE LIST:\n\n" << m_document.toString();
732 emit progressInfo(QString(), -1);
735 void KdenliveDoc::checkProjectClips()
737 kDebug() << "+++++++++++++ + + + + CHK PCLIPS";
738 if (m_render == NULL) return;
739 m_clipManager->resetProducersList(m_render->producersList());
742 void KdenliveDoc::updatePreviewSettings()
744 m_clipManager->updatePreviewSettings();
745 m_render->updatePreviewSettings();
746 QList <Mlt::Producer *> prods = m_render->producersList();
747 m_clipManager->resetProducersList(m_render->producersList());
752 Render *KdenliveDoc::renderer()
757 void KdenliveDoc::updateClip(const QString id)
759 emit updateClipDisplay(id);
762 int KdenliveDoc::getFramePos(QString duration)
764 return m_timecode.getFrameCount(duration);
767 QString KdenliveDoc::producerName(const QString &id)
769 QString result = "unnamed";
770 QDomNodeList prods = producersList();
771 int ct = prods.count();
772 for (int i = 0; i < ct ; i++) {
773 QDomElement e = prods.item(i).toElement();
774 if (e.attribute("id") != "black" && e.attribute("id") == id) {
775 result = e.attribute("name");
776 if (result.isEmpty()) result = KUrl(e.attribute("resource")).fileName();
783 QDomDocument KdenliveDoc::toXml()
788 Timecode KdenliveDoc::timecode() const
793 QDomNodeList KdenliveDoc::producersList()
795 return m_document.elementsByTagName("producer");
798 double KdenliveDoc::projectDuration() const
801 return GenTime(m_render->getLength(), m_fps).ms() / 1000;
806 double KdenliveDoc::fps() const
811 int KdenliveDoc::width() const
816 int KdenliveDoc::height() const
821 KUrl KdenliveDoc::url() const
826 void KdenliveDoc::setUrl(KUrl url)
831 void KdenliveDoc::setModified(bool mod)
833 if (!m_url.isEmpty() && mod && KdenliveSettings::crashrecovery()) {
834 m_autoSaveTimer->start(3000);
836 if (mod == m_modified) return;
838 emit docModified(m_modified);
841 bool KdenliveDoc::isModified() const
846 const QString KdenliveDoc::description() const
849 return i18n("Untitled") + " / " + m_profile.description;
851 return m_url.fileName() + " / " + m_profile.description;
854 void KdenliveDoc::addClip(QDomElement elem, QString clipId, bool createClipItem)
856 const QString producerId = clipId.section('_', 0, 0);
857 DocClipBase *clip = m_clipManager->getClipById(producerId);
860 elem.setAttribute("id", producerId);
861 QString path = elem.attribute("resource");
863 if (elem.attribute("type").toInt() == SLIDESHOW) {
864 extension = KUrl(path).fileName();
865 path = KUrl(path).directory();
868 if (path.isEmpty() == false && QFile::exists(path) == false && elem.attribute("type").toInt() != TEXT && !elem.hasAttribute("placeholder")) {
869 kDebug() << "// FOUND MISSING CLIP: " << path << ", TYPE: " << elem.attribute("type").toInt();
870 const QString size = elem.attribute("file_size");
871 const QString hash = elem.attribute("file_hash");
873 int action = KMessageBox::No;
874 if (!size.isEmpty() && !hash.isEmpty()) {
875 if (!m_searchFolder.isEmpty()) newpath = searchFileRecursively(m_searchFolder, size, hash);
876 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")));
878 if (elem.attribute("type").toInt() == SLIDESHOW) {
879 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")));
880 if (res == KMessageBox::Yes)
881 newpath = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow(), i18n("Looking for %1", path));
883 // Abort project loading
887 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")));
888 if (res == KMessageBox::Yes)
889 newpath = KFileDialog::getOpenFileName(KUrl("kfiledialog:///clipfolder"), QString(), kapp->activeWindow(), i18n("Looking for %1", path));
891 // Abort project loading
896 if (action == KMessageBox::Yes) {
897 kDebug() << "// ASKED FOR SRCH CLIP: " << clipId;
898 m_searchFolder = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow());
899 if (!m_searchFolder.isEmpty()) {
900 newpath = searchFileRecursively(QDir(m_searchFolder), size, hash);
902 } else if (action == KMessageBox::Cancel) {
903 m_abortLoading = true;
905 } else if (action == KMessageBox::No) {
906 // Keep clip as placeHolder
907 elem.setAttribute("placeholder", '1');
909 if (!newpath.isEmpty()) {
910 if (elem.attribute("type").toInt() == SLIDESHOW) newpath.append('/' + extension);
911 elem.setAttribute("resource", newpath);
912 setNewClipResource(clipId, newpath);
916 clip = new DocClipBase(m_clipManager, elem, producerId);
917 m_clipManager->addClip(clip);
920 if (createClipItem) {
921 emit addProjectClip(clip);
922 //qApp->processEvents();
926 void KdenliveDoc::setNewClipResource(const QString &id, const QString &path)
928 QDomNodeList prods = m_document.elementsByTagName("producer");
929 int maxprod = prods.count();
930 for (int i = 0; i < maxprod; i++) {
931 QDomNode m = prods.at(i);
932 QString prodId = m.toElement().attribute("id");
933 if (prodId == id || prodId.startsWith(id + '_')) {
934 QDomNodeList params = m.childNodes();
935 for (int j = 0; j < params.count(); j++) {
936 QDomElement e = params.item(j).toElement();
937 if (e.attribute("name") == "resource") {
938 e.firstChild().setNodeValue(path);
946 QString KdenliveDoc::searchFileRecursively(const QDir &dir, const QString &matchSize, const QString &matchHash) const
948 QString foundFileName;
951 QStringList filesAndDirs = dir.entryList(QDir::Files | QDir::Readable);
952 for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
953 QFile file(dir.absoluteFilePath(filesAndDirs.at(i)));
954 if (file.open(QIODevice::ReadOnly)) {
955 if (QString::number(file.size()) == matchSize) {
957 * 1 MB = 1 second per 450 files (or faster)
958 * 10 MB = 9 seconds per 450 files (or faster)
960 if (file.size() > 1000000*2) {
961 fileData = file.read(1000000);
962 if (file.seek(file.size() - 1000000))
963 fileData.append(file.readAll());
965 fileData = file.readAll();
967 fileHash = QCryptographicHash::hash(fileData, QCryptographicHash::Md5);
968 if (QString(fileHash.toHex()) == matchHash)
969 return file.fileName();
972 kDebug() << filesAndDirs.at(i) << file.size() << fileHash.toHex();
974 filesAndDirs = dir.entryList(QDir::Dirs | QDir::Readable | QDir::Executable | QDir::NoDotAndDotDot);
975 for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
976 foundFileName = searchFileRecursively(dir.absoluteFilePath(filesAndDirs.at(i)), matchSize, matchHash);
977 if (!foundFileName.isEmpty())
980 return foundFileName;
983 void KdenliveDoc::addClipInfo(QDomElement elem, QDomElement orig, QString clipId)
985 DocClipBase *clip = m_clipManager->getClipById(clipId);
987 addClip(elem, clipId, false);
989 QMap <QString, QString> properties;
990 QDomNamedNodeMap attributes = elem.attributes();
992 for (int i = 0; i < attributes.count(); i++) {
993 attrname = attributes.item(i).nodeName();
994 if (attrname != "resource")
995 properties.insert(attrname, attributes.item(i).nodeValue());
996 kDebug() << attrname << " = " << attributes.item(i).nodeValue();
998 clip->setProperties(properties);
999 emit addProjectClip(clip, false);
1001 if (orig != QDomElement()) {
1002 QMap<QString, QString> meta;
1003 QDomNode m = orig.firstChild();
1004 while (!m.isNull()) {
1005 QString name = m.toElement().attribute("name");
1006 if (name.startsWith("meta.attr")) {
1007 meta.insert(name.section('.', 2, 3), m.firstChild().nodeValue());
1009 m = m.nextSibling();
1011 if (!meta.isEmpty()) {
1012 if (clip == NULL) clip = m_clipManager->getClipById(clipId);
1013 if (clip) clip->setMetadata(meta);
1018 void KdenliveDoc::deleteProjectClip(QStringList ids)
1020 for (int i = 0; i < ids.size(); ++i) {
1021 emit deleteTimelineClip(ids.at(i));
1023 m_clipManager->slotDeleteClips(ids);
1027 void KdenliveDoc::deleteClip(const QString &clipId)
1029 emit signalDeleteProjectClip(clipId);
1032 void KdenliveDoc::slotAddClipList(const KUrl::List urls, const QString group, const QString &groupId)
1034 m_clipManager->slotAddClipList(urls, group, groupId);
1035 //emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1040 void KdenliveDoc::slotAddClipFile(const KUrl url, const QString group, const QString &groupId)
1042 m_clipManager->slotAddClipFile(url, group, groupId);
1043 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1047 const QString KdenliveDoc::getFreeClipId()
1049 return QString::number(m_clipManager->getFreeClipId());
1052 DocClipBase *KdenliveDoc::getBaseClip(const QString &clipId)
1054 return m_clipManager->getClipById(clipId);
1057 void KdenliveDoc::slotCreateColorClip(const QString &name, const QString &color, const QString &duration, QString group, const QString &groupId)
1059 m_clipManager->slotAddColorClipFile(name, color, duration, group, groupId);
1061 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1064 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)
1066 m_clipManager->slotAddSlideshowClipFile(name, path, count, duration, loop, fade, luma_duration, luma_file, softness, group, groupId);
1068 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1071 void KdenliveDoc::slotCreateTextClip(QString group, const QString &groupId, const QString &templatePath)
1073 QString titlesFolder = projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
1074 KStandardDirs::makeDir(titlesFolder);
1075 TitleWidget *dia_ui = new TitleWidget(templatePath, m_timecode, titlesFolder, m_render, kapp->activeWindow());
1076 if (dia_ui->exec() == QDialog::Accepted) {
1077 m_clipManager->slotAddTextClipFile(i18n("Title clip"), dia_ui->duration(), dia_ui->xml().toString(), group, groupId);
1079 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1084 void KdenliveDoc::slotCreateTextTemplateClip(QString group, const QString &groupId, KUrl path)
1086 QString titlesFolder = projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
1087 if (path.isEmpty()) {
1088 path = KFileDialog::getOpenUrl(KUrl(titlesFolder), "*.kdenlivetitle", kapp->activeWindow(), i18n("Enter Template Path"));
1091 if (path.isEmpty()) return;
1093 //TODO: rewrite with new title system (just set resource)
1094 m_clipManager->slotAddTextTemplateClip(i18n("Template title clip"), path, group, groupId);
1096 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1099 int KdenliveDoc::tracksCount() const
1101 return m_tracksList.count();
1104 TrackInfo KdenliveDoc::trackInfoAt(int ix) const
1106 return m_tracksList.at(ix);
1109 void KdenliveDoc::switchTrackAudio(int ix, bool hide)
1111 m_tracksList[ix].isMute = hide; // !m_tracksList.at(ix).isMute;
1114 void KdenliveDoc::switchTrackLock(int ix, bool lock)
1116 m_tracksList[ix].isLocked = lock;
1119 bool KdenliveDoc::isTrackLocked(int ix) const
1121 return m_tracksList.at(ix).isLocked;
1124 void KdenliveDoc::switchTrackVideo(int ix, bool hide)
1126 m_tracksList[ix].isBlind = hide; // !m_tracksList.at(ix).isBlind;
1129 void KdenliveDoc::insertTrack(int ix, TrackInfo type)
1131 if (ix == -1) m_tracksList << type;
1132 else m_tracksList.insert(ix, type);
1135 void KdenliveDoc::deleteTrack(int ix)
1137 m_tracksList.removeAt(ix);
1140 void KdenliveDoc::setTrackType(int ix, TrackInfo type)
1142 m_tracksList[ix].type = type.type;
1143 m_tracksList[ix].isMute = type.isMute;
1144 m_tracksList[ix].isBlind = type.isBlind;
1145 m_tracksList[ix].isLocked = type.isLocked;
1146 m_tracksList[ix].trackName = type.trackName;
1149 const QList <TrackInfo> KdenliveDoc::tracksList() const
1151 return m_tracksList;
1154 QPoint KdenliveDoc::getTracksCount() const
1158 foreach(const TrackInfo &info, m_tracksList) {
1159 if (info.type == VIDEOTRACK) video++;
1162 return QPoint(video, audio);
1165 void KdenliveDoc::cachePixmap(const QString &fileId, const QPixmap &pix) const
1167 pix.save(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + fileId + ".png");
1170 QString KdenliveDoc::getLadspaFile() const
1173 QString counter = QString::number(ct).rightJustified(5, '0', false);
1174 while (QFile::exists(m_projectFolder.path(KUrl::AddTrailingSlash) + "ladspa/" + counter + ".ladspa")) {
1176 counter = QString::number(ct).rightJustified(5, '0', false);
1178 return m_projectFolder.path(KUrl::AddTrailingSlash) + "ladspa/" + counter + ".ladspa";
1181 bool KdenliveDoc::checkDocumentClips(QDomNodeList infoproducers)
1183 DocumentChecker d(infoproducers, m_document);
1184 return (d.hasMissingClips() == false);
1190 QList <QDomElement> missingClips;
1191 for (int i = 0; i < infoproducers.count(); i++) {
1192 e = infoproducers.item(i).toElement();
1193 clipType = e.attribute("type").toInt();
1194 if (clipType == COLOR) continue;
1195 if (clipType == TEXT) {
1196 //TODO: Check is clip template is missing (xmltemplate) or hash changed
1199 id = e.attribute("id");
1200 resource = e.attribute("resource");
1201 if (clipType == SLIDESHOW) resource = KUrl(resource).directory();
1202 if (!KIO::NetAccess::exists(KUrl(resource), KIO::NetAccess::SourceSide, 0)) {
1203 // Missing clip found
1204 missingClips.append(e);
1206 // Check if the clip has changed
1207 if (clipType != SLIDESHOW && e.hasAttribute("file_hash")) {
1208 if (e.attribute("file_hash") != DocClipBase::getHash(e.attribute("resource")))
1209 e.removeAttribute("file_hash");
1213 if (missingClips.isEmpty()) return true;
1214 DocumentChecker d(missingClips, m_document);
1215 return (d.exec() == QDialog::Accepted);*/
1218 void KdenliveDoc::setDocumentProperty(const QString &name, const QString &value)
1220 m_documentProperties[name] = value;
1223 const QString KdenliveDoc::getDocumentProperty(const QString &name) const
1225 return m_documentProperties.value(name);
1228 #include "kdenlivedoc.moc"