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) :
57 m_commandStack(new QUndoStack(undoGroup)),
59 m_projectFolder(projectFolder),
60 m_documentLoadingStep(0.0),
61 m_documentLoadingProgress(0),
62 m_abortLoading(false),
66 m_clipManager = new ClipManager(this);
67 m_autoSaveTimer = new QTimer(this);
68 m_autoSaveTimer->setSingleShot(true);
72 success = KIO::NetAccess::download(url.path(), tmpFile, parent);
73 if (!success) // The file cannot be opened
74 KMessageBox::error(parent, KIO::NetAccess::lastErrorString());
78 success = m_document.setContent(&file, false, &errorMsg);
80 KIO::NetAccess::removeTempFile(tmpFile);
81 if (!success) // It is corrupted
82 KMessageBox::error(parent, errorMsg);
84 DocumentValidator validator(m_document);
85 success = validator.isProject();
86 if (!success) // It is not a project file
87 parent->slotGotProgressInfo(i18n("File %1 is not a Kdenlive project file.", m_url.path()), 100);
90 * Validate the file against the current version (upgrade
91 * and recover it if needed). It is NOT a passive operation
93 // TODO: backup the document or alert the user?
94 success = validator.validate(DOCUMENTVERSION);
95 if (success) { // Let the validator handle error messages
96 setModified(validator.isModified());
97 QDomElement mlt = m_document.firstChildElement("mlt");
98 QDomElement infoXml = mlt.firstChildElement("kdenlivedoc");
100 profileName = infoXml.attribute("profile");
101 m_projectFolder = infoXml.attribute("projectfolder");
103 m_startPos = infoXml.attribute("position").toInt();
104 m_zoom = infoXml.attribute("zoom", "7").toInt();
105 m_zoneStart = infoXml.attribute("zonein", "0").toInt();
106 m_zoneEnd = infoXml.attribute("zoneout", "100").toInt();
110 QDomElement tracksinfo = infoXml.firstChildElement("tracksinfo");
111 TrackInfo projectTrack;
112 if (!tracksinfo.isNull()) {
113 QDomNodeList trackslist = tracksinfo.childNodes();
114 int maxchild = trackslist.count();
115 for (int k = 0; k < maxchild; k++) {
116 e = trackslist.at(k).toElement();
117 if (e.tagName() == "trackinfo") {
118 if (e.attribute("type") == "audio") projectTrack.type = AUDIOTRACK;
119 else projectTrack.type = VIDEOTRACK;
120 projectTrack.isMute = e.attribute("mute").toInt();
121 projectTrack.isBlind = e.attribute("blind").toInt();
122 projectTrack.isLocked = e.attribute("locked").toInt();
123 m_tracksList.append(projectTrack);
126 mlt.removeChild(tracksinfo);
128 QDomNodeList producers = m_document.elementsByTagName("producer");
129 QDomNodeList infoproducers = m_document.elementsByTagName("kdenlive_producer");
130 if (checkDocumentClips(infoproducers) == false) m_abortLoading = true;
131 const int max = producers.count();
132 const int infomax = infoproducers.count();
134 QDomNodeList folders = m_document.elementsByTagName("folder");
135 for (int i = 0; i < folders.count(); i++) {
136 e = folders.item(i).cloneNode().toElement();
137 m_clipManager->addFolder(e.attribute("id"), e.attribute("name"));
141 m_documentLoadingStep = 100.0 / (max + infomax + m_document.elementsByTagName("entry").count());
142 parent->slotGotProgressInfo(i18n("Loading project clips"), (int) m_documentLoadingProgress);
146 for (int i = 0; i < infomax && !m_abortLoading; i++) {
147 e = infoproducers.item(i).cloneNode().toElement();
148 if (m_documentLoadingStep > 0) {
149 m_documentLoadingProgress += m_documentLoadingStep;
150 parent->slotGotProgressInfo(QString(), (int) m_documentLoadingProgress);
151 //qApp->processEvents();
153 QString prodId = e.attribute("id");
154 if (!e.isNull() && prodId != "black" && !prodId.startsWith("slowmotion") && !m_abortLoading) {
155 e.setTagName("producer");
156 // Get MLT's original producer properties
158 for (int j = 0; j < max; j++) {
159 QDomElement o = producers.item(j).cloneNode().toElement();
160 QString origId = o.attribute("id").section('_', 0, 0);
161 if (origId == prodId) {
166 addClipInfo(e, orig, prodId);
167 kDebug() << "// KDENLIVE PRODUCER: " << prodId;
170 if (m_abortLoading) {
171 //parent->slotGotProgressInfo(i18n("File %1 is not a Kdenlive project file."), 100);
172 emit resetProjectList();
175 m_tracksList.clear();
176 kWarning() << "Aborted loading of: " << url.path();
177 m_document = createEmptyDocument(KdenliveSettings::videotracks(), KdenliveSettings::audiotracks());
178 setProfilePath(KdenliveSettings::default_profile());
179 m_clipManager->clear();
181 QDomElement markers = infoXml.firstChildElement("markers");
182 if (!markers.isNull()) {
183 QDomNodeList markerslist = markers.childNodes();
184 int maxchild = markerslist.count();
185 for (int k = 0; k < maxchild; k++) {
186 e = markerslist.at(k).toElement();
187 if (e.tagName() == "marker") {
188 m_clipManager->getClipById(e.attribute("id"))->addSnapMarker(GenTime(e.attribute("time").toDouble()), e.attribute("comment"));
191 infoXml.removeChild(markers);
193 setProfilePath(profileName);
194 kDebug() << "Reading file: " << url.path() << ", found clips: " << producers.count();
200 } else setProfilePath(profileName);
202 // Something went wrong, or a new file was requested: create a new project
205 m_document = createEmptyDocument(tracks.x(), tracks.y());
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() + "/titles/");
218 KStandardDirs::makeDir(m_projectFolder.path() + "/thumbs/");
219 KStandardDirs::makeDir(m_projectFolder.path() + "/ladspa/");
221 kDebug() << "Kdenlive document, init timecode: " << m_fps;
222 if (m_fps == 30000.0 / 1001.0) m_timecode.setFormat(30, true);
223 else m_timecode.setFormat((int) 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 delete m_commandStack;
232 delete m_clipManager;
233 delete m_autoSaveTimer;
235 if (!m_autosave->fileName().isEmpty()) m_autosave->remove();
240 void KdenliveDoc::setSceneList()
242 m_render->setSceneList(m_document.toString(), m_startPos);
243 // m_document xml is now useless, clear it
248 QDomDocument KdenliveDoc::createEmptyDocument(const int videotracks, const int audiotracks)
250 // Creating new document
252 QDomElement mlt = doc.createElement("mlt");
253 doc.appendChild(mlt);
256 TrackInfo videoTrack;
257 videoTrack.type = VIDEOTRACK;
258 videoTrack.isMute = false;
259 videoTrack.isBlind = false;
260 videoTrack.isLocked = false;
262 TrackInfo audioTrack;
263 audioTrack.type = AUDIOTRACK;
264 audioTrack.isMute = false;
265 audioTrack.isBlind = true;
266 audioTrack.isLocked = false;
268 QDomElement tractor = doc.createElement("tractor");
269 tractor.setAttribute("id", "maintractor");
270 QDomElement multitrack = doc.createElement("multitrack");
271 QDomElement playlist = doc.createElement("playlist");
272 playlist.setAttribute("id", "black_track");
273 mlt.appendChild(playlist);
277 int total = audiotracks + videotracks + 1;
279 for (int i = 1; i < total; i++) {
280 QDomElement playlist = doc.createElement("playlist");
281 playlist.setAttribute("id", "playlist" + QString::number(i));
282 mlt.appendChild(playlist);
285 QDomElement track0 = doc.createElement("track");
286 track0.setAttribute("producer", "black_track");
287 tractor.appendChild(track0);
289 // create audio tracks
290 for (int i = 1; i < audiotracks + 1; i++) {
291 QDomElement track = doc.createElement("track");
292 track.setAttribute("producer", "playlist" + QString::number(i));
293 track.setAttribute("hide", "video");
294 tractor.appendChild(track);
295 m_tracksList.append(audioTrack);
298 // create video tracks
299 for (int i = audiotracks + 1; i < total; i++) {
300 QDomElement track = doc.createElement("track");
301 track.setAttribute("producer", "playlist" + QString::number(i));
302 tractor.appendChild(track);
303 m_tracksList.append(videoTrack);
306 for (int i = 2; i < total ; i++) {
307 QDomElement transition = doc.createElement("transition");
308 transition.setAttribute("always_active", "1");
310 QDomElement property = doc.createElement("property");
311 property.setAttribute("name", "a_track");
312 QDomText value = doc.createTextNode(QString::number(1));
313 property.appendChild(value);
314 transition.appendChild(property);
316 property = doc.createElement("property");
317 property.setAttribute("name", "b_track");
318 value = doc.createTextNode(QString::number(i));
319 property.appendChild(value);
320 transition.appendChild(property);
322 property = doc.createElement("property");
323 property.setAttribute("name", "mlt_service");
324 value = doc.createTextNode("mix");
325 property.appendChild(value);
326 transition.appendChild(property);
328 property = doc.createElement("property");
329 property.setAttribute("name", "combine");
330 value = doc.createTextNode("1");
331 property.appendChild(value);
332 transition.appendChild(property);
334 property = doc.createElement("property");
335 property.setAttribute("name", "internal_added");
336 value = doc.createTextNode("237");
337 property.appendChild(value);
338 transition.appendChild(property);
339 tractor.appendChild(transition);
341 mlt.appendChild(tractor);
346 void KdenliveDoc::syncGuides(QList <Guide *> guides)
349 QDomElement guideNode = m_guidesXml.createElement("guides");
350 m_guidesXml.appendChild(guideNode);
353 for (int i = 0; i < guides.count(); i++) {
354 e = m_guidesXml.createElement("guide");
355 e.setAttribute("time", guides.at(i)->position().ms() / 1000);
356 e.setAttribute("comment", guides.at(i)->label());
357 guideNode.appendChild(e);
360 emit guidesUpdated();
363 QDomElement KdenliveDoc::guidesXml() const
365 return m_guidesXml.documentElement();
368 void KdenliveDoc::slotAutoSave()
370 if (m_render && m_autosave) {
371 if (!m_autosave->isOpen() && !m_autosave->open(QIODevice::ReadWrite)) {
372 // show error: could not open the autosave file
373 kDebug() << "ERROR; CANNOT CREATE AUTOSAVE FILE";
375 kDebug() << "// AUTOSAVE FILE: " << m_autosave->fileName();
377 if (KdenliveSettings::dropbframes()) {
378 KdenliveSettings::setDropbframes(false);
379 m_clipManager->updatePreviewSettings();
380 doc = m_render->sceneList();
381 KdenliveSettings::setDropbframes(true);
382 m_clipManager->updatePreviewSettings();
383 } else doc = m_render->sceneList();
384 saveSceneList(m_autosave->fileName(), doc);
388 void KdenliveDoc::setZoom(int factor)
393 int KdenliveDoc::zoom() const
398 void KdenliveDoc::setZone(int start, int end)
404 QPoint KdenliveDoc::zone() const
406 return QPoint(m_zoneStart, m_zoneEnd);
409 bool KdenliveDoc::saveSceneList(const QString &path, const QString &scene)
411 QDomDocument sceneList;
412 sceneList.setContent(scene, true);
413 QDomElement mlt = sceneList.firstChildElement("mlt");
414 QDomElement addedXml = sceneList.createElement("kdenlivedoc");
415 mlt.appendChild(addedXml);
417 QDomElement markers = sceneList.createElement("markers");
418 addedXml.setAttribute("version", DOCUMENTVERSION);
419 addedXml.setAttribute("kdenliveversion", VERSION);
420 addedXml.setAttribute("profile", profilePath());
421 addedXml.setAttribute("position", m_render->seekPosition().frames(m_fps));
422 addedXml.setAttribute("zonein", m_zoneStart);
423 addedXml.setAttribute("zoneout", m_zoneEnd);
424 addedXml.setAttribute("projectfolder", m_projectFolder.path());
425 addedXml.setAttribute("zoom", m_zoom);
428 QDomElement profileinfo = sceneList.createElement("profileinfo");
429 profileinfo.setAttribute("description", m_profile.description);
430 profileinfo.setAttribute("frame_rate_num", m_profile.frame_rate_num);
431 profileinfo.setAttribute("frame_rate_den", m_profile.frame_rate_den);
432 profileinfo.setAttribute("width", m_profile.width);
433 profileinfo.setAttribute("height", m_profile.height);
434 profileinfo.setAttribute("progressive", m_profile.progressive);
435 profileinfo.setAttribute("sample_aspect_num", m_profile.sample_aspect_num);
436 profileinfo.setAttribute("sample_aspect_den", m_profile.sample_aspect_den);
437 profileinfo.setAttribute("display_aspect_num", m_profile.display_aspect_num);
438 profileinfo.setAttribute("display_aspect_den", m_profile.display_aspect_den);
439 addedXml.appendChild(profileinfo);
442 QDomElement tracksinfo = sceneList.createElement("tracksinfo");
443 foreach(const TrackInfo &info, m_tracksList) {
444 QDomElement trackinfo = sceneList.createElement("trackinfo");
445 if (info.type == AUDIOTRACK) trackinfo.setAttribute("type", "audio");
446 trackinfo.setAttribute("mute", info.isMute);
447 trackinfo.setAttribute("blind", info.isBlind);
448 trackinfo.setAttribute("locked", info.isLocked);
449 tracksinfo.appendChild(trackinfo);
451 addedXml.appendChild(tracksinfo);
453 // save project folders
454 QMap <QString, QString> folderlist = m_clipManager->documentFolderList();
456 QMapIterator<QString, QString> f(folderlist);
457 while (f.hasNext()) {
459 QDomElement folder = sceneList.createElement("folder");
460 folder.setAttribute("id", f.key());
461 folder.setAttribute("name", f.value());
462 addedXml.appendChild(folder);
465 // Save project clips
467 QList <DocClipBase*> list = m_clipManager->documentClipList();
468 for (int i = 0; i < list.count(); i++) {
469 e = list.at(i)->toXML();
470 e.setTagName("kdenlive_producer");
471 addedXml.appendChild(sceneList.importNode(e, true));
472 QList < CommentedTime > marks = list.at(i)->commentedSnapMarkers();
473 for (int j = 0; j < marks.count(); j++) {
474 QDomElement marker = sceneList.createElement("marker");
475 marker.setAttribute("time", marks.at(j).time().ms() / 1000);
476 marker.setAttribute("comment", marks.at(j).comment());
477 marker.setAttribute("id", e.attribute("id"));
478 markers.appendChild(marker);
481 addedXml.appendChild(markers);
484 if (!m_guidesXml.isNull()) addedXml.appendChild(sceneList.importNode(m_guidesXml.documentElement(), true));
487 addedXml.appendChild(sceneList.importNode(m_clipManager->groupsXml(), true));
489 //wes.appendChild(doc.importNode(kdenliveData, true));
492 if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
493 kWarning() << "////// ERROR writing to file: " << path;
494 KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1", path));
498 file.write(sceneList.toString().toUtf8());
499 if (file.error() != QFile::NoError) {
500 KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1", path));
508 ClipManager *KdenliveDoc::clipManager()
510 return m_clipManager;
513 KUrl KdenliveDoc::projectFolder() const
515 //if (m_projectFolder.isEmpty()) return KUrl(KStandardDirs::locateLocal("appdata", "/projects/"));
516 return m_projectFolder;
519 void KdenliveDoc::setProjectFolder(KUrl url)
521 if (url == m_projectFolder) return;
523 KStandardDirs::makeDir(url.path());
524 KStandardDirs::makeDir(url.path() + "/titles/");
525 KStandardDirs::makeDir(url.path() + "/thumbs/");
526 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);
527 m_projectFolder = url;
530 void KdenliveDoc::moveProjectData(KUrl url)
532 QList <DocClipBase*> list = m_clipManager->documentClipList();
533 //TODO: Also move ladspa effects files
534 for (int i = 0; i < list.count(); i++) {
535 DocClipBase *clip = list.at(i);
536 if (clip->clipType() == TEXT) {
537 // the image for title clip must be moved
538 KUrl oldUrl = clip->fileURL();
539 KUrl newUrl = KUrl(url.path() + "/titles/" + oldUrl.fileName());
540 KIO::Job *job = KIO::copy(oldUrl, newUrl);
541 if (KIO::NetAccess::synchronousRun(job, 0)) clip->setProperty("resource", newUrl.path());
543 QString hash = clip->getClipHash();
544 KUrl oldVideoThumbUrl = KUrl(m_projectFolder.path() + "/thumbs/" + hash + ".png");
545 KUrl oldAudioThumbUrl = KUrl(m_projectFolder.path() + "/thumbs/" + hash + ".thumb");
546 if (KIO::NetAccess::exists(oldVideoThumbUrl, KIO::NetAccess::SourceSide, 0)) {
547 KUrl newUrl = KUrl(url.path() + "/thumbs/" + hash + ".png");
548 KIO::Job *job = KIO::copy(oldVideoThumbUrl, newUrl);
549 KIO::NetAccess::synchronousRun(job, 0);
551 if (KIO::NetAccess::exists(oldAudioThumbUrl, KIO::NetAccess::SourceSide, 0)) {
552 KUrl newUrl = KUrl(url.path() + "/thumbs/" + hash + ".thumb");
553 KIO::Job *job = KIO::copy(oldAudioThumbUrl, newUrl);
554 if (KIO::NetAccess::synchronousRun(job, 0)) clip->refreshThumbUrl();
559 const QString &KdenliveDoc::profilePath() const
561 return m_profile.path;
564 MltVideoProfile KdenliveDoc::mltProfile() const
569 void KdenliveDoc::setProfilePath(QString path)
571 if (path.isEmpty()) path = KdenliveSettings::default_profile();
572 if (path.isEmpty()) path = "dv_pal";
573 m_profile = ProfilesDialog::getVideoProfile(path);
574 if (m_profile.path.isEmpty()) {
575 // Profile not found, use embedded profile
576 QDomElement profileInfo = m_document.elementsByTagName("profileinfo").at(0).toElement();
577 if (profileInfo.isNull()) {
578 KMessageBox::information(kapp->activeWindow(), i18n("Project profile was not found, using default profile."), i18n("Missing Profile"));
579 m_profile = ProfilesDialog::getVideoProfile(KdenliveSettings::default_profile());
581 m_profile.description = profileInfo.attribute("description");
582 m_profile.frame_rate_num = profileInfo.attribute("frame_rate_num").toInt();
583 m_profile.frame_rate_den = profileInfo.attribute("frame_rate_den").toInt();
584 m_profile.width = profileInfo.attribute("width").toInt();
585 m_profile.height = profileInfo.attribute("height").toInt();
586 m_profile.progressive = profileInfo.attribute("progressive").toInt();
587 m_profile.sample_aspect_num = profileInfo.attribute("sample_aspect_num").toInt();
588 m_profile.sample_aspect_den = profileInfo.attribute("sample_aspect_den").toInt();
589 m_profile.display_aspect_num = profileInfo.attribute("display_aspect_num").toInt();
590 m_profile.display_aspect_den = profileInfo.attribute("display_aspect_den").toInt();
591 QString existing = ProfilesDialog::existingProfile(m_profile);
592 if (!existing.isEmpty()) {
593 m_profile = ProfilesDialog::getVideoProfile(existing);
594 KMessageBox::information(kapp->activeWindow(), i18n("Project profile not found, replacing with existing one: %1", m_profile.description), i18n("Missing Profile"));
596 QString newDesc = m_profile.description;
598 while (ok && (newDesc.isEmpty() || ProfilesDialog::existingProfileDescription(newDesc))) {
599 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);
602 // User canceled, use default profile
603 m_profile = ProfilesDialog::getVideoProfile(KdenliveSettings::default_profile());
605 if (newDesc != m_profile.description) {
606 // Profile description existed, was replaced by new one
607 m_profile.description = newDesc;
609 KMessageBox::information(kapp->activeWindow(), i18n("Project profile was not found, it will be added to your system now."), i18n("Missing Profile"));
611 ProfilesDialog::saveProfile(m_profile);
618 KdenliveSettings::setProject_display_ratio((double) m_profile.display_aspect_num / m_profile.display_aspect_den);
619 m_fps = (double) m_profile.frame_rate_num / m_profile.frame_rate_den;
620 KdenliveSettings::setProject_fps(m_fps);
621 m_width = m_profile.width;
622 m_height = m_profile.height;
623 kDebug() << "Kdenlive document, init timecode from path: " << path << ", " << m_fps;
624 if (m_fps == 30000.0 / 1001.0) m_timecode.setFormat(30, true);
625 else m_timecode.setFormat((int) m_fps);
628 double KdenliveDoc::dar()
630 return (double) m_profile.display_aspect_num / m_profile.display_aspect_den;
633 void KdenliveDoc::setThumbsProgress(const QString &message, int progress)
635 emit progressInfo(message, progress);
638 void KdenliveDoc::loadingProgressed()
640 m_documentLoadingProgress += m_documentLoadingStep;
641 emit progressInfo(QString(), (int) m_documentLoadingProgress);
644 QUndoStack *KdenliveDoc::commandStack()
646 return m_commandStack;
650 void KdenliveDoc::setRenderer(Render *render) {
651 if (m_render) return;
653 emit progressInfo(i18n("Loading playlist..."), 0);
654 //qApp->processEvents();
656 m_render->setSceneList(m_document.toString(), m_startPos);
657 kDebug() << "// SETTING SCENE LIST:\n\n" << m_document.toString();
660 emit progressInfo(QString(), -1);
663 void KdenliveDoc::checkProjectClips()
665 kDebug() << "+++++++++++++ + + + + CHK PCLIPS";
666 if (m_render == NULL) return;
667 m_clipManager->resetProducersList(m_render->producersList());
671 QList <Mlt::Producer *> prods = m_render->producersList();
675 for (int i = 0; i < prods.count(); i++) {
676 id = prods.at(i)->get("id");
677 prodId = id.section('_', 0, 0);
678 prodTrack = id.section('_', 1, 1);
679 DocClipBase *clip = m_clipManager->getClipById(prodId);
680 if (clip) clip->setProducer(prods.at(i));
681 if (clip && clip->clipType() == TEXT && !QFile::exists(clip->fileURL().path())) {
682 // regenerate text clip image if required
683 //kDebug() << "// TITLE: " << clip->getProperty("titlename") << " Preview file: " << clip->getProperty("resource") << " DOES NOT EXIST";
684 QString titlename = clip->getProperty("name");
685 QString titleresource;
686 if (titlename.isEmpty()) {
687 QStringList titleInfo = TitleWidget::getFreeTitleInfo(projectFolder());
688 titlename = titleInfo.at(0);
689 titleresource = titleInfo.at(1);
690 clip->setProperty("name", titlename);
691 kDebug() << "// New title set to: " << titlename;
693 titleresource = TitleWidget::getFreeTitleInfo(projectFolder()).at(1);
694 //titleresource = TitleWidget::getTitleResourceFromName(projectFolder(), titlename);
696 TitleWidget *dia_ui = new TitleWidget(KUrl(), KUrl(titleresource).directory(), m_render, kapp->activeWindow());
698 doc.setContent(clip->getProperty("xmldata"));
700 QImage pix = dia_ui->renderedPixmap();
701 pix.save(titleresource);
702 clip->setProperty("resource", titleresource);
704 clip->producer()->set("force_reload", 1);
709 void KdenliveDoc::updatePreviewSettings()
711 m_clipManager->updatePreviewSettings();
712 m_render->updatePreviewSettings();
713 m_clipManager->resetProducersList(m_render->producersList());
717 Render *KdenliveDoc::renderer()
722 void KdenliveDoc::updateClip(const QString &id)
724 emit updateClipDisplay(id);
727 int KdenliveDoc::getFramePos(QString duration)
729 return m_timecode.getFrameCount(duration, m_fps);
732 QString KdenliveDoc::producerName(const QString &id)
734 QString result = "unnamed";
735 QDomNodeList prods = producersList();
736 int ct = prods.count();
737 for (int i = 0; i < ct ; i++) {
738 QDomElement e = prods.item(i).toElement();
739 if (e.attribute("id") != "black" && e.attribute("id") == id) {
740 result = e.attribute("name");
741 if (result.isEmpty()) result = KUrl(e.attribute("resource")).fileName();
748 QDomDocument KdenliveDoc::toXml()
753 Timecode KdenliveDoc::timecode() const
758 QDomNodeList KdenliveDoc::producersList()
760 return m_document.elementsByTagName("producer");
763 double KdenliveDoc::projectDuration() const
766 return GenTime(m_render->getLength(), m_fps).ms() / 1000;
771 double KdenliveDoc::fps() const
776 int KdenliveDoc::width() const
781 int KdenliveDoc::height() const
786 KUrl KdenliveDoc::url() const
791 void KdenliveDoc::setUrl(KUrl url)
796 void KdenliveDoc::setModified(bool mod)
798 if (!m_url.isEmpty() && mod && KdenliveSettings::crashrecovery()) {
799 m_autoSaveTimer->start(3000);
801 if (mod == m_modified) return;
803 emit docModified(m_modified);
806 bool KdenliveDoc::isModified() const
811 const QString KdenliveDoc::description() const
814 return i18n("Untitled") + " / " + m_profile.description;
816 return m_url.fileName() + " / " + m_profile.description;
819 void KdenliveDoc::addClip(QDomElement elem, QString clipId, bool createClipItem)
821 const QString producerId = clipId.section('_', 0, 0);
822 DocClipBase *clip = m_clipManager->getClipById(producerId);
825 elem.setAttribute("id", producerId);
826 QString path = elem.attribute("resource");
828 if (elem.attribute("type").toInt() == SLIDESHOW) {
829 extension = KUrl(path).fileName();
830 path = KUrl(path).directory();
831 } else if (elem.attribute("type").toInt() == TEXT && QFile::exists(path) == false) {
832 kDebug() << "// TITLE: " << elem.attribute("name") << " Preview file: " << elem.attribute("resource") << " DOES NOT EXIST";
833 QString titlename = elem.attribute("name");
834 QString titleresource;
835 if (titlename.isEmpty()) {
836 QStringList titleInfo = TitleWidget::getFreeTitleInfo(projectFolder());
837 titlename = titleInfo.at(0);
838 titleresource = titleInfo.at(1);
839 elem.setAttribute("name", titlename);
840 kDebug() << "// New title set to: " << titlename;
842 titleresource = TitleWidget::getFreeTitleInfo(projectFolder()).at(1);
843 //titleresource = TitleWidget::getTitleResourceFromName(projectFolder(), titlename);
845 TitleWidget *dia_ui = new TitleWidget(KUrl(), KUrl(titleresource).directory(), m_render, kapp->activeWindow());
847 doc.setContent(elem.attribute("xmldata"));
849 QImage pix = dia_ui->renderedPixmap();
850 pix.save(titleresource);
851 elem.setAttribute("resource", titleresource);
852 setNewClipResource(clipId, titleresource);
856 if (path.isEmpty() == false && QFile::exists(path) == false && elem.attribute("type").toInt() != TEXT && !elem.hasAttribute("placeholder")) {
857 kDebug() << "// FOUND MISSING CLIP: " << path << ", TYPE: " << elem.attribute("type").toInt();
858 const QString size = elem.attribute("file_size");
859 const QString hash = elem.attribute("file_hash");
861 int action = KMessageBox::No;
862 if (!size.isEmpty() && !hash.isEmpty()) {
863 if (!m_searchFolder.isEmpty()) newpath = searchFileRecursively(m_searchFolder, size, hash);
864 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")));
866 if (elem.attribute("type").toInt() == SLIDESHOW) {
867 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")));
868 if (res == KMessageBox::Yes)
869 newpath = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow(), i18n("Looking for %1", path));
871 // Abort project loading
875 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")));
876 if (res == KMessageBox::Yes)
877 newpath = KFileDialog::getOpenFileName(KUrl("kfiledialog:///clipfolder"), QString(), kapp->activeWindow(), i18n("Looking for %1", path));
879 // Abort project loading
884 if (action == KMessageBox::Yes) {
885 kDebug() << "// ASKED FOR SRCH CLIP: " << clipId;
886 m_searchFolder = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow());
887 if (!m_searchFolder.isEmpty()) {
888 newpath = searchFileRecursively(QDir(m_searchFolder), size, hash);
890 } else if (action == KMessageBox::Cancel) {
891 m_abortLoading = true;
893 } else if (action == KMessageBox::No) {
894 // Keep clip as placeHolder
895 elem.setAttribute("placeholder", '1');
897 if (!newpath.isEmpty()) {
898 if (elem.attribute("type").toInt() == SLIDESHOW) newpath.append('/' + extension);
899 elem.setAttribute("resource", newpath);
900 setNewClipResource(clipId, newpath);
904 clip = new DocClipBase(m_clipManager, elem, producerId);
905 m_clipManager->addClip(clip);
908 if (createClipItem) {
909 emit addProjectClip(clip);
910 qApp->processEvents();
911 m_render->getFileProperties(clip->toXML(), clip->getId());
916 void KdenliveDoc::setNewClipResource(const QString &id, const QString &path)
918 QDomNodeList prods = m_document.elementsByTagName("producer");
919 int maxprod = prods.count();
920 for (int i = 0; i < maxprod; i++) {
921 QDomNode m = prods.at(i);
922 QString prodId = m.toElement().attribute("id");
923 if (prodId == id || prodId.startsWith(id + '_')) {
924 QDomNodeList params = m.childNodes();
925 for (int j = 0; j < params.count(); j++) {
926 QDomElement e = params.item(j).toElement();
927 if (e.attribute("name") == "resource") {
928 e.firstChild().setNodeValue(path);
936 QString KdenliveDoc::searchFileRecursively(const QDir &dir, const QString &matchSize, const QString &matchHash) const
938 QString foundFileName;
941 QStringList filesAndDirs = dir.entryList(QDir::Files | QDir::Readable);
942 for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
943 QFile file(dir.absoluteFilePath(filesAndDirs.at(i)));
944 if (file.open(QIODevice::ReadOnly)) {
945 if (QString::number(file.size()) == matchSize) {
947 * 1 MB = 1 second per 450 files (or faster)
948 * 10 MB = 9 seconds per 450 files (or faster)
950 if (file.size() > 1000000*2) {
951 fileData = file.read(1000000);
952 if (file.seek(file.size() - 1000000))
953 fileData.append(file.readAll());
955 fileData = file.readAll();
957 fileHash = QCryptographicHash::hash(fileData, QCryptographicHash::Md5);
958 if (QString(fileHash.toHex()) == matchHash)
959 return file.fileName();
962 kDebug() << filesAndDirs.at(i) << file.size() << fileHash.toHex();
964 filesAndDirs = dir.entryList(QDir::Dirs | QDir::Readable | QDir::Executable | QDir::NoDotAndDotDot);
965 for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
966 foundFileName = searchFileRecursively(dir.absoluteFilePath(filesAndDirs.at(i)), matchSize, matchHash);
967 if (!foundFileName.isEmpty())
970 return foundFileName;
973 void KdenliveDoc::addClipInfo(QDomElement elem, QDomElement orig, QString clipId)
975 DocClipBase *clip = m_clipManager->getClipById(clipId);
977 addClip(elem, clipId, false);
979 QMap <QString, QString> properties;
980 QDomNamedNodeMap attributes = elem.attributes();
982 for (int i = 0; i < attributes.count(); i++) {
983 attrname = attributes.item(i).nodeName();
984 if (attrname != "resource")
985 properties.insert(attrname, attributes.item(i).nodeValue());
986 kDebug() << attrname << " = " << attributes.item(i).nodeValue();
988 clip->setProperties(properties);
989 emit addProjectClip(clip, false);
991 if (orig != QDomElement()) {
992 QMap<QString, QString> meta;
993 QDomNode m = orig.firstChild();
994 while (!m.isNull()) {
995 QString name = m.toElement().attribute("name");
996 if (name.startsWith("meta.attr")) {
997 meta.insert(name.section('.', 2, 3), m.firstChild().nodeValue());
1001 if (!meta.isEmpty()) {
1002 if (clip == NULL) clip = m_clipManager->getClipById(clipId);
1003 if (clip) clip->setMetadata(meta);
1008 void KdenliveDoc::deleteProjectClip(QList <QString> ids)
1010 for (int i = 0; i < ids.size(); ++i) {
1011 emit deleteTimelineClip(ids.at(i));
1012 m_clipManager->slotDeleteClip(ids.at(i));
1017 void KdenliveDoc::deleteClip(const QString &clipId)
1019 emit signalDeleteProjectClip(clipId);
1020 m_clipManager->deleteClip(clipId);
1023 void KdenliveDoc::slotAddClipList(const KUrl::List urls, const QString group, const QString &groupId)
1025 m_clipManager->slotAddClipList(urls, group, groupId);
1026 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1031 void KdenliveDoc::slotAddClipFile(const KUrl url, const QString group, const QString &groupId)
1033 //kDebug() << "///////// DOCUM, ADD CLP: " << url;
1034 m_clipManager->slotAddClipFile(url, group, groupId);
1035 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1039 const QString KdenliveDoc::getFreeClipId()
1041 return QString::number(m_clipManager->getFreeClipId());
1044 DocClipBase *KdenliveDoc::getBaseClip(const QString &clipId)
1046 return m_clipManager->getClipById(clipId);
1049 void KdenliveDoc::slotCreateTextClip(QString /*group*/, const QString &/*groupId*/)
1051 QString titlesFolder = projectFolder().path() + "/titles/";
1052 KStandardDirs::makeDir(titlesFolder);
1053 TitleWidget *dia_ui = new TitleWidget(KUrl(), titlesFolder, m_render, kapp->activeWindow());
1054 if (dia_ui->exec() == QDialog::Accepted) {
1055 QStringList titleInfo = TitleWidget::getFreeTitleInfo(projectFolder());
1056 QImage pix = dia_ui->renderedPixmap();
1057 pix.save(titleInfo.at(1));
1058 //dia_ui->saveTitle(path + ".kdenlivetitle");
1059 m_clipManager->slotAddTextClipFile(titleInfo.at(0), titleInfo.at(1), dia_ui->xml().toString(), QString(), QString());
1065 int KdenliveDoc::tracksCount() const
1067 return m_tracksList.count();
1070 TrackInfo KdenliveDoc::trackInfoAt(int ix) const
1072 return m_tracksList.at(ix);
1075 void KdenliveDoc::switchTrackAudio(int ix, bool hide)
1077 m_tracksList[ix].isMute = hide; // !m_tracksList.at(ix).isMute;
1080 void KdenliveDoc::switchTrackLock(int ix, bool lock)
1082 m_tracksList[ix].isLocked = lock;
1085 bool KdenliveDoc::isTrackLocked(int ix) const
1087 return m_tracksList.at(ix).isLocked;
1090 void KdenliveDoc::switchTrackVideo(int ix, bool hide)
1092 m_tracksList[ix].isBlind = hide; // !m_tracksList.at(ix).isBlind;
1095 void KdenliveDoc::insertTrack(int ix, TrackInfo type)
1097 if (ix == -1) m_tracksList << type;
1098 else m_tracksList.insert(ix, type);
1101 void KdenliveDoc::deleteTrack(int ix)
1103 m_tracksList.removeAt(ix);
1106 void KdenliveDoc::setTrackType(int ix, TrackInfo type)
1108 m_tracksList[ix].type = type.type;
1109 m_tracksList[ix].isMute = type.isMute;
1110 m_tracksList[ix].isBlind = type.isBlind;
1111 m_tracksList[ix].isLocked = type.isLocked;
1114 const QList <TrackInfo> KdenliveDoc::tracksList() const
1116 return m_tracksList;
1119 QPoint KdenliveDoc::getTracksCount() const
1123 foreach(const TrackInfo &info, m_tracksList) {
1124 if (info.type == VIDEOTRACK) video++;
1127 return QPoint(video, audio);
1130 void KdenliveDoc::cachePixmap(const QString &fileId, const QPixmap &pix) const
1132 pix.save(m_projectFolder.path() + "/thumbs/" + fileId + ".png");
1135 QString KdenliveDoc::getLadspaFile() const
1138 QString counter = QString::number(ct).rightJustified(5, '0', false);
1139 while (QFile::exists(m_projectFolder.path() + "/ladspa/" + counter + ".ladspa")) {
1141 counter = QString::number(ct).rightJustified(5, '0', false);
1143 return m_projectFolder.path() + "/ladspa/" + counter + ".ladspa";
1146 bool KdenliveDoc::checkDocumentClips(QDomNodeList infoproducers)
1152 QList <QDomElement> missingClips;
1153 for (int i = 0; i < infoproducers.count(); i++) {
1154 e = infoproducers.item(i).toElement();
1155 clipType = e.attribute("type").toInt();
1156 if (clipType == TEXT || clipType == COLOR) continue;
1157 id = e.attribute("id");
1158 resource = e.attribute("resource");
1159 if (clipType == SLIDESHOW) resource = KUrl(resource).directory();
1160 if (!KIO::NetAccess::exists(KUrl(resource), KIO::NetAccess::SourceSide, 0)) {
1161 // Missing clip found
1162 missingClips.append(e);
1165 if (missingClips.isEmpty()) return true;
1166 DocumentChecker d(missingClips, m_document);
1167 return (d.exec() == QDialog::Accepted);
1171 #include "kdenlivedoc.moc"