id
int64 0
755k
| file_name
stringlengths 3
109
| file_path
stringlengths 13
185
| content
stringlengths 31
9.38M
| size
int64 31
9.38M
| language
stringclasses 1
value | extension
stringclasses 11
values | total_lines
int64 1
340k
| avg_line_length
float64 2.18
149k
| max_line_length
int64 7
2.22M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 6
65
| repo_stars
int64 100
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 9
values | repo_extraction_date
stringclasses 92
values | exact_duplicates_redpajama
bool 2
classes | near_duplicates_redpajama
bool 2
classes | exact_duplicates_githubcode
bool 2
classes | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 2
classes | near_duplicates_githubcode
bool 2
classes | near_duplicates_stackv1
bool 2
classes | near_duplicates_stackv2
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
13,147
|
thumbnailprovider.cpp
|
mltframework_shotcut/src/qmltypes/thumbnailprovider.cpp
|
/*
* Copyright (c) 2013-2023 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "thumbnailprovider.h"
#include <QQuickImageProvider>
#include <QCryptographicHash>
#include "mltcontroller.h"
#include "models/playlistmodel.h"
#include "database.h"
#include "util.h"
#include "settings.h"
#include <Logger.h>
ThumbnailProvider::ThumbnailProvider()
: QQuickImageProvider(QQmlImageProviderBase::Image,
QQmlImageProviderBase::ForceAsynchronousImageLoading)
, m_profile("atsc_720p_60")
{
}
QImage ThumbnailProvider::requestImage(const QString &id, QSize *size, const QSize &requestedSize)
{
QImage result;
// id is [hash]/mlt_service/resource#frameNumber[!]
// optional trailing '!' means to force update
int index = id.lastIndexOf('#');
if (index != -1) {
QString myId = id;
bool force = id.endsWith('!');
if (force)
myId = id.left(id.size() - 1);
QString hash = myId.section('/', 0, 0);
QString service = myId.section('/', 1, 1);
QString resource = myId.section('/', 2);
int frameNumber = myId.mid(index + 1).toInt();
Mlt::Properties properties;
// Scale the frameNumber to ThumbnailProvider profile's fps.
frameNumber = qRound(frameNumber / MLT.profile().fps() * m_profile.fps());
resource = resource.left(resource.lastIndexOf('#'));
resource = Util::removeQueryString(resource);
properties.set("_profile", m_profile.get_profile(), 0);
QString key = cacheKey(properties, service, resource, hash, frameNumber);
result = DB.getThumbnail(key);
if (force || result.isNull()) {
if (service == "avformat-novalidate")
service = "avformat";
else if (service.startsWith("xml"))
service = "xml-nogl";
Mlt::Producer producer;
if (service == "count") {
producer = Mlt::Producer(m_profile, service.toUtf8().constData(), "loader-nogl");
} else if (!Settings.playerGPU() || (service != "xml-nogl" && service != "consumer")) {
producer = Mlt::Producer(m_profile, service.toUtf8().constData(), resource.toUtf8().constData());
}
if (producer.is_valid()) {
result = makeThumbnail(producer, frameNumber, requestedSize);
DB.putThumbnail(key, result);
}
}
}
if (result.isNull()) {
result = QImage(1, 1, QImage::Format_Alpha8);
result.fill(0);
}
if (size)
*size = result.size();
return result;
}
QString ThumbnailProvider::cacheKey(Mlt::Properties &properties, const QString &service,
const QString &resource, const QString &hash, int frameNumber)
{
QString time = properties.frames_to_time(frameNumber, mlt_time_clock);
// Reduce the precision to centiseconds to increase chance for cache hit
// without much loss of accuracy.
time = time.left(time.size() - 1);
QString key;
if (hash.isEmpty()) {
key = QStringLiteral("%1 %2 %3")
.arg(service)
.arg(resource)
.arg(time);
QCryptographicHash hash(QCryptographicHash::Sha1);
hash.addData(key.toUtf8());
key = hash.result().toHex();
} else {
key = QStringLiteral("%1 %2").arg(hash).arg(time);
}
return key;
}
QImage ThumbnailProvider::makeThumbnail(Mlt::Producer &producer, int frameNumber,
const QSize &requestedSize)
{
Mlt::Filter scaler(m_profile, "swscale");
Mlt::Filter padder(m_profile, "resize");
Mlt::Filter converter(m_profile, "avcolor_space");
int height = PlaylistModel::THUMBNAIL_HEIGHT * 2;
int width = PlaylistModel::THUMBNAIL_WIDTH * 2;
if (!requestedSize.isEmpty()) {
width = requestedSize.width();
height = requestedSize.height();
}
producer.attach(scaler);
producer.attach(padder);
producer.attach(converter);
return MLT.image(producer, frameNumber, width, height);
}
| 4,739
|
C++
|
.cpp
| 117
| 33.350427
| 113
| 0.638967
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,148
|
filedialog.cpp
|
mltframework_shotcut/src/qmltypes/filedialog.cpp
|
/*
* Copyright (c) 2023 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "filedialog.h"
#include "mainwindow.h"
#include "settings.h"
#include "util.h"
FileDialog::FileDialog(QObject *parent)
: QObject{parent}
{
m_fileDialog.reset(new QFileDialog(&MAIN));
connect(m_fileDialog.get(), &QDialog::accepted, this, &FileDialog::accepted);
connect(m_fileDialog.get(), &QDialog::rejected, this, &FileDialog::rejected);
connect(m_fileDialog.get(), &QFileDialog::fileSelected, this, &FileDialog::fileSelected);
connect(m_fileDialog.get(), &QFileDialog::filterSelected, this, &FileDialog::filterSelected);
}
void FileDialog::setFileMode(FileMode mode)
{
m_fileMode = mode;
}
QString FileDialog::title() const
{
return m_fileDialog->windowTitle();
}
void FileDialog::setTitle(const QString &title)
{
if (title != m_fileDialog->windowTitle()) {
m_fileDialog->setWindowTitle(title);
emit titleChanged();
}
}
QStringList FileDialog::nameFilters() const
{
return m_fileDialog->nameFilters();
}
void FileDialog::setNameFilters(const QStringList &filters)
{
if (filters != m_fileDialog->nameFilters()) {
m_fileDialog->setNameFilters(filters);
emit nameFiltersChanged();
}
}
QString FileDialog::selectedFile()
{
return m_fileDialog->selectedFiles().first();
}
void FileDialog::open()
{
if (m_fileMode == FileDialog::OpenFile) {
m_fileDialog->setAcceptMode(QFileDialog::AcceptOpen);
m_fileDialog->setDirectory(Settings.openPath());
} else {
m_fileDialog->setAcceptMode(QFileDialog::AcceptSave);
m_fileDialog->setDirectory(Settings.savePath());
}
#ifdef Q_OS_MAC
m_fileDialog->setWindowModality(Qt::NonModal);
#else
m_fileDialog->setWindowModality(Qt::ApplicationModal);
#endif
m_fileDialog->setOptions(Util::getFileDialogOptions());
m_fileDialog->open();
}
| 2,524
|
C++
|
.cpp
| 76
| 29.947368
| 97
| 0.731037
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,149
|
fontdialog.cpp
|
mltframework_shotcut/src/qmltypes/fontdialog.cpp
|
/*
* Copyright (c) 2023-2024 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "fontdialog.h"
#include <QFontDialog>
FontDialog::FontDialog(QObject *parent)
: QObject{parent}
{
}
void FontDialog::open()
{
QFontDialog dialog(m_font);
dialog.setModal(true);
#if defined(Q_OS_UNIX) && !defined(Q_OS_MAC)
dialog.setOption(QFontDialog::DontUseNativeDialog);
#endif
if (dialog.exec() == QDialog::Accepted) {
setSelectedFont(dialog.currentFont());
emit accepted();
} else {
emit rejected();
}
}
void FontDialog::setSelectedFont(const QFont &font)
{
if (font != m_font) {
m_font = font;
emit selectedFontChanged(font);
}
}
| 1,372
|
C++
|
.cpp
| 43
| 27.55814
| 73
| 0.691433
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,150
|
qmlproducer.cpp
|
mltframework_shotcut/src/qmltypes/qmlproducer.cpp
|
/*
* Copyright (c) 2016-2023 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "qmlproducer.h"
#include "mltcontroller.h"
#include "util.h"
#include "models/audiolevelstask.h"
#include "mainwindow.h"
#include "qmltypes/qmlapplication.h"
#include "widgets/glaxnimateproducerwidget.h"
#include "settings.h"
#include <Logger.h>
static const char *kWidthProperty = "meta.media.width";
static const char *kHeightProperty = "meta.media.height";
static const char *kAspectNumProperty = "meta.media.sample_aspect_num";
static const char *kAspectDenProperty = "meta.media.sample_aspect_den";
QmlProducer::QmlProducer(QObject *parent)
: QObject(parent)
{
connect(this, SIGNAL(inChanged(int)), this, SIGNAL(durationChanged()));
connect(this, SIGNAL(outChanged(int)), this, SIGNAL(durationChanged()));
}
int QmlProducer::in()
{
if (!m_producer.is_valid()) return 0;
if (m_producer.get(kFilterInProperty))
// Shots on the timeline will set the producer to the cut parent.
// However, we want time-based filters such as fade in/out to use
// the cut's in/out and not the parent's.
return m_producer.get_int(kFilterInProperty);
else
return m_producer.get_in();
}
int QmlProducer::out()
{
if (!m_producer.is_valid()) return 0;
if (m_producer.get(kFilterOutProperty))
// Shots on the timeline will set the producer to the cut parent.
// However, we want time-based filters such as fade in/out to use
// the cut's in/out and not the parent's.
return m_producer.get_int(kFilterOutProperty);
else
return m_producer.get_out();
}
double QmlProducer::aspectRatio()
{
if (!m_producer.is_valid()) return 1.0;
if (m_producer.get(kHeightProperty)) {
double sar = 1.0;
if (m_producer.get(kAspectDenProperty)) {
sar = m_producer.get_double(kAspectNumProperty) /
m_producer.get_double(kAspectDenProperty);
}
return sar * m_producer.get_double(kWidthProperty) / m_producer.get_double(kHeightProperty);
}
return MLT.profile().dar();
}
QString QmlProducer::resource()
{
if (!m_producer.is_valid()) return QString();
QString result = QString::fromUtf8(m_producer.get("resource"));
if (result == "<producer>" && m_producer.get("mlt_service"))
result = QString::fromUtf8(m_producer.get("mlt_service"));
return result;
}
QString QmlProducer::name()
{
return Util::producerTitle(m_producer);
}
QVariant QmlProducer::audioLevels()
{
if (!m_producer.is_valid()) return QVariant();
if (m_producer.get_data(kAudioLevelsProperty))
return QVariant::fromValue(*((QVariantList *) m_producer.get_data(kAudioLevelsProperty)));
else
return QVariant();
}
int QmlProducer::fadeIn()
{
if (!m_producer.is_valid()) return 0;
QScopedPointer<Mlt::Filter> filter(MLT.getFilter("fadeInVolume", &m_producer));
if (!filter || !filter->is_valid())
filter.reset(MLT.getFilter("fadeInBrightness", &m_producer));
if (!filter || !filter->is_valid())
filter.reset(MLT.getFilter("fadeInMovit", &m_producer));
return (filter && filter->is_valid()) ? filter->get_length() : 0;
}
int QmlProducer::fadeOut()
{
if (!m_producer.is_valid()) return 0;
QScopedPointer<Mlt::Filter> filter(MLT.getFilter("fadeOutVolume", &m_producer));
if (!filter || !filter->is_valid())
filter.reset(MLT.getFilter("fadeOutBrightness", &m_producer));
if (!filter || !filter->is_valid())
filter.reset(MLT.getFilter("fadeOutMovit", &m_producer));
return (filter && filter->is_valid()) ? filter->get_length() : 0;
}
double QmlProducer::speed()
{
double result = 1.0;
if (!m_producer.is_valid()) return result;
if (m_producer.is_valid()) {
if (!qstrcmp("timewarp", m_producer.get("mlt_service")))
result = m_producer.get_double("warp_speed");
}
return result;
}
void QmlProducer::setPosition(int position)
{
if (!m_producer.is_valid()) return;
int length = duration();
if (position < length) {
if (MLT.isMultitrack())
emit seeked(m_producer.get_int(kPlaylistStartProperty) + qMax(0, position));
else
emit seeked(in() + qMax(0, position));
} else if (m_position != length - 1) {
m_position = length - 1;
emit positionChanged(m_position);
}
}
void QmlProducer::seek(int position)
{
if (m_producer.is_valid() && m_position != position) {
m_position = position;
emit positionChanged(qBound(0, position, duration()));
}
}
Q_INVOKABLE bool QmlProducer::outOfBounds()
{
return m_position < 0 || m_position > duration();
}
void QmlProducer::newGlaxnimateFile(const QString &filename)
{
GlaxnimateIpcServer::instance().newFile(filename, duration());
}
void QmlProducer::launchGlaxnimate(const QString &filename) const
{
if (!filename.isEmpty()) {
GlaxnimateIpcServer::instance().launch(m_producer, filename, false);
}
}
void QmlProducer::audioLevelsReady(const QPersistentModelIndex &index)
{
Q_UNUSED(index)
emit audioLevelsChanged();
}
void QmlProducer::remakeAudioLevels()
{
AudioLevelsTask::start(m_producer, this, QModelIndex(), true);
}
void QmlProducer::remakeAudioLevels(bool isKeyframesVisible)
{
if (isKeyframesVisible)
AudioLevelsTask::start(m_producer, this, QModelIndex());
}
double QmlProducer::displayAspectRatio()
{
if (m_producer.is_valid() && m_producer.get(kHeightProperty)) {
double sar = 1.0;
if (m_producer.get(kAspectDenProperty)) {
sar = m_producer.get_double(kAspectNumProperty) /
m_producer.get_double(kAspectDenProperty);
}
return sar * m_producer.get_double(kWidthProperty) / m_producer.get_double(kHeightProperty);
}
return MLT.profile().dar();
}
QString QmlProducer::get(QString name, int position)
{
if (m_producer.is_valid()) {
if (position < 0)
return QString::fromUtf8(m_producer.get(name.toUtf8().constData()));
else
return QString::fromUtf8(m_producer.anim_get(name.toUtf8().constData(), position, duration()));
} else {
return QString();
}
}
double QmlProducer::getDouble(QString name, int position)
{
if (m_producer.is_valid()) {
if (position < 0)
return m_producer.get_double(name.toUtf8().constData());
else
return m_producer.anim_get_double(name.toUtf8().constData(), position, duration());
} else {
return 0.0;
}
}
QRectF QmlProducer::getRect(QString name, int position)
{
if (!m_producer.is_valid()) return QRectF();
QString s = QString::fromUtf8(m_producer.get(name.toUtf8().constData()));
if (!s.isEmpty()) {
mlt_rect rect;
if (position < 0) {
rect = m_producer.get_rect(name.toUtf8().constData());
} else {
rect = m_producer.anim_get_rect(name.toUtf8().constData(), position, duration());
}
if (s.contains('%')) {
return QRectF(qRound(rect.x * MLT.profile().width()),
qRound(rect.y * MLT.profile().height()),
qRound(rect.w * MLT.profile().width()),
qRound(rect.h * MLT.profile().height()));
} else {
return QRectF(rect.x, rect.y, rect.w, rect.h);
}
} else {
return QRectF(0.0, 0.0, 0.0, 0.0);
}
}
void QmlProducer::setProducer(Mlt::Producer &producer)
{
m_producer = producer;
if (m_producer.is_valid()) {
remakeAudioLevels(MAIN.keyframesDockIsVisible());
} else {
GlaxnimateIpcServer::instance().reset();
}
emit producerChanged();
emit inChanged(0);
emit outChanged(0);
emit lengthChanged();
}
| 8,451
|
C++
|
.cpp
| 239
| 30.158996
| 107
| 0.66402
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,151
|
qmlprofile.cpp
|
mltframework_shotcut/src/qmltypes/qmlprofile.cpp
|
/*
* Copyright (c) 2014 Meltytech, LLC
* Author: Brian Matherly <pez4brian@yahoo.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "qmlprofile.h"
#include "mltcontroller.h"
QmlProfile &QmlProfile::singleton()
{
static QmlProfile instance;
return instance;
}
QmlProfile::QmlProfile() :
QObject()
{
}
int QmlProfile::width() const
{
return MLT.profile().width();
}
int QmlProfile::height() const
{
return MLT.profile().height();
}
double QmlProfile::aspectRatio() const
{
return MLT.profile().dar();
}
double QmlProfile::fps() const
{
return MLT.profile().fps();
}
double QmlProfile::sar() const
{
return MLT.profile().sar();
}
| 1,285
|
C++
|
.cpp
| 48
| 24.604167
| 72
| 0.738812
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,152
|
qmlutilities.cpp
|
mltframework_shotcut/src/qmltypes/qmlutilities.cpp
|
/*
* Copyright (c) 2013-2023 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "qmltypes/qmlapplication.h"
#include "qmltypes/colordialog.h"
#include "qmltypes/colorpickeritem.h"
#include "qmltypes/colorwheelitem.h"
#include "qmltypes/filedialog.h"
#include "qmltypes/fontdialog.h"
#include "qmltypes/messagedialog.h"
#include "qmltypes/qmleditmenu.h"
#include "qmltypes/qmlprofile.h"
#include "qmltypes/qmlutilities.h"
#include "qmltypes/qmlfile.h"
#include "qmltypes/qmlfilter.h"
#include "qmltypes/qmlmarkermenu.h"
#include "qmltypes/qmlmetadata.h"
#include "qmltypes/qmlrichtext.h"
#include "qmltypes/qmlrichtextmenu.h"
#include "qmltypes/timelineitems.h"
#include "settings.h"
#include "models/metadatamodel.h"
#include "models/keyframesmodel.h"
#include "models/subtitlesmodel.h"
#include "models/subtitlesselectionmodel.h"
#include <QCoreApplication>
#include <QSysInfo>
#include <QCursor>
#include <QtQml>
#include <QQmlEngine>
#include <QQmlContext>
QmlUtilities::QmlUtilities(QObject *parent) :
QObject(parent)
{
}
void QmlUtilities::registerCommonTypes()
{
qmlRegisterType<QmlFile>("org.shotcut.qml", 1, 0, "File");
qmlRegisterType<QmlFilter>("org.shotcut.qml", 1, 0, "Filter");
qmlRegisterType<QmlMetadata>("org.shotcut.qml", 1, 0, "Metadata");
qmlRegisterAnonymousType<QmlKeyframesMetadata>("org.shotcut.qml", 1);
qmlRegisterType<QmlKeyframesParameter>("org.shotcut.qml", 1, 0, "Parameter");
qmlRegisterType<QmlRichText>("org.shotcut.qml", 1, 0, "RichText");
qmlRegisterType<KeyframesModel>("org.shotcut.qml", 1, 0, "KeyframesModel");
qmlRegisterType<SubtitlesModel>("org.shotcut.qml", 1, 0, "SubtitlesModel");
qmlRegisterType<SubtitlesSelectionModel>("org.shotcut.qml", 1, 0, "SubtitlesSelectionModel");
qmlRegisterType<QmlUtilities>("org.shotcut.qml", 1, 0, "Utilities");
// MetadataModel is registered to access its MetadataFilter enum.
qmlRegisterUncreatableType<MetadataModel>("org.shotcut.qml", 1, 0, "MetadataModel",
"You cannot create a MetadataModel from QML.");
qmlRegisterUncreatableType<ShotcutSettings>("org.shotcut.qml", 1, 0, "Settings",
"You cannot create a Settings from QML.");
qmlRegisterType<ColorPickerItem>("Shotcut.Controls", 1, 0, "ColorPickerItem");
qmlRegisterType<ColorWheelItem>("Shotcut.Controls", 1, 0, "ColorWheelItem");
qmlRegisterType<QmlMarkerMenu>("Shotcut.Controls", 1, 0, "MarkerMenu");
qmlRegisterType<QmlEditMenu>("Shotcut.Controls", 1, 0, "EditContextMenu");
qmlRegisterType<QmlRichTextMenu>("Shotcut.Controls", 1, 0, "RichTextMenu");
qmlRegisterType<ColorDialog>("Shotcut.Controls", 1, 0, "ColorDialog");
qmlRegisterType<FontDialog>("Shotcut.Controls", 1, 0, "FontDialog");
qmlRegisterType<MessageDialog>("Shotcut.Controls", 1, 0, "MessageDialog");
qmlRegisterType<FileDialog>("Shotcut.Controls", 1, 0, "FileDialog");
registerTimelineItems();
}
void QmlUtilities::setCommonProperties(QQmlContext *context)
{
context->setContextProperty("settings", &ShotcutSettings::singleton());
context->setContextProperty("application", &QmlApplication::singleton());
context->setContextProperty("profile", &QmlProfile::singleton());
}
QDir QmlUtilities::qmlDir()
{
QDir dir = QmlApplication::dataDir();
dir.cd("shotcut");
dir.cd("qml");
return dir;
}
QQmlEngine *QmlUtilities::sharedEngine()
{
static QQmlEngine *s_engine = 0;
if (!s_engine)
s_engine = new QQmlEngine;
return s_engine;
}
QUrl QmlUtilities::blankVui()
{
QDir dir = qmlDir();
dir.cd("modules");
dir.cd("Shotcut");
dir.cd("Controls");
return QUrl::fromLocalFile(dir.absoluteFilePath("VuiBase.qml"));
}
| 4,400
|
C++
|
.cpp
| 104
| 38.615385
| 97
| 0.736768
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,153
|
colordialog.cpp
|
mltframework_shotcut/src/qmltypes/colordialog.cpp
|
/*
* Copyright (c) 2023 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "colordialog.h"
#include <QColorDialog>
ColorDialog::ColorDialog(QObject *parent)
: QObject{parent}
{
}
void ColorDialog::open()
{
auto color = m_color;
QColorDialog::ColorDialogOptions flags = QColorDialog::ShowAlphaChannel;
#if defined(Q_OS_UNIX) && !defined(Q_OS_MAC)
flags = flags | QColorDialog::DontUseNativeDialog;
#endif
auto newColor = QColorDialog::getColor(color, nullptr, m_title, flags);
if (newColor.isValid()) {
auto rgb = newColor;
auto transparent = QColor(0, 0, 0, 0);
rgb.setAlpha(color.alpha());
if (newColor.alpha() == 0 && (rgb != color || (newColor == transparent && color == transparent))) {
newColor.setAlpha(255);
}
setSelectedColor(newColor);
emit accepted();
}
}
void ColorDialog::setSelectedColor(const QColor &color)
{
if (color != m_color) {
m_color = color;
emit selectedColorChanged(color);
}
}
void ColorDialog::setTitle(const QString &title)
{
if (title != m_title) {
m_title = title;
emit titleChanged();
}
}
| 1,858
|
C++
|
.cpp
| 55
| 28.672727
| 108
| 0.668342
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,154
|
qmlmarkermenu.cpp
|
mltframework_shotcut/src/qmltypes/qmlmarkermenu.cpp
|
/*
* Copyright (c) 2022-2023 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "qmlmarkermenu.h"
#include "actions.h"
#include "docks/timelinedock.h"
#include "qmltypes/qmlapplication.h"
#include <QColorDialog>
#include <QLabel>
#include <QMenu>
#include <QToolButton>
#include <QWidgetAction>
QmlMarkerMenu::QmlMarkerMenu(QObject *parent)
: QObject(parent)
, m_timeline(nullptr)
, m_index(-1)
{
}
QObject *QmlMarkerMenu::target()
{
return m_timeline;
}
void QmlMarkerMenu::setTarget(QObject *target)
{
m_timeline = dynamic_cast<TimelineDock *>(target);
}
int QmlMarkerMenu::index()
{
return m_index;
}
void QmlMarkerMenu::setIndex(int index)
{
m_index = index;
}
void QmlMarkerMenu::popup()
{
if (!m_timeline || m_index < 0)
return;
QMenu menu;
QAction editAction(tr("Edit..."));
editAction.setShortcut(Actions["timelineMarkerAction"]->shortcut());
connect(&editAction, &QAction::triggered, this, [&]() {
m_timeline->editMarker(m_index);
});
menu.addAction(&editAction);
QAction deleteAction(tr("Delete"));
deleteAction.setShortcut(Actions["timelineDeleteMarkerAction"]->shortcut());
connect(&deleteAction, &QAction::triggered, this, [&]() {
m_timeline->deleteMarker(m_index);
});
menu.addAction(&deleteAction);
QAction colorAction(tr("Choose Color..."));
connect(&colorAction, &QAction::triggered, this, [&]() {
QColor markerColor = m_timeline->markersModel()->getMarker(m_index).color;
QColorDialog colorDialog(markerColor);
#if defined(Q_OS_UNIX) && !defined(Q_OS_MAC)
colorDialog.setOptions(QColorDialog::DontUseNativeDialog);
#endif
colorDialog.setModal(QmlApplication::dialogModality());
if (colorDialog.exec() == QDialog::Accepted) {
m_timeline->markersModel()->setColor(m_index, colorDialog.currentColor());
}
});
menu.addAction(&colorAction);
QMenu *recentColorMenu = menu.addMenu(tr("Choose Recent Color"));
QStringList colors = m_timeline->markersModel()->recentColors();
QString highlightColor = QApplication::palette().highlight().color().name();
for (int c = 0; c < colors.size(); c++) {
QWidgetAction *widgetAction = new QWidgetAction(recentColorMenu);
QToolButton *colorButton = new QToolButton();
colorButton->setText(colors[c]);
QString textColor = QmlApplication::contrastingColor(colors[c]).name();
QString styleSheet = QString(
"QToolButton {"
" background-color: %1;"
" border-style: solid;"
" border-width: 3px;"
" border-color: %1;"
" color: %2"
"}"
"QToolButton:hover {"
" background-color: %1;"
" border-style: solid;"
" border-width: 3px;"
" border-color: %3;"
" color: %2"
"}"
).arg(colors[c]).arg(textColor).arg(highlightColor);
colorButton->setStyleSheet(styleSheet);
connect(colorButton, &QToolButton::clicked, this, [ &, colorButton]() {
m_timeline->markersModel()->setColor(m_index, colorButton->text());
menu.close();
});
widgetAction->setDefaultWidget(colorButton);
recentColorMenu->addAction(widgetAction);
}
menu.exec(QCursor::pos());
}
| 4,342
|
C++
|
.cpp
| 111
| 30.693694
| 86
| 0.610624
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,158
|
spatialmedia.cpp
|
mltframework_shotcut/src/spatialmedia/spatialmedia.cpp
|
/*****************************************************************************
*
* Copyright 2016 Varol Okan. All rights reserved.
* Copyright (c) 2020-2024 Meltytech, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
****************************************************************************/
#include "spatialmedia.h"
#include "mpeg4_container.h"
#include "sa3d.h"
#include <stdint.h>
#include <fstream>
#include <iostream>
#include <sstream>
#include <Logger.h>
static const uint8_t SPHERICAL_UUID_ID[] = {0xff, 0xcc, 0x82, 0x63, 0xf8, 0x55, 0x4a, 0x93, 0x88, 0x14, 0x58, 0x7a, 0x02, 0x52, 0x1f, 0xdd };
// "\xff\xcc\x82\x63\xf8\x55\x4a\x93\x88\x14\x58\x7a\x02\x52\x1f\xdd")
//static std::string RDF_PREFIX = " xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" ";
static std::string SPHERICAL_XML_HEADER = "<?xml version=\"1.0\"?>"\
"<rdf:SphericalVideo\n"\
"xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n"\
"xmlns:GSpherical=\"http://ns.google.com/videos/1.0/spherical/\">";
static std::string SPHERICAL_XML_CONTENTS = "<GSpherical:Spherical>true</GSpherical:Spherical>"\
"<GSpherical:Stitched>true</GSpherical:Stitched>"\
"<GSpherical:StitchingSoftware>Spherical Metadata Tool</GSpherical:StitchingSoftware>"\
"<GSpherical:ProjectionType>equirectangular</GSpherical:ProjectionType>";
//static std::string SPHERICAL_XML_CONTENTS_TOP_BOTTOM = "<GSpherical:StereoMode>top-bottom</GSpherical:StereoMode>";
//static std::string SPHERICAL_XML_CONTENTS_LEFT_RIGHT = "<GSpherical:StereoMode>left-right</GSpherical:StereoMode>";
// Parameter order matches that of the crop option.
static std::string SPHERICAL_XML_CONTENTS_CROP_FORMAT = \
"<GSpherical:CroppedAreaImageWidthPixels>%d</GSpherical:CroppedAreaImageWidthPixels>"\
"<GSpherical:CroppedAreaImageHeightPixels>%d</GSpherical:CroppedAreaImageHeightPixels>"\
"<GSpherical:FullPanoWidthPixels>%d</GSpherical:FullPanoWidthPixels>"\
"<GSpherical:FullPanoHeightPixels>%d</GSpherical:FullPanoHeightPixels>"\
"<GSpherical:CroppedAreaLeftPixels>%d</GSpherical:CroppedAreaLeftPixels>"\
"<GSpherical:CroppedAreaTopPixels>%d</GSpherical:CroppedAreaTopPixels>";
static std::string SPHERICAL_XML_FOOTER = "</rdf:SphericalVideo>";
//static std::string SPHERICAL_PREFIX = "{http://ns.google.com/videos/1.0/spherical/}";
static Box *spherical_uuid ( std::string &strMetadata )
{
// Constructs a uuid containing spherical metadata.
Box *p = new Box;
// a box containing spherical metadata.
// if ( strUUID.length ( ) != 16 )
// std::cerr << "ERROR: Data mismatch" << std::endl;
int iSize = strMetadata.size ( );
const uint8_t *pMetadata = reinterpret_cast<const uint8_t*>(strMetadata.c_str());
memcpy ( p->m_name, constants::TAG_UUID, 4 );
p->m_iHeaderSize = 8;
p->m_iContentSize = 0;
p->m_pContents = new uint8_t[iSize + 16 + 1];
memcpy ( p->m_pContents, SPHERICAL_UUID_ID, 16 );
memcpy ((p->m_pContents+16), pMetadata, iSize );
p->m_iContentSize=iSize+16;
return p;
}
static int get_descriptor_length(std::fstream &inFile)
{
auto result = 0;
uint8_t size_byte;
for (int i = 0; i < 4; i++) {
inFile.read((char*) &size_byte, 1);
result = (result << 7) | (size_byte & 0x7f);
if (size_byte != 0x80) break;
}
return result;
}
static int get_aac_num_channels(Box *mp4aBox, std::fstream &inFile)
{
auto result = -1;
auto size = sizeof(mp4aBox->m_name);
auto pos = inFile.tellg();
for (auto box : static_cast<Container*>(mp4aBox)->m_listContents) {
if (!memcmp(constants::TAG_WAVE, box->m_name, size)) {
// Handle .mov with AAC audio: stsd -> mp4a -> wave -> esds
return get_aac_num_channels(box, inFile);
} else if (!memcmp(constants::TAG_ESDS, box->m_name, size)) {
// Read the AAC AudioSpecificConfig
char data[2];
inFile.seekg(box->content_start() + 4);
// Verify the read descriptor is an elementary stream descriptor
inFile.read(data, 1);
if (data[0] != 3) break;
// Verify the read descriptor is a decoder config. descriptor
auto length = get_descriptor_length(inFile);
inFile.seekg(3, std::ios_base::cur);
inFile.read(data, 1);
if (data[0] != 4) break;
// Verify the read descriptor is a decoder specific info descriptor
length = get_descriptor_length(inFile);
inFile.seekg(13, std::ios_base::cur); // offset to the decoder specific config descriptor
inFile.read(data, 1);
if (data[0] != 5) break;
auto audio_specific_descriptor_size = get_descriptor_length(inFile);
if (audio_specific_descriptor_size < 2) break;
inFile.read(data, 2);
auto object_type = (data[0] >> 3) & 0x1f;
if (object_type != 2) break;
auto sampling_frequency_index = ((data[0] & 0x07) << 1 | (data[1] >> 7) & 0x01);
// TODO: If the sample rate is 96kHz an additional 24 bit offset
// value here specifies the actual sample rate.
if (sampling_frequency_index == 0) break;
result = (data[1] >> 3) & 0x0f;
}
}
inFile.seekg(pos);
return result;
}
static bool sound_samples_contains(const char *name)
{
auto nameSize = sizeof(Box::m_name);
auto size = sizeof(constants::SOUND_SAMPLE_DESCRIPTIONS) / nameSize;
for (int i = 0; i < size; i++) {
if (!memcmp(name, constants::SOUND_SAMPLE_DESCRIPTIONS[i], nameSize))
return true;
}
return false;
}
static int get_sample_description_num_channels(Box *ssdBox, std::fstream &inFile)
{
auto result = -1;
auto size = sizeof(ssdBox->m_name);
auto pos = inFile.tellg();
char data[4];
// Read the AAC AudioSpecificConfig
inFile.seekg(ssdBox->content_start() + 8);
inFile.read(data, 2);
auto version = (data[0] << 8) | data[1];
inFile.seekg(2 + 4, std::ios_base::cur); // revision_level and vendor
switch (version) {
case 0:
case 1:
inFile.read(data, 2);
result = (data[0] << 8) | data[1];
break;
case 2:
inFile.seekg(24, std::ios_base::cur);
inFile.read(data, 4);
result = 0;
for (int i = 0; i < 4; i++)
result = (result << 8) | data[i];
break;
}
inFile.seekg(pos);
return result;
}
static void mpeg4_add_spatial_audio(Box *mdiaBox, std::fstream &inFile)
{
auto size = sizeof(mdiaBox->m_name);
for (auto box : static_cast<Container*>(mdiaBox)->m_listContents) {
if (!memcmp(constants::TAG_MINF, box->m_name, size)) {
for (auto box : static_cast<Container*>(box)->m_listContents) {
if (!memcmp(constants::TAG_STBL, box->m_name, size)) {
for (auto box : static_cast<Container*>(box)->m_listContents) {
if (!memcmp(constants::TAG_STSD, box->m_name, size)) {
for (auto box : static_cast<Container*>(box)->m_listContents) {
auto channels = 0;
if (!memcmp(constants::TAG_MP4A, box->m_name, size)) {
channels = get_aac_num_channels(box, inFile);
} else if (sound_samples_contains(box->m_name)) {
channels = get_sample_description_num_channels(box, inFile);
}
if (4 == channels) {
static_cast<Container*>(box)->add(SA3DBox::create(channels));
break;
}
}
}
}
}
}
}
}
}
static bool mpeg4_add_spherical ( Mpeg4Container *pMPEG4, std::fstream &inFile, std::string &strMetadata )
{
// Adds a spherical uuid box to an mpeg4 file for all video tracks.
//
// pMPEG4 : Mpeg4 file structure to add metadata.
// inFile : file handle, Source for uncached file contents.
// strMetadata: string, xml metadata to inject into spherical tag.
if ( ! pMPEG4 )
return false;
bool bAdded = false;
Container *pMoov = (Container *)pMPEG4->m_pMoovBox;
if ( ! pMoov )
return false;
std::vector<Box *>::iterator it = pMoov->m_listContents.begin ( );
while ( it != pMoov->m_listContents.end ( ) ) {
Container *pBox = (Container *)*it++;
if ( memcmp ( pBox->m_name, constants::TAG_TRAK, 4 ) == 0 ) {
bAdded = false;
pBox->remove ( constants::TAG_UUID );
std::vector<Box *>::iterator it2 = pBox->m_listContents.begin ( );
while ( it2 != pBox->m_listContents.end ( ) ) {
Container *pSub = (Container *)*it2++;
if ( memcmp ( pSub->m_name, constants::TAG_MDIA, 4 ) != 0 )
continue;
std::vector<Box *>::iterator it3 = pSub->m_listContents.begin ( );
while ( it3 != pSub->m_listContents.end ( ) ) {
Box *pMDIA = *it3++;
if ( memcmp ( pMDIA->m_name, constants::TAG_MINF, 4 ) == 0 ) {
mpeg4_add_spatial_audio(pSub, inFile);
continue;
}
if ( memcmp ( pMDIA->m_name, constants::TAG_HDLR, 4 ) != 0 )
continue;
char name[4];
int iPos = pMDIA->content_start ( ) + 8;
inFile.seekg( iPos );
inFile.read ( name, 4 );
if ( memcmp ( name, constants::TRAK_TYPE_VIDE, 4 ) == 0 ) {
bAdded = true;
break;
}
}
if ( bAdded ) {
if ( ! pBox->add ( spherical_uuid ( strMetadata ) ) )
return true;
break;
}
}
}
}
pMPEG4->resize ( );
return true;
}
bool SpatialMedia::injectSpherical(const std::string& strInFile, const std::string& strOutFile)
{
std::fstream inFile(strInFile.c_str(), std::ios::in | std::ios::binary | std::ios::ate);
if (!inFile.is_open()) {
LOG_ERROR() << "Error \"" << strInFile.c_str() << "\" does not exist or do not have permission.";
return false;
}
Mpeg4Container* pMPEG4 = Mpeg4Container::load(inFile);
if (!pMPEG4) {
LOG_ERROR() << "Error, file could not be opened.";
return false;
}
std::string stereo_xml;
// if ( stereo == SpatialMedia::Parser::SM_TOP_BOTTOM )
// stereo_xml += SPHERICAL_XML_CONTENTS_TOP_BOTTOM;
// if ( stereo == SpatialMedia::Parser::SM_LEFT_RIGHT )
// stereo_xml += SPHERICAL_XML_CONTENTS_LEFT_RIGHT;
std::string xml = SPHERICAL_XML_HEADER + SPHERICAL_XML_CONTENTS + stereo_xml + SPHERICAL_XML_FOOTER;;
bool bRet = mpeg4_add_spherical(pMPEG4, inFile, xml);
if (!bRet) {
LOG_ERROR() << "Error failed to insert spherical data";
}
LOG_INFO() << "Saved spatial media metadata";
std::fstream outFile(strOutFile.c_str(), std::ios::out | std::ios::binary);
if (!outFile.is_open()) {
LOG_ERROR() << "Error file: \"" << strOutFile.c_str() << "\" could not create or do not have permission.";
return false;
}
pMPEG4->save(inFile, outFile, 0);
return true;
}
| 11,800
|
C++
|
.cpp
| 269
| 36.32342
| 141
| 0.5992
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,160
|
alignmentarray.cpp
|
mltframework_shotcut/src/dialogs/alignmentarray.cpp
|
/*
* Copyright (c) 2022 Meltytech, LLC
*
* Author: André Caldas de Souza <andrecaldas@unb.br>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "alignmentarray.h"
#include <QDebug>
#include <QMutexLocker>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <iostream>
#include <numeric>
// FFTW plan functions are not threadsafe
static QMutex s_fftwPlanningMutex;
AlignmentArray::AlignmentArray()
: m_forwardBuf(nullptr)
, m_backwardBuf(nullptr)
, m_autocorrelationMax(std::numeric_limits<double>::min())
, m_isTransformed(false)
{
}
AlignmentArray::AlignmentArray(size_t minimum_size)
: AlignmentArray()
{
init(minimum_size);
}
AlignmentArray::~AlignmentArray()
{
QMutexLocker locker(&s_fftwPlanningMutex);
if (m_forwardBuf) {
fftw_free(reinterpret_cast<fftw_complex *>(m_forwardBuf));
fftw_destroy_plan(m_forwardPlan);
fftw_free(reinterpret_cast<fftw_complex *>(m_backwardBuf));
fftw_destroy_plan(m_backwardPlan);
}
}
void AlignmentArray::init(size_t minimumSize)
{
QMutexLocker locker(&m_transformMutex);
m_minimumSize = minimumSize;
m_actualComplexSize = (minimumSize * 2) - 1;
if (m_forwardBuf) {
QMutexLocker locker(&s_fftwPlanningMutex);
fftw_free(reinterpret_cast<fftw_complex *>(m_forwardBuf));
m_forwardBuf = nullptr;
fftw_destroy_plan(m_forwardPlan);
fftw_free(reinterpret_cast<fftw_complex *>(m_backwardBuf));
m_backwardBuf = nullptr;
fftw_destroy_plan(m_backwardPlan);
}
}
void AlignmentArray::setValues(const std::vector<double> &values)
{
QMutexLocker locker(&m_transformMutex);
m_values = values;
m_isTransformed = false;
}
double AlignmentArray::calculateOffset(AlignmentArray &from, int *offset)
{
// Create a destination for the correlation values
s_fftwPlanningMutex.lock();
fftw_complex *buf = fftw_alloc_complex(m_actualComplexSize);
std::complex<double> *correlationBuf = reinterpret_cast<std::complex<double>*>(buf);
fftw_plan correlationPlan = fftw_plan_dft_1d(m_actualComplexSize, buf, buf, FFTW_BACKWARD,
FFTW_ESTIMATE);
std::fill(correlationBuf, correlationBuf + m_actualComplexSize, std::complex<double>(0));
s_fftwPlanningMutex.unlock();
// Ensure the two sequences are transformed
transform();
from.transform();
// Calculate the cross-correlation signal
for (size_t i = 0; i < m_actualComplexSize; ++i) {
correlationBuf[i] = m_forwardBuf[i] * std::conj(from.m_forwardBuf[i]);
}
// Convert to time series
fftw_execute(correlationPlan);
// Find the maximum correlation offset
double max = 0;
for (size_t i = 0; i < m_actualComplexSize; ++i) {
double norm = std::norm(correlationBuf[i]);
if (max < norm) {
*offset = i;
max = norm;
}
}
if ( 2 * *offset > (int)m_actualComplexSize ) {
*offset -= ((int)m_actualComplexSize);
}
s_fftwPlanningMutex.lock();
fftw_free(correlationBuf);
fftw_destroy_plan(correlationPlan);
s_fftwPlanningMutex.unlock();
// Normalize the best score by dividing by the max autocorrelation of the two signals
// (Pearson's correlation coefficient)
double correlationCoefficient = sqrt(m_autocorrelationMax) * sqrt(from.m_autocorrelationMax);
return max / correlationCoefficient;
}
double AlignmentArray::calculateOffsetAndSpeed(AlignmentArray &from, double *speed, int *offset,
double speedRange)
{
// The minimum speed step results in one frame of stretch.
// Do not try to compensate for more than 1 frame of speed difference.
double minimumSpeedStep = 1.0 / (double)from.m_values.size();
double speedStep = 0.0005;
double bestSpeed = 1.0;
int bestOffset = 0;
double bestScore = calculateOffset(from, &bestOffset);
AlignmentArray stretched(m_minimumSize);
double speedMin = bestSpeed - speedRange;
double speedMax = bestSpeed + speedRange;
while (speedStep > (minimumSpeedStep / 10)) {
for (double s = speedMin; s <= speedMax; s += speedStep) {
if (s == bestSpeed) {
continue;
}
// Stretch the original values to simulate a speed compensation
double factor = 1.0 / s;
size_t stretchedSize = std::floor((double)from.m_values.size() * factor);
std::vector<double> strechedValues(stretchedSize);
// Nearest neighbor interpolation
for (size_t i = 0; i < stretchedSize; i++) {
size_t srcIndex = std::round(s * i);
strechedValues[i] = from.m_values[srcIndex];
}
stretched.setValues(strechedValues);
double score = calculateOffset(stretched, offset);
if (score > bestScore) {
bestScore = score;
bestSpeed = s;
bestOffset = *offset;
}
}
speedStep /= 10;
speedMin = bestSpeed - (speedStep * 5);
speedMax = bestSpeed + (speedStep * 5);
}
*speed = bestSpeed;
*offset = bestOffset;
return bestScore;
}
void AlignmentArray::transform()
{
QMutexLocker locker(&m_transformMutex);
if (!m_isTransformed) {
if (!m_forwardBuf) {
// Create the plans while the global planning mutex is locked
s_fftwPlanningMutex.lock();
fftw_complex *buf = nullptr;
// Allocate the forward buffer and plan
buf = fftw_alloc_complex(m_actualComplexSize);
m_forwardBuf = reinterpret_cast<std::complex<double>*>(buf);
m_forwardPlan = fftw_plan_dft_1d(m_actualComplexSize, buf, buf, FFTW_FORWARD, FFTW_ESTIMATE);
// Allocate the backward buffer and plan
buf = fftw_alloc_complex(m_actualComplexSize);
m_backwardBuf = reinterpret_cast<std::complex<double>*>(buf);
m_backwardPlan = fftw_plan_dft_1d(m_actualComplexSize, buf, buf, FFTW_BACKWARD, FFTW_ESTIMATE);
s_fftwPlanningMutex.unlock();
}
std::fill(m_forwardBuf, m_forwardBuf + m_actualComplexSize, std::complex<double>(0));
std::fill(m_backwardBuf, m_backwardBuf + m_actualComplexSize, std::complex<double>(0));
// Calculate the mean and standard deviation to be used to normalize the values.
double accum = 0.0;
std::for_each (m_values.begin(), m_values.end(), [&](const double d) {
accum += d;
});
double mean = accum / m_values.size();
accum = 0;
std::for_each (m_values.begin(), m_values.end(), [&](const double d) {
accum += (d - mean) * (d - mean);
});
double stddev = sqrt(accum / (m_values.size() - 1));
// Fill the transform array
// Normalize the input values: Subtract the mean and divide by the standard deviation.
for ( size_t i = 0; i < m_values.size(); i++ ) {
m_forwardBuf[i] = (m_values[i] - mean) / stddev;
}
// Perform the forward DFT
fftw_execute(m_forwardPlan);
// Perform autocorrelation to calculate the maximum correlation value
for (size_t i = 0; i < m_actualComplexSize; i++) {
m_backwardBuf[i] = m_forwardBuf[i] * std::conj(m_forwardBuf[i]);
}
// Convert back to time series
fftw_execute(m_backwardPlan);
// Find the maximum autocorrelation value
for (size_t i = 0; i < m_actualComplexSize; i++) {
double norm = std::norm(m_backwardBuf[i]);
if (norm > m_autocorrelationMax)
m_autocorrelationMax = norm;
}
m_isTransformed = true;
}
}
| 8,424
|
C++
|
.cpp
| 207
| 33.47343
| 107
| 0.644182
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,161
|
bitratedialog.cpp
|
mltframework_shotcut/src/dialogs/bitratedialog.cpp
|
/*
* Copyright (c) 2023-2024 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "bitratedialog.h"
#include "settings.h"
#include "dialogs/saveimagedialog.h"
#include <QtCharts/QChartView>
#include <QtCharts/QStackedBarSeries>
#include <QtCharts/QBarSet>
#include <QtCharts/QLineSeries>
#include <QtCharts/QSplineSeries>
#include <QtCharts/QLegend>
#include <QtCharts/QBarCategoryAxis>
#include <QtCharts/QValueAxis>
#include <QVBoxLayout>
#include <QScrollArea>
#include <QJsonObject>
#include <QQueue>
#include <QDialogButtonBox>
#include <QPushButton>
static const auto kSlidingWindowSize = 30;
BitrateDialog::BitrateDialog(const QString &resource, double fps, const QJsonArray &data,
QWidget *parent)
: QDialog(parent)
{
setMinimumSize(400, 200);
setModal(true);
setWindowTitle(tr("Bitrate Viewer"));
setSizeGripEnabled(true);
double time = 0.0;
double maxSize = 0.0;
double firstTime = 0.0;
double keySubtotal = 0.0;
double interSubtotal = 0.0;
double totalKbps = 0.0;
double minKbps = std::numeric_limits<double>().max();
double maxKbps = 0.0;
int periodCount = 0;
double previousSecond = 0.0;
QQueue<double> window;
auto barSeries = new QStackedBarSeries;
auto averageLine = new QSplineSeries;
QBarSet *interSet = nullptr;
auto keySet = new QBarSet(fps > 0.0 ? "I" : tr("Audio"));
barSeries->setBarWidth(1.0);
if (fps > 0.0) {
interSet = new QBarSet("P/B");
barSeries->append(interSet);
}
barSeries->append(keySet);
averageLine->setName(tr("Average"));
for (int i = 0; i < data.size(); ++i) {
auto o = data[i].toObject();
auto pts = o["pts_time"].toString().toDouble();
auto duration = o["duration_time"].toString().toDouble();
auto size = o["size"].toString().toDouble() * 8.0 / 1000.0; // Kb
if (pts > 0.0)
time = pts + qMax(0.0, duration);
if (i == 0)
firstTime = time;
time -= firstTime;
if (o["flags"].toString()[0] == 'K') {
keySubtotal += size;
} else {
interSubtotal += size;
}
totalKbps += size;
// Every second as the period
if (time >= (previousSecond + 1.0) || (i + 1) == data.size()) {
// For the min, max, and overall average
auto kbps = interSubtotal + keySubtotal;
if (kbps < minKbps)
minKbps = kbps;
if (kbps > maxKbps)
maxKbps = kbps;
// Add a bar to the graph for each period
int n = qMax(1, int(time - previousSecond));
for (int j = 0; j < n; ++j) {
if (interSet)
interSet->append(interSubtotal);
keySet->append(keySubtotal);
++periodCount;
}
// For the smoothed average
while (window.size() >= kSlidingWindowSize)
window.dequeue();
window.enqueue(kbps);
double sum = 0.0;
for (auto &v : window)
sum += v;
// subtract 0.5 from the time because the X axis tick marks are centered
// under the bar such that "0s" is actually at 0.5s
averageLine->append(time - 0.5, sum / window.size());
// Reset counters
interSubtotal = 0.0;
keySubtotal = 0.0;
previousSecond = std::floor(time);
}
}
auto chart = new QChart();
chart->addSeries(barSeries);
chart->addSeries(averageLine);
chart->setTheme(Settings.theme() == "dark" ? QChart::ChartThemeDark : QChart::ChartThemeLight);
averageLine->setColor(Qt::yellow);
chart->setTitle(tr("Bitrates for %1 ~~ Avg. %2 Min. %3 Max. %4 Kb/s").arg(resource)
.arg(qRound(totalKbps / time)).arg(qRound(minKbps)).arg(qRound(maxKbps)));
auto axisX = new QValueAxis();
chart->addAxis(axisX, Qt::AlignBottom);
barSeries->attachAxis(axisX);
averageLine->attachAxis(axisX);
axisX->setRange(0.0, time);
axisX->setLabelFormat("%.0f s");
axisX->setTickType(QValueAxis::TicksDynamic);
axisX->setTickInterval(periodCount > 100 ? 10.0 : 5.0);
QValueAxis *axisY = new QValueAxis();
chart->addAxis(axisY, Qt::AlignLeft);
barSeries->attachAxis(axisY);
averageLine->attachAxis(axisY);
axisY->setRange(0.0, maxKbps);
axisY->setLabelFormat("%.0f Kb/s");
chart->legend()->setVisible(true);
chart->legend()->setAlignment(Qt::AlignBottom);
QChartView *chartView = new QChartView(chart);
chartView->setRenderHint(QPainter::Antialiasing);
setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
auto layout = new QVBoxLayout(this);
layout->setContentsMargins(0, 0, 8, 8);
layout->setSpacing(8);
auto scrollArea = new QScrollArea(this);
scrollArea->setWidget(chartView);
layout->addWidget(scrollArea);
auto buttons = new QDialogButtonBox(QDialogButtonBox::Save | QDialogButtonBox::Close, this);
buttons->button(QDialogButtonBox::Close)->setDefault(true);
layout->addWidget(buttons);
connect(buttons, &QDialogButtonBox::accepted, this, [ = ] {
QImage image(chartView->size(), QImage::Format_RGB32);
QPainter painter(&image);
painter.setRenderHint(QPainter::Antialiasing);
chartView->render(&painter);
painter.end();
SaveImageDialog(this, tr("Save Bitrate Graph"), image).exec();
});
connect(buttons, &QDialogButtonBox::rejected, this, &QDialog::reject);
chartView->setMinimumWidth(qMax(1010, periodCount * 5));
chartView->setMinimumHeight(520);
resize(1024, 576);
show();
}
| 6,545
|
C++
|
.cpp
| 161
| 32.627329
| 100
| 0.622754
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,162
|
actionsdialog.cpp
|
mltframework_shotcut/src/dialogs/actionsdialog.cpp
|
/*
* Copyright (c) 20222-2024 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "actionsdialog.h"
#include "widgets/statuslabelwidget.h"
#include <QDialogButtonBox>
#include <QHBoxLayout>
#include <QHeaderView>
#include <QKeySequenceEdit>
#include <QLineEdit>
#include <QSortFilterProxyModel>
#include <QStyledItemDelegate>
#include <QToolButton>
#include <QTreeView>
#include <QVBoxLayout>
#include <QAction>
#include <QPushButton>
#include <QKeyEvent>
static const unsigned int editorWidth = 180;
class ShortcutEditor : public QWidget
{
Q_OBJECT
public:
ShortcutEditor(QWidget *parent = nullptr)
: QWidget(parent)
{
setMinimumWidth(editorWidth);
setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
QHBoxLayout *layout = new QHBoxLayout(this);
layout->setContentsMargins(0, 0, 0, 0);
layout->setSpacing(0);
seqEdit = new QKeySequenceEdit();
layout->addWidget(seqEdit);
QToolButton *applyButton = new QToolButton();
applyButton->setIcon(QIcon::fromTheme("dialog-ok",
QIcon(":/icons/oxygen/32x32/actions/dialog-ok.png")));
applyButton->setText(tr("Apply"));
applyButton->setToolTip(tr("Apply"));
connect(applyButton, &QToolButton::clicked, this, [this]() {
emit applied();
});
layout->addWidget(applyButton);
QToolButton *defaultButton = new QToolButton();
defaultButton->setIcon(QIcon::fromTheme("edit-undo",
QIcon(":/icons/oxygen/32x32/actions/edit-undo.png")));
defaultButton->setText(tr("Set to default"));
defaultButton->setToolTip(tr("Set to default"));
connect(defaultButton, &QToolButton::clicked, this, [&]() {
seqEdit->setKeySequence(defaultSeq);
});
layout->addWidget(defaultButton);
QToolButton *clearButton = new QToolButton();
clearButton->setIcon(QIcon::fromTheme("edit-clear",
QIcon(":/icons/oxygen/32x32/actions/edit-clear.png")));
clearButton->setText(tr("Clear shortcut"));
clearButton->setToolTip(tr("Clear shortcut"));
connect(clearButton, &QToolButton::clicked, this, [&]() {
seqEdit->clear();
});
layout->addWidget(clearButton);
setLayout(layout);
QMetaObject::invokeMethod(seqEdit, "setFocus", Qt::QueuedConnection);
}
~ShortcutEditor() = default;
QKeySequenceEdit *seqEdit;
QKeySequence defaultSeq;
signals:
void applied();
};
class ShortcutItemDelegate : public QStyledItemDelegate
{
Q_OBJECT
public:
ShortcutItemDelegate(QObject *parent = nullptr)
: QStyledItemDelegate(parent)
{
}
QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
if (index.column() == ActionsModel::COLUMN_SEQUENCE1 ||
(index.column() == ActionsModel::COLUMN_SEQUENCE2
&& !index.data(ActionsModel::HardKeyRole).isValid() )) {
// Hard key shortcuts are in column 2 and are not editable.
m_currentEditor = new ShortcutEditor(parent);
connect(m_currentEditor, &ShortcutEditor::applied, this, [this]() {
auto dialog = static_cast<ActionsDialog *>(QObject::parent());
dialog->saveCurrentEditor();
});
m_currentEditor->setFocus();
return m_currentEditor;
}
return nullptr;
}
void destroyEditor(QWidget *editor, const QModelIndex &index) const
{
m_currentEditor = nullptr;
QStyledItemDelegate::destroyEditor(editor, index);
}
void setEditorData(QWidget *editor, const QModelIndex &index) const
{
ShortcutEditor *widget = dynamic_cast<ShortcutEditor *>(editor);
if (widget) {
widget->seqEdit->setKeySequence(index.data(Qt::EditRole).value<QKeySequence>());
widget->defaultSeq = index.data(ActionsModel::DefaultKeyRole).value<QKeySequence>();
}
}
void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
QKeySequence newSeq = static_cast<ShortcutEditor *>(editor)->seqEdit->keySequence();
model->setData(index, newSeq);
}
ShortcutEditor *currentEditor() const
{
return m_currentEditor;
}
private:
mutable ShortcutEditor *m_currentEditor = nullptr;
};
class KeyPressFilter : public QObject
{
Q_OBJECT
public:
KeyPressFilter(QObject *parent = 0) : QObject(parent) {}
protected:
bool eventFilter(QObject *obj, QEvent *event) override
{
if (event->type() == QEvent::KeyPress) {
auto keyEvent = static_cast<QKeyEvent *>(event);
if (!keyEvent->modifiers() && (keyEvent->key() == Qt::Key_Return
|| keyEvent->key() == Qt::Key_Enter)) {
auto window = static_cast<QWidget *>(parent());
window->close();
}
}
return QObject::eventFilter(obj, event);
}
};
class PrivateTreeView : public QTreeView
{
Q_OBJECT
public:
PrivateTreeView(QWidget *parent = nullptr) : QTreeView(parent) {}
virtual bool edit(const QModelIndex &index, QAbstractItemView::EditTrigger trigger,
QEvent *event) override
{
bool editInProgress = QTreeView::edit(index, trigger, event);
if (editInProgress && trigger == QAbstractItemView::AllEditTriggers &&
(index.column() == ActionsModel::COLUMN_SEQUENCE1
|| index.column() == ActionsModel::COLUMN_SEQUENCE2)) {
if (state() != QAbstractItemView::EditingState)
emit editRejected();
}
return editInProgress;
}
#ifdef Q_OS_MAC
virtual void keyPressEvent(QKeyEvent *event) override
{
if (event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) {
emit activated(currentIndex());
} else if (event->key() == Qt::Key_F2) {
edit(currentIndex(), QAbstractItemView::EditKeyPressed, event);
} else {
QAbstractItemView::keyPressEvent(event);
}
}
#endif
signals:
void editRejected();
};
class SearchKeyPressFilter : public QObject
{
Q_OBJECT
public:
SearchKeyPressFilter(QObject *parent = 0) : QObject(parent) {}
protected:
bool eventFilter(QObject *obj, QEvent *event) override
{
if (event->type() == QEvent::KeyPress) {
auto keyEvent = static_cast<QKeyEvent *>(event);
if (keyEvent->key() == Qt::Key_Down || keyEvent->key() == Qt::Key_Up) {
auto dialog = static_cast<ActionsDialog *>(parent());
dialog->focusSearchResults();
event->accept();
}
}
return QObject::eventFilter(obj, event);
}
};
// Include this so that ShortcutItemDelegate can be declared in the source file.
#include "actionsdialog.moc"
ActionsDialog::ActionsDialog(QWidget *parent)
: QDialog(parent)
{
setWindowTitle(tr("Actions and Shortcuts"));
setSizeGripEnabled(true) ;
QVBoxLayout *vlayout = new QVBoxLayout();
// Search Bar
QHBoxLayout *searchLayout = new QHBoxLayout();
m_searchField = new QLineEdit(this);
m_searchField->setPlaceholderText(tr("search"));
m_searchField->installEventFilter(new SearchKeyPressFilter(this));
connect(m_searchField, &QLineEdit::textChanged, this, [&](const QString & text) {
if (m_proxyModel) {
m_proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive);
m_proxyModel->setFilterFixedString(text);
}
});
connect(m_searchField, &QLineEdit::returnPressed, this, &ActionsDialog::focusSearchResults);
searchLayout->addWidget(m_searchField);
QToolButton *clearSearchButton = new QToolButton(this);
clearSearchButton->setIcon(QIcon::fromTheme("edit-clear",
QIcon(":/icons/oxygen/32x32/actions/edit-clear.png")));
clearSearchButton->setMaximumSize(22, 22);
clearSearchButton->setToolTip(tr("Clear search"));
clearSearchButton->setAutoRaise(true);
connect(clearSearchButton, &QAbstractButton::clicked, m_searchField, &QLineEdit::clear);
searchLayout->addWidget(clearSearchButton);
vlayout->addLayout(searchLayout);
m_proxyModel = new QSortFilterProxyModel(this);
m_proxyModel->setSourceModel(&m_model);
m_proxyModel->setFilterKeyColumn(-1);
// List
m_table = new PrivateTreeView();
m_table->setSelectionMode(QAbstractItemView::SingleSelection);
m_table->setItemsExpandable(false);
m_table->setRootIsDecorated(false);
m_table->setUniformRowHeights(true);
m_table->setSortingEnabled(true);
m_table->setEditTriggers(QAbstractItemView::SelectedClicked | QAbstractItemView::EditKeyPressed);
m_table->setItemDelegateForColumn(1, new ShortcutItemDelegate(this));
m_table->setItemDelegateForColumn(2, new ShortcutItemDelegate(this));
m_table->setModel(m_proxyModel);
m_table->setWordWrap(false);
m_table->setSortingEnabled(true);
m_table->header()->setStretchLastSection(false);
m_table->header()->setSectionResizeMode(0, QHeaderView::ResizeToContents);
m_table->header()->setSectionResizeMode(1, QHeaderView::QHeaderView::Fixed);
m_table->header()->setSectionResizeMode(2, QHeaderView::QHeaderView::Fixed);
m_table->header()->resizeSection(1, editorWidth);
m_table->header()->resizeSection(2, editorWidth);
m_table->sortByColumn(ActionsModel::COLUMN_ACTION, Qt::AscendingOrder);
m_table->installEventFilter(new KeyPressFilter(this));
connect(m_table->selectionModel(), &QItemSelectionModel::selectionChanged,
this, [&](const QItemSelection & selected, const QItemSelection & deselected) {
m_status->showText(tr("Click on the selected shortcut to show the editor"), 5, nullptr,
QPalette::AlternateBase);
});
connect(m_table, &PrivateTreeView::editRejected, this, [&]() {
m_status->showText(tr("Reserved shortcuts can not be edited"), 5, nullptr,
QPalette::AlternateBase);
});
connect(m_table->selectionModel(), &QItemSelectionModel::currentChanged,
this, [&](const QModelIndex & current) {
if (current.column() == 0) {
m_table->setCurrentIndex(m_proxyModel->index(current.row(), 1));
}
});
vlayout->addWidget(m_table);
QHBoxLayout *hlayout = new QHBoxLayout();
m_status = new StatusLabelWidget();
connect(&m_model, &ActionsModel::editError, this, [&](const QString & message) {
m_status->showText(message, 5, nullptr);
});
hlayout->addWidget(m_status);
// Button Box
QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Close);
buttonBox->button(QDialogButtonBox::Close)->setAutoDefault(false);
connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
hlayout->addWidget(buttonBox);
vlayout->addLayout(hlayout);
setLayout(vlayout);
connect(m_table, &QAbstractItemView::activated, this, [&](const QModelIndex & index) {
auto action = m_model.action(m_proxyModel->mapToSource(index));
if (action && action->isEnabled()) {
action->trigger();
}
});
int tableWidth = 38;
for (int i = 0; i < m_table->model()->columnCount(); i++) {
tableWidth += m_table->columnWidth(i);
}
resize(tableWidth, 600);
}
void ActionsDialog::saveCurrentEditor()
{
auto delegate = static_cast<ShortcutItemDelegate *>(m_table->itemDelegateForColumn(
m_table->currentIndex().column()));
if (delegate) {
auto editor = delegate->currentEditor();
if (editor && editor->seqEdit) {
m_proxyModel->setData(m_table->currentIndex(), editor->seqEdit->keySequence());
emit delegate->closeEditor(editor);
}
}
}
void ActionsDialog::focusSearchResults()
{
m_table->setCurrentIndex(m_proxyModel->index(0, 1));
m_table->setFocus();
}
void ActionsDialog::hideEvent(QHideEvent *event)
{
Q_UNUSED(event)
saveCurrentEditor();
}
void ActionsDialog::showEvent(QShowEvent *event)
{
Q_UNUSED(event)
m_searchField->setFocus();
m_searchField->clear();
m_table->clearSelection();
}
| 13,198
|
C++
|
.cpp
| 326
| 33.171779
| 103
| 0.658014
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,163
|
saveimagedialog.cpp
|
mltframework_shotcut/src/dialogs/saveimagedialog.cpp
|
/*
* Copyright (c) 2021-2023 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "saveimagedialog.h"
#include "mltcontroller.h"
#include "settings.h"
#include "util.h"
#include <Logger.h>
#include <QDebug>
#include <QtMath>
static QString suffixFromFilter(const QString &filterText)
{
QString suffix = filterText.section("*", 1, 1).section(")", 0, 0).section(" ", 0, 0);
if (!suffix.startsWith(".") ) {
suffix.clear();
}
return suffix;
}
SaveImageDialog::SaveImageDialog(QWidget *parent, const QString &caption, QImage &image)
: QFileDialog(parent, caption)
, m_image(image)
{
setModal(true);
setAcceptMode(QFileDialog::AcceptSave);
setFileMode(QFileDialog::AnyFile);
setOptions(Util::getFileDialogOptions());
setDirectory(Settings.savePath());
QString nameFilter =
tr("PNG (*.png);;BMP (*.bmp);;JPEG (*.jpg *.jpeg);;PPM (*.ppm);;TIFF (*.tif *.tiff);;WebP (*.webp);;All Files (*)");
setNameFilter(nameFilter);
QStringList nameFilters = nameFilter.split(";;");
QString suffix = Settings.exportFrameSuffix();
QString selectedNameFilter = nameFilters[0];
for (const auto &f : nameFilters) {
if (f.contains(suffix.toLower())) {
selectedNameFilter = f;
break;
}
}
selectNameFilter(selectedNameFilter);
// Use the current player time as a suggested file name
QString nameSuggestion = QStringLiteral("Shotcut_%1").arg(MLT.producer()->frame_time(
mlt_time_clock));
nameSuggestion = nameSuggestion.replace(":", "_");
nameSuggestion = nameSuggestion.replace(".", "_");
nameSuggestion += suffix;
selectFile(nameSuggestion);
#if !defined(Q_OS_WIN)
if (!connect(this, &QFileDialog::filterSelected, this, &SaveImageDialog::onFilterSelected))
connect(this, SIGNAL(filterSelected(const QString &)),
SLOT(const onFilterSelected(const QString &)));
#endif
if (!connect(this, &QFileDialog::fileSelected, this, &SaveImageDialog::onFileSelected))
connect(this, SIGNAL(fileSelected(const QString &)), SLOT(onFileSelected(const QString &)));
}
void SaveImageDialog::onFilterSelected(const QString &filter)
{
// When the file type filter is changed, automatically change
// the file extension to match.
if (filter.isEmpty()) {
return;
}
QString suffix = suffixFromFilter(filter);
if (suffix.isEmpty()) {
return; // All files
}
QStringList files = selectedFiles();
if (files.size() == 0) {
return;
}
QString filename = files[0];
// Strip the suffix from the current file name
if (!QFileInfo(filename).suffix().isEmpty()) {
filename = filename.section(".", 0, -2);
}
// Add the new suffix
filename += suffix;
selectFile(filename);
}
void SaveImageDialog::onFileSelected(const QString &file)
{
if (file.isEmpty()) {
return;
}
m_saveFile = file;
QFileInfo fi(m_saveFile);
if (fi.suffix().isEmpty()) {
QString suffix = suffixFromFilter(selectedNameFilter());
if ( suffix.isEmpty() ) {
suffix = ".png";
}
m_saveFile += suffix;
fi = QFileInfo(m_saveFile);
}
if (Util::warnIfNotWritable(m_saveFile, this, windowTitle()))
return;
// Convert to square pixels if needed.
qreal aspectRatio = (qreal) m_image.width() / m_image.height();
if (qFloor(aspectRatio * 1000) != qFloor(MLT.profile().dar() * 1000)) {
m_image = m_image.scaled(qRound(m_image.height() * MLT.profile().dar()), m_image.height(),
Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
}
m_image.save(m_saveFile, Q_NULLPTR, (fi.suffix() == "webp") ? 80 : -1);
Settings.setSavePath(fi.path());
Settings.setExportFrameSuffix(QStringLiteral(".") + fi.suffix());
}
| 4,552
|
C++
|
.cpp
| 119
| 32.605042
| 124
| 0.658526
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,164
|
multifileexportdialog.cpp
|
mltframework_shotcut/src/dialogs/multifileexportdialog.cpp
|
/*
* Copyright (c) 2021-2022 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "multifileexportdialog.h"
#include "mainwindow.h"
#include "proxymanager.h"
#include "shotcut_mlt_properties.h"
#include "util.h"
#include "qmltypes/qmlapplication.h"
#include <MltPlaylist.h>
#include <QComboBox>
#include <QDialogButtonBox>
#include <QDir>
#include <QFileDialog>
#include <QHBoxLayout>
#include <QGridLayout>
#include <QLabel>
#include <QLineEdit>
#include <QListWidget>
#include <QPushButton>
enum {
NAME_FIELD_NONE = 0,
NAME_FIELD_NAME,
NAME_FIELD_INDEX,
NAME_FIELD_DATE,
NAME_FIELD_HASH,
};
MultiFileExportDialog::MultiFileExportDialog(QString title, Mlt::Playlist *playlist,
const QString &directory, const QString &prefix, const QString &extension, QWidget *parent)
: QDialog(parent)
, m_playlist(playlist)
{
int col = 0;
setWindowTitle(title);
setWindowModality(QmlApplication::dialogModality());
QGridLayout *glayout = new QGridLayout();
glayout->setHorizontalSpacing(4);
glayout->setVerticalSpacing(2);
// Directory
glayout->addWidget(new QLabel(tr("Directory")), col, 0, Qt::AlignRight);
QHBoxLayout *dirHbox = new QHBoxLayout();
m_dir = new QLineEdit(QDir::toNativeSeparators(directory));
m_dir->setReadOnly(true);
QPushButton *browseButton = new QPushButton(this);
browseButton->setIcon(QIcon::fromTheme("document-open",
QIcon(":/icons/oxygen/32x32/actions/document-open.png")));
if (!connect(browseButton, &QAbstractButton::clicked, this, &MultiFileExportDialog::browse))
connect(browseButton, SIGNAL(clicked()), SLOT(browse()));
dirHbox->addWidget(m_dir);
dirHbox->addWidget(browseButton);
glayout->addLayout(dirHbox, col++, 1, Qt::AlignLeft);
// Prefix
glayout->addWidget(new QLabel(tr("Prefix")), col, 0, Qt::AlignRight);
m_prefix = new QLineEdit(prefix.isEmpty() ? tr("export") : prefix);
if (!connect(m_prefix, &QLineEdit::textChanged, this, &MultiFileExportDialog::rebuildList))
connect(m_prefix, SIGNAL(textChanged(const QString &)), SLOT(rebuildList()));
glayout->addWidget(m_prefix, col++, 1, Qt::AlignLeft);
// Field 1
glayout->addWidget(new QLabel(tr("Field 1")), col, 0, Qt::AlignRight);
m_field1 = new QComboBox();
fillCombo(m_field1);
if (!connect(m_field1, QOverload<int>::of(&QComboBox::activated), this,
&MultiFileExportDialog::rebuildList))
connect(m_field1, SIGNAL(activated(const QString &)), SLOT(rebuildList()));
glayout->addWidget(m_field1, col++, 1, Qt::AlignLeft);
// Field 2
glayout->addWidget(new QLabel(tr("Field 2")), col, 0, Qt::AlignRight);
m_field2 = new QComboBox();
fillCombo(m_field2);
if (!connect(m_field2, QOverload<int>::of(&QComboBox::activated), this,
&MultiFileExportDialog::rebuildList))
connect(m_field2, SIGNAL(activated(const QString &)), SLOT(rebuildList()));
glayout->addWidget(m_field2, col++, 1, Qt::AlignLeft);
// Field 3
glayout->addWidget(new QLabel(tr("Field 3")), col, 0, Qt::AlignRight);
m_field3 = new QComboBox();
fillCombo(m_field3);
m_field3->setCurrentIndex(NAME_FIELD_INDEX);
if (!connect(m_field3, QOverload<int>::of(&QComboBox::activated), this,
&MultiFileExportDialog::rebuildList))
connect(m_field3, SIGNAL(activated(const QString &)), SLOT(rebuildList()));
glayout->addWidget(m_field3, col++, 1, Qt::AlignLeft);
// Extension
glayout->addWidget(new QLabel(tr("Extension")), col, 0, Qt::AlignRight);
m_ext = new QLineEdit(extension);
if (!connect(m_ext, &QLineEdit::textChanged, this, &MultiFileExportDialog::rebuildList))
connect(m_ext, SIGNAL(textChanged(const QString &)), SLOT(rebuildList()));
glayout->addWidget(m_ext, col++, 1, Qt::AlignLeft);
// Error
m_errorIcon = new QLabel();
QIcon icon = QIcon(":/icons/oxygen/32x32/status/task-reject.png");
m_errorIcon->setPixmap(icon.pixmap(QSize(24, 24)));
glayout->addWidget(m_errorIcon, col, 0, Qt::AlignRight);
m_errorText = new QLabel();
glayout->addWidget(m_errorText, col++, 1, Qt::AlignLeft);
// List
m_list = new QListWidget();
m_list->setSelectionMode(QAbstractItemView::NoSelection);
m_list->setIconSize(QSize(16, 16));
glayout->addWidget(m_list, col++, 0, 1, 2);
// Buttons
m_buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
glayout->addWidget(m_buttonBox, col++, 0, 1, 2);
connect(m_buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
connect(m_buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
glayout->setColumnMinimumWidth(1,
fontMetrics().horizontalAdvance(m_dir->text()) + browseButton->width());
this->setLayout (glayout);
this->setModal(true);
rebuildList();
resize(400, 300);
}
QStringList MultiFileExportDialog::getExportFiles()
{
return m_stringList;
}
QString MultiFileExportDialog::appendField(QString text, QComboBox *combo, int clipIndex)
{
QString field;
switch (combo->currentData().toInt()) {
default:
case NAME_FIELD_NONE:
break;
case NAME_FIELD_NAME: {
QScopedPointer<Mlt::ClipInfo> info(MAIN.playlist()->clip_info(clipIndex));
if (info && info->producer && info->producer->is_valid()) {
field = info->producer->get(kShotcutCaptionProperty);
if (field.isEmpty()) {
field = ProxyManager::resource(*info->producer);
field = QFileInfo(field).completeBaseName();
}
if (field == "<producer>") {
field = QString::fromUtf8(info->producer->get("mlt_service"));
}
}
break;
}
case NAME_FIELD_INDEX: {
int digits = QString::number(m_playlist->count()).size();
field = QStringLiteral("%1").arg(clipIndex + 1, digits, 10, QChar('0'));
break;
}
case NAME_FIELD_DATE: {
QScopedPointer<Mlt::ClipInfo> info(MAIN.playlist()->clip_info(clipIndex));
if (info && info->producer && info->producer->is_valid()) {
int64_t ms = info->producer->get_creation_time();
if (ms) {
field = QDateTime::fromMSecsSinceEpoch(ms).toString("yyyyMMdd-HHmmss");
}
}
break;
}
case NAME_FIELD_HASH: {
QScopedPointer<Mlt::ClipInfo> info(MAIN.playlist()->clip_info(clipIndex));
field = Util::getHash(*info->producer);
break;
}
}
if (text.isEmpty()) {
return field;
} else if (field.isEmpty()) {
return text;
} else {
return text + "-" + field;
}
}
void MultiFileExportDialog::fillCombo(QComboBox *combo)
{
combo->addItem(tr("None"), QVariant(NAME_FIELD_NONE));
combo->addItem(tr("Name"), QVariant(NAME_FIELD_NAME));
combo->addItem(tr("Index"), QVariant(NAME_FIELD_INDEX));
combo->addItem(tr("Date"), QVariant(NAME_FIELD_DATE));
combo->addItem(tr("Hash"), QVariant(NAME_FIELD_HASH));
}
void MultiFileExportDialog::rebuildList()
{
m_stringList.clear();
m_list->clear();
for (int i = 0; i < m_playlist->count(); i++) {
QString filename = m_prefix->text();
filename = appendField(filename, m_field1, i);
filename = appendField(filename, m_field2, i);
filename = appendField(filename, m_field3, i);
if (!filename.isEmpty()) {
filename = m_dir->text() + QDir::separator() + filename + "." + m_ext->text();
m_stringList << filename;
}
}
m_list->addItems(m_stringList);
// Detect Errors
m_errorText->setText("");
int n = m_stringList.size();
if (n == 0) {
m_errorText->setText(tr("Empty File Name"));
} else if (!QDir(m_dir->text()).exists()) {
m_errorText->setText(tr("Directory does not exist: %1").arg(m_dir->text()));
} else {
// Search for existing or duplicate files
for (int i = 0; i < n; i++) {
QString errorString;
QFileInfo fileInfo(m_stringList[i]);
if (fileInfo.exists()) {
errorString = tr("File Exists: %1").arg(m_stringList[i]);
} else {
for (int j = 0; j < n; j++) {
if (j != i && m_stringList[i] == m_stringList[j]) {
QString filename = QFileInfo(m_stringList[i]).fileName();
errorString = tr("Duplicate File Name: %1").arg(filename);
break;
}
}
}
QListWidgetItem *item = m_list->item(i);
if (errorString.isEmpty()) {
item->setIcon(QIcon(":/icons/oxygen/32x32/status/task-complete.png"));
} else {
item->setIcon(QIcon(":/icons/oxygen/32x32/status/task-reject.png"));
item->setToolTip(errorString);
m_errorText->setText(errorString);
}
}
}
if (m_errorText->text().isEmpty()) {
m_errorText->setVisible(false);
m_errorIcon->setVisible(false);
m_buttonBox->button(QDialogButtonBox::Ok)->setEnabled(true);
} else {
m_errorText->setVisible(true);
m_errorIcon->setVisible(true);
m_buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
}
m_buttonBox->button(QDialogButtonBox::Ok)->setToolTip(tr("Fix file name errors before export."));
}
void MultiFileExportDialog::browse()
{
QString directory = QDir::toNativeSeparators(QFileDialog::getExistingDirectory(this,
tr("Export Directory"), m_dir->text(), Util::getFileDialogOptions()));
if (!directory.isEmpty()) {
m_dir->setText(directory);
rebuildList();
}
}
| 10,596
|
C++
|
.cpp
| 255
| 34.2
| 153
| 0.629784
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,165
|
slideshowgeneratordialog.cpp
|
mltframework_shotcut/src/dialogs/slideshowgeneratordialog.cpp
|
/*
* Copyright (c) 2020 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "slideshowgeneratordialog.h"
#include "Logger.h"
#include "widgets/slideshowgeneratorwidget.h"
#include <MltProfile.h>
#include <MltTransition.h>
#include <QDebug>
#include <QDialogButtonBox>
#include <QVBoxLayout>
SlideshowGeneratorDialog::SlideshowGeneratorDialog(QWidget *parent, Mlt::Playlist &clips)
: QDialog(parent)
{
setWindowTitle(tr("Slideshow Generator - %n Clips", nullptr, clips.count()));
QVBoxLayout *VLayout = new QVBoxLayout(this);
m_sWidget = new SlideshowGeneratorWidget(&clips, this);
VLayout->addWidget(m_sWidget);
m_buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Close);
VLayout->addWidget(m_buttonBox);
connect(m_buttonBox, SIGNAL(clicked(QAbstractButton *)), this, SLOT(clicked(QAbstractButton *)));
setLayout(VLayout);
setModal(true);
layout()->setSizeConstraint(QLayout::SetFixedSize);
}
Mlt::Playlist *SlideshowGeneratorDialog::getSlideshow()
{
return m_sWidget->getSlideshow();
}
void SlideshowGeneratorDialog::clicked(QAbstractButton *button)
{
QDialogButtonBox::ButtonRole role = m_buttonBox->buttonRole(button);
if (role == QDialogButtonBox::AcceptRole) {
LOG_DEBUG() << "Accept";
accept();
} else if (role == QDialogButtonBox::RejectRole) {
LOG_DEBUG() << "Reject";
reject();
} else {
LOG_DEBUG() << "Unknown role" << role;
}
}
| 2,108
|
C++
|
.cpp
| 55
| 34.890909
| 101
| 0.734574
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
13,166
|
alignaudiodialog.cpp
|
mltframework_shotcut/src/dialogs/alignaudiodialog.cpp
|
/*
* Copyright (c) 2022 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "alignaudiodialog.h"
#include "mainwindow.h"
#include "commands/timelinecommands.h"
#include "dialogs/alignmentarray.h"
#include "dialogs/longuitask.h"
#include "mltcontroller.h"
#include "proxymanager.h"
#include "settings.h"
#include "shotcut_mlt_properties.h"
#include "util.h"
#include "models/multitrackmodel.h"
#include "qmltypes/qmlapplication.h"
#include <Logger.h>
#include <QApplication>
#include <QCheckBox>
#include <QComboBox>
#include <QDialogButtonBox>
#include <QGridLayout>
#include <QHBoxLayout>
#include <QHeaderView>
#include <QIcon>
#include <QLabel>
#include <QLocale>
#include <QPainter>
#include <QPushButton>
#include <QStyledItemDelegate>
#include <QTreeView>
class AudioReader : public QObject
{
Q_OBJECT
public:
AudioReader(QString producerXml, AlignmentArray *array, int in = -1, int out = -1)
: QObject()
, m_producerXml(producerXml)
, m_array(array)
, m_in(in)
, m_out(out)
{
}
void init(int maxLength)
{
m_array->init(maxLength);
}
void process()
{
QScopedPointer<Mlt::Producer> producer(new Mlt::Producer(MLT.profile(), "xml-string",
m_producerXml.toUtf8().constData()));
if (m_in >= 0) {
producer->set_in_and_out(m_in, m_out);
}
size_t frameCount = producer->get_playtime();
std::vector<double> values(frameCount);
int progress = 0;
for (size_t i = 0; i < frameCount; ++i) {
int frequency = 48000;
int channels = 1;
mlt_audio_format format = mlt_audio_s16;
std::unique_ptr<Mlt::Frame> frame(producer->get_frame(i));
mlt_position position = mlt_frame_get_position(frame->get_frame());
int samples = mlt_audio_calculate_frame_samples(float(producer->get_fps()), frequency, position);
int16_t *data = static_cast<int16_t *>(frame->get_audio(format, frequency, channels, samples));
double sampleTotal = 0;
// Add all values from the frame
for (int k = 0; k < samples; ++k) {
sampleTotal += std::abs(data[k]);
}
// Average the sample values
values[i] = sampleTotal / samples;
int newProgress = 100 * i / frameCount;
if (newProgress != progress) {
progress = newProgress;
emit progressUpdate(progress);
}
}
m_array->setValues(values);
}
signals:
void progressUpdate(int);
private:
QString m_producerXml;
AlignmentArray *m_array;
int m_in;
int m_out;
};
class ClipAudioReader : public QObject
{
Q_OBJECT
public:
ClipAudioReader(QString producerXml, AlignmentArray &referenceArray, int index, int in, int out)
: QObject()
, m_referenceArray(referenceArray)
, m_reader(producerXml, &m_clipArray, in, out)
, m_index(index)
{
connect(&m_reader, SIGNAL(progressUpdate(int)), this, SLOT(onReaderProgressUpdate(int)));
}
void init(int maxLength)
{
m_reader.init(maxLength);
}
void start()
{
m_future = QtConcurrent::run(&ClipAudioReader::process, this);
}
bool isFinished()
{
return m_future.isFinished();
}
void process()
{
onReaderProgressUpdate(0);
m_reader.process();
double speed = 1.0;
int offset = 0;
double quality;
double speedRange = Settings.audioReferenceSpeedRange();
if (speedRange != 0.0) {
quality = m_referenceArray.calculateOffsetAndSpeed(m_clipArray, &speed, &offset, speedRange);
} else {
quality = m_referenceArray.calculateOffset(m_clipArray, &offset);
}
onReaderProgressUpdate(100);
emit finished(m_index, offset, speed, quality);
}
public slots:
void onReaderProgressUpdate(int progress)
{
progress = progress * 99 / 100; // Reader goes from 0-99
emit progressUpdate(m_index, progress);
}
signals:
void progressUpdate(int index, int percent);
void finished(int index, int offset, double speed, double quality);
private:
AlignmentArray m_clipArray;
AlignmentArray &m_referenceArray;
AudioReader m_reader;
int m_index;
QFuture<void> m_future;
bool m_calculateSpeed;
};
class AlignTableDelegate : public QStyledItemDelegate
{
Q_OBJECT
public:
void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
const AlignClipsModel *model = dynamic_cast<const AlignClipsModel *>(index.model());
switch (index.column()) {
case AlignClipsModel::COLUMN_ERROR: {
QIcon icon;
if (!index.data().toString().isEmpty()) {
icon = QIcon(":/icons/oxygen/32x32/status/task-reject.png");
} else if (model->getProgress(index.row()) == 100) {
icon = QIcon(":/icons/oxygen/32x32/status/task-complete.png");
}
icon.paint(painter, option.rect, Qt::AlignCenter);
break;
}
case AlignClipsModel::COLUMN_NAME: {
int progress = model->getProgress(index.row());
if (progress > 0 ) {
QStyleOptionProgressBar progressBarOption;
progressBarOption.rect = option.rect;
progressBarOption.minimum = 0;
progressBarOption.maximum = 100;
progressBarOption.progress = progress;
QApplication::style()->drawControl(QStyle::CE_ProgressBar, &progressBarOption, painter);
}
painter->drawText(option.rect, Qt::AlignLeft | Qt::AlignVCenter, index.data().toString() );
break;
}
case AlignClipsModel::COLUMN_OFFSET:
case AlignClipsModel::COLUMN_SPEED:
QStyledItemDelegate::paint(painter, option, index);
break;
default:
LOG_ERROR() << "Invalid Column" << index.row() << index.column();
break;
}
}
};
// Include this so that AlignTableDelegate can be declared in the source file.
#include "alignaudiodialog.moc"
AlignAudioDialog::AlignAudioDialog(QString title, MultitrackModel *model,
const QVector<QUuid> &uuids, QWidget *parent)
: QDialog(parent)
, m_model(model)
, m_uuids(uuids)
, m_uiTask(nullptr)
{
int row = 0;
setWindowTitle(title);
setWindowModality(QmlApplication::dialogModality());
QGridLayout *glayout = new QGridLayout();
glayout->setHorizontalSpacing(4);
glayout->setVerticalSpacing(2);
// Track Combo
glayout->addWidget(new QLabel(tr("Reference audio track")), row, 0, Qt::AlignRight);
m_trackCombo = new QComboBox();
int trackCount = m_model->trackList().size();
for (int i = 0; i < trackCount; i++) {
m_trackCombo->addItem(m_model->getTrackName(i), QVariant(i));
}
int defaultTrack = Settings.audioReferenceTrack();
if (defaultTrack < trackCount) {
m_trackCombo->setCurrentIndex(defaultTrack);
}
if (!connect(m_trackCombo, QOverload<int>::of(&QComboBox::activated), this,
&AlignAudioDialog::rebuildClipList))
connect(m_trackCombo, SIGNAL(activated(const QString &)), SLOT(rebuildClipList()));
glayout->addWidget(m_trackCombo, row++, 1, Qt::AlignLeft);
// Speed combo box
glayout->addWidget(new QLabel(tr("Speed adjustment range")), row, 0, Qt::AlignRight);
m_speedCombo = new QComboBox();
m_speedCombo->setToolTip("Larger speed adjustment ranges take longer to process.");
m_speedCombo->addItem(tr("None") + QStringLiteral(" (%L1%)").arg(0), QVariant(0));
m_speedCombo->addItem(tr("Narrow") + QStringLiteral(" (%L1%)").arg((double)0.1, 0, 'g', 2),
QVariant(0.001));
m_speedCombo->addItem(tr("Normal") + QStringLiteral(" (%L1%)").arg((double)0.5, 0, 'g', 2),
QVariant(0.005));
m_speedCombo->addItem(tr("Wide") + QStringLiteral(" (%L1%)").arg(1), QVariant(0.01));
m_speedCombo->addItem(tr("Very wide") + QStringLiteral(" (%L1%)").arg(5), QVariant(0.05));
double defaultRange = Settings.audioReferenceSpeedRange();
for (int i = 0; i < m_speedCombo->count(); i++) {
if (m_speedCombo->itemData(i).toDouble() == defaultRange) {
m_speedCombo->setCurrentIndex(i);
break;
}
}
if (!connect(m_speedCombo, QOverload<int>::of(&QComboBox::activated), this,
&AlignAudioDialog::rebuildClipList))
connect(m_speedCombo, SIGNAL(activated(const QString &)), SLOT(rebuildClipList()));
glayout->addWidget(m_speedCombo, row++, 1, Qt::AlignLeft);
// List
m_table = new QTreeView();
m_table->setSelectionMode(QAbstractItemView::NoSelection);
m_table->setItemsExpandable(false);
m_table->setRootIsDecorated(false);
m_table->setUniformRowHeights(true);
m_table->setSortingEnabled(false);
m_table->setModel(&m_alignClipsModel);
m_table->setWordWrap(false);
m_delegate = new AlignTableDelegate();
m_table->setItemDelegate(m_delegate);
m_table->header()->setStretchLastSection(false);
qreal rowHeight = fontMetrics().height() * devicePixelRatioF();
m_table->header()->setMinimumSectionSize(rowHeight);
m_table->header()->setSectionResizeMode(AlignClipsModel::COLUMN_ERROR, QHeaderView::Fixed);
m_table->setColumnWidth(AlignClipsModel::COLUMN_ERROR, rowHeight);
m_table->header()->setSectionResizeMode(AlignClipsModel::COLUMN_NAME, QHeaderView::Stretch);
m_table->header()->setSectionResizeMode(AlignClipsModel::COLUMN_OFFSET, QHeaderView::Fixed);
m_table->setColumnWidth(AlignClipsModel::COLUMN_OFFSET,
fontMetrics().horizontalAdvance("-00:00:00:00") * devicePixelRatioF() + 8);
m_table->header()->setSectionResizeMode(AlignClipsModel::COLUMN_SPEED,
QHeaderView::ResizeToContents);
glayout->addWidget(m_table, row++, 0, 1, 2);
// Button Box + cancel
m_buttonBox = new QDialogButtonBox(QDialogButtonBox::Cancel);
connect(m_buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
glayout->addWidget(m_buttonBox, row++, 0, 1, 2);
// Process button
QPushButton *processButton = m_buttonBox->addButton(tr("Process"), QDialogButtonBox::ActionRole);
connect(processButton, SIGNAL(pressed()), this, SLOT(process()));
// Apply button
m_applyButton = m_buttonBox->addButton(tr("Apply"), QDialogButtonBox::ApplyRole);
connect(m_applyButton, SIGNAL(pressed()), this, SLOT(apply()));
// Process and apply button
m_processAndApplyButton = m_buttonBox->addButton(tr("Process + Apply"),
QDialogButtonBox::AcceptRole);
connect(m_processAndApplyButton, SIGNAL(pressed()), this, SLOT(processAndApply()));
this->setLayout (glayout);
this->setModal(true);
rebuildClipList();
resize(500, 300);
}
AlignAudioDialog::~AlignAudioDialog()
{
delete m_delegate;
delete m_uiTask;
}
void AlignAudioDialog::rebuildClipList()
{
QStringList stringList;
m_alignClipsModel.clear();
int referenceIndex = m_trackCombo->currentData().toInt();
Settings.setAudioReferenceTrack(referenceIndex);
Settings.setAudioReferenceSpeedRange(m_speedCombo->currentData().toDouble());
m_applyButton->setEnabled(false);
for (const auto &uuid : m_uuids) {
int trackIndex, clipIndex;
auto info = m_model->findClipByUuid(uuid, trackIndex, clipIndex);
if (info && info->cut && info->cut->is_valid()) {
QString error;
QString clipName = info->producer->get(kShotcutCaptionProperty);
if (clipName.isNull() || clipName.isEmpty())
clipName = Util::baseName(ProxyManager::resource(*info->producer));
if (clipName == "<producer>" || clipName.isNull() || clipName.isEmpty())
clipName = QString::fromUtf8(info->producer->get("mlt_service"));
if (trackIndex == referenceIndex) {
error = tr("This clip will be skipped because it is on the reference track.");
} else {
// Only support avformat clips
QString shotcutProducer(info->producer->get(kShotcutProducerProperty));
QString service(info->producer->get("mlt_service"));
if (!service.startsWith("avformat") && !shotcutProducer.startsWith("avformat"))
error = tr("This item can not be aligned.");
}
m_alignClipsModel.addClip(clipName, AlignClipsModel::INVALID_OFFSET,
AlignClipsModel::INVALID_OFFSET, error);
}
}
}
void AlignAudioDialog::process()
{
m_uiTask = new LongUiTask(tr("Align Audio"));
m_uiTask->setMinimumDuration(0);
int referenceTrackIndex = m_trackCombo->currentData().toInt();
auto mlt_index = m_model->trackList().at(referenceTrackIndex).mlt_index;
QScopedPointer<Mlt::Producer> track(m_model->tractor()->track(mlt_index));
int maxLength = track->get_playtime();
bool validClip = false;
QString xml = MLT.XML(track.data());
AlignmentArray trackArray;
AudioReader trackReader(MLT.XML(track.data()), &trackArray);
connect(&trackReader, SIGNAL(progressUpdate(int)), this, SLOT(updateReferenceProgress(int)));
QList<ClipAudioReader *> m_clipReaders;
for (const auto &uuid : m_uuids) {
int trackIndex, clipIndex;
auto info = m_model->findClipByUuid(uuid, trackIndex, clipIndex);
if (!info || !info->cut || !info->cut->is_valid()) {
continue;
}
QString shotcutProducer(info->producer->get(kShotcutProducerProperty));
QString service(info->producer->get("mlt_service"));
if (!service.startsWith("avformat") && !shotcutProducer.startsWith("avformat")) {
m_clipReaders.append(nullptr);
} else if (trackIndex == referenceTrackIndex) {
m_clipReaders.append(nullptr);
} else {
QString xml = MLT.XML(info->cut);
ClipAudioReader *clipReader = new ClipAudioReader(xml, trackArray, m_clipReaders.size(),
info->frame_in, info->frame_out);
connect(clipReader, SIGNAL(progressUpdate(int, int)), this, SLOT(updateClipProgress(int, int)));
connect(clipReader, SIGNAL(finished(int, int, double, double)), this, SLOT(clipFinished(int, int,
double, double)));
m_clipReaders.append(clipReader);
maxLength = qMax(maxLength, info->frame_count);
validClip = true;
}
}
if (!validClip) {
m_uiTask->deleteLater();
m_uiTask = nullptr;
return;
}
trackReader.init(maxLength);
for (const auto &clipReader : m_clipReaders) {
if (clipReader) clipReader->init(maxLength);
}
trackReader.process();
for (const auto &clipReader : m_clipReaders) {
if (clipReader) clipReader->start();
}
for (const auto &clipReader : m_clipReaders) {
if (clipReader) {
while (!clipReader->isFinished()) {
QThread::msleep(10);
QCoreApplication::processEvents();
}
clipReader->deleteLater();
}
}
m_uiTask->deleteLater();
m_uiTask = nullptr;
m_applyButton->setEnabled(true);
}
void AlignAudioDialog::apply()
{
Timeline::AlignClipsCommand *command = new Timeline::AlignClipsCommand(*m_model);
int referenceTrackIndex = m_trackCombo->currentData().toInt();
int alignmentCount = 0;
int modelIndex = 0;
for (const auto &uuid : m_uuids) {
int trackIndex, clipIndex;
auto info = m_model->findClipByUuid(uuid, trackIndex, clipIndex);
if (!info || !info->cut || !info->cut->is_valid()) {
continue;
}
if (trackIndex != referenceTrackIndex) {
int offset = m_alignClipsModel.getOffset(modelIndex);
if (offset != AlignClipsModel::INVALID_OFFSET) {
double speedCompensation = m_alignClipsModel.getSpeed(modelIndex);
command->addAlignment(uuid, offset, speedCompensation);
alignmentCount++;
}
}
modelIndex++;
}
if (alignmentCount > 0) {
MAIN.undoStack()->push(command);
} else {
delete command;
}
accept();
}
void AlignAudioDialog::processAndApply()
{
process();
apply();
}
void AlignAudioDialog::updateReferenceProgress(int percent)
{
if (m_uiTask) {
m_uiTask->reportProgress(tr("Analyze Reference Track"), percent, 100);
}
}
void AlignAudioDialog::updateClipProgress(int index, int percent)
{
m_alignClipsModel.updateProgress(index, percent);
if (m_uiTask) {
m_uiTask->reportProgress(tr("Analyze Clips"), 0, 0);
}
}
void AlignAudioDialog::clipFinished(int index, int offset, double speed, double quality)
{
QString error;
LOG_INFO() << "Clip" << index << "Offset:" << offset << "Speed:" << speed << "Quality:" << quality;
if (quality < 0.01) {
error = tr("Alignment not found.");
offset = AlignClipsModel::INVALID_OFFSET;
speed = AlignClipsModel::INVALID_OFFSET;
}
m_alignClipsModel.updateOffsetAndSpeed(index, offset, speed, error);
m_alignClipsModel.updateProgress(index, 100);
}
| 18,404
|
C++
|
.cpp
| 452
| 32.869469
| 118
| 0.636562
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,167
|
customprofiledialog.cpp
|
mltframework_shotcut/src/dialogs/customprofiledialog.cpp
|
/*
* Copyright (c) 2013-2024 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "customprofiledialog.h"
#include "ui_customprofiledialog.h"
#include "mltcontroller.h"
#include "settings.h"
#include "util.h"
#include <QDir>
#include <QDesktopServices>
#include <QRegularExpression>
CustomProfileDialog::CustomProfileDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::CustomProfileDialog),
m_fps(0.0)
{
ui->setupUi(this);
ui->widthSpinner->setValue(MLT.profile().width());
ui->heightSpinner->setValue(MLT.profile().height());
ui->aspectNumSpinner->setValue(MLT.profile().display_aspect_num());
ui->aspectDenSpinner->setValue(MLT.profile().display_aspect_den());
ui->fpsSpinner->setValue(MLT.profile().fps());
ui->scanModeCombo->setCurrentIndex(MLT.profile().progressive());
ui->colorspaceCombo->setCurrentIndex(MLT.profile().colorspace() == 709);
}
CustomProfileDialog::~CustomProfileDialog()
{
delete ui;
}
QString CustomProfileDialog::profileName() const
{
// Replace characters that are not allowed in Windows file names
QString filename = ui->nameEdit->text();
static QRegularExpression re("[" + QRegularExpression::escape( "\\/:*?\"<>|" ) + "]");
filename = filename.replace(re, QStringLiteral( "_" ));
return filename;
}
void CustomProfileDialog::on_buttonBox_accepted()
{
MLT.profile().set_explicit(1);
MLT.profile().set_width(ui->widthSpinner->value());
MLT.profile().set_height(ui->heightSpinner->value());
MLT.profile().set_display_aspect(ui->aspectNumSpinner->value(), ui->aspectDenSpinner->value());
QSize sar(ui->aspectNumSpinner->value() * ui->heightSpinner->value(),
ui->aspectDenSpinner->value() * ui->widthSpinner->value());
auto gcd = Util::greatestCommonDivisor(sar.width(), sar.height());
MLT.profile().set_sample_aspect(sar.width() / gcd, sar.height() / gcd);
int numerator, denominator;
Util::normalizeFrameRate(ui->fpsSpinner->value(), numerator, denominator);
MLT.profile().set_frame_rate(numerator, denominator);
MLT.profile().set_progressive(ui->scanModeCombo->currentIndex());
MLT.profile().set_colorspace((ui->colorspaceCombo->currentIndex() == 1) ? 709 : 601);
MLT.updatePreviewProfile();
MLT.setPreviewScale(Settings.playerPreviewScale());
// Save it to a file
if (!ui->nameEdit->text().isEmpty()) {
QDir dir(Settings.appDataLocation());
QString subdir("profiles");
if (!dir.exists())
dir.mkpath(dir.path());
if (!dir.cd(subdir)) {
if (dir.mkdir(subdir))
dir.cd(subdir);
}
Mlt::Properties p;
p.set("width", MLT.profile().width());
p.set("height", MLT.profile().height());
p.set("sample_aspect_num", MLT.profile().sample_aspect_num());
p.set("sample_aspect_den", MLT.profile().sample_aspect_den());
p.set("display_aspect_num", MLT.profile().display_aspect_num());
p.set("display_aspect_den", MLT.profile().display_aspect_den());
p.set("progressive", MLT.profile().progressive());
p.set("colorspace", MLT.profile().colorspace());
p.set("frame_rate_num", MLT.profile().frame_rate_num());
p.set("frame_rate_den", MLT.profile().frame_rate_den());
p.save(dir.filePath(profileName()).toUtf8().constData());
}
}
void CustomProfileDialog::on_widthSpinner_editingFinished()
{
ui->widthSpinner->setValue(Util::coerceMultiple(ui->widthSpinner->value()));
}
void CustomProfileDialog::on_heightSpinner_editingFinished()
{
ui->heightSpinner->setValue(Util::coerceMultiple(ui->heightSpinner->value()));
}
void CustomProfileDialog::on_fpsSpinner_editingFinished()
{
if (ui->fpsSpinner->value() != m_fps) {
const QString caption(tr("Video Mode Frames/sec"));
if (ui->fpsSpinner->value() == 23.98 || ui->fpsSpinner->value() == 23.976) {
Util::showFrameRateDialog(caption, 24000, ui->fpsSpinner, this);
} else if (ui->fpsSpinner->value() == 29.97) {
Util::showFrameRateDialog(caption, 30000, ui->fpsSpinner, this);
} else if (ui->fpsSpinner->value() == 47.95) {
Util::showFrameRateDialog(caption, 48000, ui->fpsSpinner, this);
} else if (ui->fpsSpinner->value() == 59.94) {
Util::showFrameRateDialog(caption, 60000, ui->fpsSpinner, this);
}
m_fps = ui->fpsSpinner->value();
}
}
void CustomProfileDialog::on_fpsComboBox_textActivated(const QString &arg1)
{
if (arg1.isEmpty()) return;
ui->fpsSpinner->setValue(arg1.toDouble());
}
void CustomProfileDialog::on_resolutionComboBox_textActivated(const QString &arg1)
{
if (arg1.isEmpty()) return;
auto parts = arg1.split(' ');
ui->widthSpinner->setValue(parts[0].toInt());
ui->heightSpinner->setValue(parts[2].toInt());
}
void CustomProfileDialog::on_aspectRatioComboBox_textActivated(const QString &arg1)
{
if (arg1.isEmpty()) return;
auto parts = arg1.split(' ')[0].split(':');
ui->aspectNumSpinner->setValue(parts[0].toInt());
ui->aspectDenSpinner->setValue(parts[1].toInt());
}
| 5,763
|
C++
|
.cpp
| 134
| 38.179104
| 99
| 0.683461
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,168
|
textviewerdialog.cpp
|
mltframework_shotcut/src/dialogs/textviewerdialog.cpp
|
/*
* Copyright (c) 2012-2024 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "textviewerdialog.h"
#include "ui_textviewerdialog.h"
#include "settings.h"
#include "util.h"
#include <QFileDialog>
#include <QPushButton>
#include <QClipboard>
#include <QScrollBar>
TextViewerDialog::TextViewerDialog(QWidget *parent, bool forMltXml) :
QDialog(parent),
ui(new Ui::TextViewerDialog),
m_forMltXml(forMltXml)
{
ui->setupUi(this);
auto button = ui->buttonBox->addButton(tr("Copy"), QDialogButtonBox::ActionRole);
connect(button, &QAbstractButton::clicked, this, [&]() {
QGuiApplication::clipboard()->setText(ui->plainTextEdit->toPlainText());
});
}
TextViewerDialog::~TextViewerDialog()
{
delete ui;
}
void TextViewerDialog::setText(const QString &s, bool scroll)
{
if (s != ui->plainTextEdit->toPlainText()) {
ui->plainTextEdit->setPlainText(s);
if (scroll)
ui->plainTextEdit->verticalScrollBar()->setValue(ui->plainTextEdit->verticalScrollBar()->maximum());
}
}
QDialogButtonBox *TextViewerDialog::buttonBox() const
{
return ui->buttonBox;
}
void TextViewerDialog::on_buttonBox_accepted()
{
QString path = Settings.savePath();
QString caption = tr("Save Text");
QString nameFilter = tr("Text Documents (*.txt);;All Files (*)");
if (m_forMltXml) {
nameFilter = tr("MLT XML (*.mlt);;All Files (*)");
}
QString filename = QFileDialog::getSaveFileName(this, caption, path, nameFilter,
nullptr, Util::getFileDialogOptions());
if (!filename.isEmpty()) {
QFileInfo fi(filename);
if (fi.suffix().isEmpty()) {
if (m_forMltXml)
filename += ".mlt";
else
filename += ".txt";
}
if (Util::warnIfNotWritable(filename, this, caption))
return;
QFile f(filename);
f.open(QIODevice::WriteOnly | QIODevice::Text);
f.write(ui->plainTextEdit->toPlainText().toUtf8());
f.close();
}
}
| 2,695
|
C++
|
.cpp
| 77
| 29.766234
| 112
| 0.669858
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,169
|
transcribeaudiodialog.cpp
|
mltframework_shotcut/src/dialogs/transcribeaudiodialog.cpp
|
/*
* Copyright (c) 2024 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "transcribeaudiodialog.h"
#include "docks/timelinedock.h"
#include "Logger.h"
#include "mainwindow.h"
#include "shotcut_mlt_properties.h"
#include "util.h"
#include "qmltypes/qmlapplication.h"
#include <MltProducer.h>
#include <QCheckBox>
#include <QComboBox>
#include <QDialogButtonBox>
#include <QFileDialog>
#include <QGridLayout>
#include <QLabel>
#include <QLineEdit>
#include <QListWidget>
#include <QPushButton>
#include <QSpinBox>
// List of supported languages from whispercpp
static const std::vector<const char *> whisperLanguages = {
"en", "zh", "de", "es", "ru", "ko", "fr", "ja", "pt", "tr",
"pl", "ca", "nl", "ar", "sv", "it", "id", "hi", "fi", "vi",
"he", "uk", "el", "ms", "cs", "ro", "da", "hu", "ta", "no",
"th", "ur", "hr", "bg", "lt", "la", "mi", "ml", "cy", "sk",
"te", "fa", "lv", "bn", "sr", "az", "sl", "kn", "et", "mk",
"br", "eu", "is", "hy", "ne", "mn", "bs", "kk", "sq", "sw",
"gl", "mr", "pa", "si", "km", "sn", "yo", "so", "af", "oc",
"ka", "be", "tg", "sd", "gu", "am", "yi", "lo", "uz", "fo",
"ht", "ps", "tk", "nn", "mt", "sa", "lb", "my", "bo", "tl",
"mg", "as", "tt", "haw", "ln", "ha", "ba", "jw", "su", "yue",
};
static void fillLanguages(QComboBox *combo)
{
QMap<QString, QString> codeMap;
for (int i = 0; i < whisperLanguages.size(); i++) {
QString langCode = whisperLanguages[i];
QLocale::Language lang = QLocale::codeToLanguage(langCode);
if (lang == QLocale::AnyLanguage) {
LOG_ERROR() << "Language not found" << langCode;
continue;
}
QString langStr = QLocale::languageToString(lang);
if (!langCode.isEmpty() && !langStr.isEmpty()) {
codeMap.insert(langStr, langCode);
}
}
for (auto it = codeMap.keyValueBegin(); it != codeMap.keyValueEnd(); ++it) {
combo->addItem(it->first, it->second);
}
}
TranscribeAudioDialog::TranscribeAudioDialog(const QString &trackName, QWidget *parent)
: QDialog(parent)
{
setWindowTitle(tr("Speech to Text"));
setWindowModality(QmlApplication::dialogModality());
Mlt::Producer *multitrack = MAIN.multitrack();
if (!multitrack || !multitrack->is_valid()) {
LOG_ERROR() << "Invalid multitrack";
return;
}
QGridLayout *grid = new QGridLayout();
grid->addWidget(new QLabel(tr("Name")), 0, 0, Qt::AlignRight);
m_name = new QLineEdit(this);
m_name->setText(trackName);
grid->addWidget(m_name, 0, 1);
grid->addWidget(new QLabel(tr("Language")), 1, 0, Qt::AlignRight);
m_lang = new QComboBox(this);
fillLanguages(m_lang);
// Try to set the default to the system language
QString currentLangCode = QLocale::languageToCode(QLocale::system().language(),
QLocale::ISO639Part1);
for (int i = 0; i < m_lang->count(); i++) {
if (m_lang->itemData(i).toString() == currentLangCode) {
m_lang->setCurrentIndex(i);
break;
}
}
// Fall back to English
if (m_lang->currentIndex() == -1) {
for (int i = 0; i < m_lang->count(); i++) {
if (m_lang->itemData(i).toString() == "en") {
m_lang->setCurrentIndex(i);
break;
}
}
}
grid->addWidget(m_lang, 1, 1);
m_translate = new QCheckBox(this);
m_translate->setCheckState(Qt::Unchecked);
grid->addWidget(m_translate, 2, 0, Qt::AlignRight);
grid->addWidget(new QLabel(tr("Translate to English")), 2, 1, Qt::AlignLeft);
grid->addWidget(new QLabel(tr("Maximum line length")), 3, 0, Qt::AlignRight);
m_maxLength = new QSpinBox(this);
m_maxLength->setRange(10, 100);
m_maxLength->setValue(42);
m_maxLength->setSuffix(" characters");
grid->addWidget(m_maxLength, 3, 1);
m_nonspoken = new QCheckBox(this);
m_nonspoken->setCheckState(Qt::Unchecked);
grid->addWidget(m_nonspoken, 4, 0, Qt::AlignRight);
grid->addWidget(new QLabel(tr("Include non-spoken sounds")), 4, 1, Qt::AlignLeft);
QLabel *tracksLabel = new QLabel(tr("Tracks with speech"));
tracksLabel->setToolTip(tr("Select tracks that contain speech to be transcribed."));
grid->addWidget(tracksLabel, 5, 0, Qt::AlignRight);
m_trackList = new QListWidget(this);
m_trackList->setSelectionMode(QAbstractItemView::NoSelection);
m_trackList->setSizeAdjustPolicy(QAbstractScrollArea::AdjustToContentsOnFirstShow);
m_trackList->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Maximum);
m_trackList->setToolTip(tracksLabel->toolTip());
Mlt::Tractor tractor(*multitrack);
if (!tractor.is_valid()) {
LOG_ERROR() << "Invalid tractor";
return;
}
TrackList trackList = MAIN.timelineDock()->model()->trackList();
if (trackList.size() == 0) {
LOG_ERROR() << "No tracks";
return;
}
for (int trackIndex = 0; trackIndex < trackList.size(); trackIndex++) {
std::unique_ptr<Mlt::Producer> track(tractor.track(trackList[trackIndex].mlt_index));
if (track) {
QString trackName = QString::fromUtf8(track->get(kTrackNameProperty));
if (!trackName.isEmpty()) {
QListWidgetItem *listItem = new QListWidgetItem(trackName, m_trackList);
if (track->get_int("hide") & 2) {
listItem->setCheckState(Qt::Unchecked);
} else {
listItem->setCheckState(Qt::Checked);
}
listItem->setData(Qt::UserRole, QVariant(trackList[trackIndex].mlt_index));
m_trackList->addItem(listItem);
}
}
}
grid->addWidget(m_trackList, 5, 1, Qt::AlignLeft);
// The config section is a single widget with a unique grid layout inside of it.
// The config section is hidden by hiding the config widget (and the layout it contains)
static const int maxPathWidth = 350;
m_configWidget = new QWidget(this);
QGridLayout *configLayout = new QGridLayout(this);
m_configWidget->setLayout(configLayout);
// Horizontal separator line
QFrame *line = new QFrame(m_configWidget);
line->setFrameShape(QFrame::HLine);
line->setFrameShadow(QFrame::Sunken);
configLayout->addWidget(line, 0, 0, 1, 2);
// Whisper.cpp exe
configLayout->addWidget(new QLabel(tr("Whisper.cpp executable")), 1, 0, Qt::AlignRight);
m_exeLabel = new QLineEdit(this);
m_exeLabel->setFixedWidth(maxPathWidth);
m_exeLabel->setReadOnly(true);
configLayout->addWidget(m_exeLabel, 1, 1, Qt::AlignLeft);
QPushButton *exeBrowseButton = new QPushButton(this);
exeBrowseButton->setIcon(QIcon::fromTheme("document-open",
QIcon(":/icons/oxygen/32x32/actions/document-open.png")));
connect(exeBrowseButton, &QAbstractButton::clicked, this, [&] {
auto path = QFileDialog::getOpenFileName(this, tr("Find Whisper.cpp"), Settings.whisperExe(),
QString(),
nullptr, Util::getFileDialogOptions());
if (QFileInfo(path).isExecutable())
{
Settings.setWhisperExe(path);
updateWhisperStatus();
}
});
configLayout->addWidget(exeBrowseButton, 1, 2, Qt::AlignLeft);
// Whisper.cpp model
configLayout->addWidget(new QLabel(tr("GGML Model")), 2, 0, Qt::AlignRight);
m_modelLabel = new QLineEdit(this);
m_modelLabel->setFixedWidth(maxPathWidth);
m_modelLabel->setReadOnly(true);
configLayout->addWidget(m_modelLabel, 2, 1, Qt::AlignLeft);
QPushButton *modelBrowseButton = new QPushButton(this);
modelBrowseButton->setIcon(QIcon::fromTheme("document-open",
QIcon(":/icons/oxygen/32x32/actions/document-open.png")));
connect(modelBrowseButton, &QAbstractButton::clicked, this, [&] {
auto path = QFileDialog::getOpenFileName(this, tr("Find Whisper.cpp"), Settings.whisperModel(),
"*.bin",
nullptr, Util::getFileDialogOptions());
if (QFileInfo(path).exists())
{
LOG_INFO() << "Model found" << path;
Settings.setWhisperModel(path);
updateWhisperStatus();
} else
{
LOG_INFO() << "Model not found" << path;
}
});
configLayout->addWidget(modelBrowseButton, 2, 2, Qt::AlignLeft);
grid->addWidget(m_configWidget, 6, 0, 1, 2);
// Add a button box to the dialog
m_buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
QPushButton *configButton = new QPushButton(tr("Configuration"));
configButton->setCheckable(true);
connect(configButton, &QPushButton::toggled, this, [&](bool checked) {
m_configWidget->setVisible(checked);
});
updateWhisperStatus();
QPushButton *okButton = m_buttonBox->button(QDialogButtonBox::Ok);
if (!m_buttonBox->button(QDialogButtonBox::Ok)->isEnabled()) {
// Show the config section
configButton->setChecked(true);
m_configWidget->setVisible(true);
} else {
configButton->setChecked(false);
m_configWidget->setVisible(false);
}
m_buttonBox->addButton(configButton, QDialogButtonBox::ActionRole);
grid->addWidget(m_buttonBox, 7, 0, 1, 2);
connect(m_buttonBox, SIGNAL(clicked(QAbstractButton *)), this, SLOT(clicked(QAbstractButton *)));
setLayout(grid);
setModal(true);
layout()->setSizeConstraint(QLayout::SetFixedSize);
}
QList<int> TranscribeAudioDialog::tracks()
{
QList<int> tracks;
for (int i = 0; i < m_trackList->count(); i++) {
QListWidgetItem *item = m_trackList->item(i);
if (item && item->checkState() == Qt::Checked) {
tracks << item->data(Qt::UserRole).toInt();
}
}
return tracks;
}
void TranscribeAudioDialog::clicked(QAbstractButton *button)
{
QDialogButtonBox::ButtonRole role = m_buttonBox->buttonRole(button);
if (role == QDialogButtonBox::AcceptRole) {
LOG_DEBUG() << "Accept";
accept();
} else if (role == QDialogButtonBox::RejectRole) {
LOG_DEBUG() << "Reject";
reject();
} else {
LOG_DEBUG() << "Unknown role" << role;
}
}
QString TranscribeAudioDialog::name()
{
return m_name->text();
}
QString TranscribeAudioDialog::language()
{
return m_lang->currentData().toString();
}
bool TranscribeAudioDialog::translate()
{
return m_translate->checkState() == Qt::Checked;
}
int TranscribeAudioDialog::maxLineLength()
{
return m_maxLength->value();
}
bool TranscribeAudioDialog::includeNonspoken()
{
return m_nonspoken->checkState() == Qt::Checked;
}
void TranscribeAudioDialog::updateWhisperStatus()
{
bool exeFound = QFileInfo(Settings.whisperExe()).isExecutable();
bool modelFound = QFileInfo(Settings.whisperModel()).exists();
m_exeLabel->setText(Settings.whisperExe());
m_modelLabel->setText(Settings.whisperModel());
QPushButton *okButton = m_buttonBox->button(QDialogButtonBox::Ok);
if (!exeFound || !modelFound) {
// Disable the OK button;
okButton->setDisabled(true);
} else {
okButton->setDisabled(false);
}
if (exeFound) {
QPalette palette;
m_exeLabel->setPalette(palette);
m_exeLabel->setToolTip(tr("Path to Whisper.cpp executable"));
} else {
QPalette palette;
palette.setColor(QPalette::Text, Qt::red);
m_exeLabel->setPalette(palette);
m_exeLabel->setToolTip(tr("Whisper.cpp executable not found"));
}
if (modelFound) {
QPalette palette;
m_modelLabel->setPalette(palette);
m_modelLabel->setToolTip(tr("Path to GGML model"));
} else {
QPalette palette;
palette.setColor(QPalette::Text, Qt::red);
m_modelLabel->setPalette(palette);
m_modelLabel->setToolTip(tr("GGML model not found"));
}
}
| 12,807
|
C++
|
.cpp
| 310
| 34.345161
| 106
| 0.630557
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,170
|
transcodedialog.cpp
|
mltframework_shotcut/src/dialogs/transcodedialog.cpp
|
/*
* Copyright (c) 2017-2024 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "transcodedialog.h"
#include "ui_transcodedialog.h"
#include "mltcontroller.h"
#include "settings.h"
#include <QPushButton>
TranscodeDialog::TranscodeDialog(const QString &message, bool isProgressive, QWidget *parent) :
QDialog(parent),
ui(new Ui::TranscodeDialog),
m_format(0),
m_isChecked(false),
m_isProgressive(isProgressive)
{
ui->setupUi(this);
setWindowTitle(tr("Convert to Edit-friendly..."));
ui->messageLabel->setText(message);
ui->checkBox->hide();
ui->subclipCheckBox->hide();
ui->deinterlaceCheckBox->setChecked(false);
connect(ui->fpsCheckBox, SIGNAL(toggled(bool)), ui->fpsWidget, SLOT(setEnabled(bool)));
connect(ui->fpsCheckBox, SIGNAL(toggled(bool)), ui->fpsLabel, SLOT(setEnabled(bool)));
connect(ui->fpsCheckBox, SIGNAL(toggled(bool)), ui->frcComboBox, SLOT(setEnabled(bool)));
connect(ui->fpsCheckBox, SIGNAL(toggled(bool)), ui->frcLabel, SLOT(setEnabled(bool)));
ui->fpsCheckBox->setChecked(false);
ui->fpsWidget->setEnabled(false);
ui->fpsLabel->setEnabled(false);
ui->frcComboBox->setEnabled(false);
ui->frcLabel->setEnabled(false);
ui->fpsWidget->setFps(MLT.profile().fps());
ui->frcComboBox->addItem(tr("Duplicate (fast)"), QVariant("dup"));
ui->frcComboBox->addItem(tr("Blend"), QVariant("blend"));
ui->frcComboBox->addItem(tr("Motion Compensation (slow)"), QVariant("mci"));
ui->frcComboBox->setCurrentIndex(0);
QPushButton *advancedButton = new QPushButton(tr("Advanced"));
advancedButton->setCheckable(true);
connect(advancedButton, SIGNAL(toggled(bool)), ui->advancedWidget, SLOT(setVisible(bool)));
if (!Settings.convertAdvanced()) {
ui->advancedWidget->hide();
}
advancedButton->setChecked(Settings.convertAdvanced());
ui->advancedCheckBox->setChecked(Settings.convertAdvanced());
ui->buttonBox->addButton(advancedButton, QDialogButtonBox::ActionRole);
on_horizontalSlider_valueChanged(m_format);
}
TranscodeDialog::~TranscodeDialog()
{
delete ui;
}
void TranscodeDialog::showCheckBox()
{
ui->checkBox->show();
}
bool TranscodeDialog::deinterlace() const
{
return ui->deinterlaceCheckBox->isChecked();
}
bool TranscodeDialog::fpsOverride() const
{
return ui->fpsCheckBox->isChecked();
}
double TranscodeDialog::fps() const
{
return ui->fpsWidget->fps();
}
QString TranscodeDialog::frc() const
{
// Frame Rate Conversion Mode
return ui->frcComboBox->currentData().toString();
}
bool TranscodeDialog::get709Convert()
{
return ui->convert709CheckBox->isChecked();
}
void TranscodeDialog::set709Convert(bool enable)
{
ui->convert709CheckBox->setChecked(enable);
}
QString TranscodeDialog::sampleRate() const
{
QString sampleRate;
if ( ui->sampleRateComboBox->currentIndex() == 1 ) {
sampleRate = "44100";
} else if ( ui->sampleRateComboBox->currentIndex() == 2 ) {
sampleRate = "48000";
}
return sampleRate;
}
void TranscodeDialog::showSubClipCheckBox()
{
ui->subclipCheckBox->show();
}
bool TranscodeDialog::isSubClip() const
{
return ui->subclipCheckBox->isChecked();
}
void TranscodeDialog::setSubClipChecked(bool checked)
{
ui->subclipCheckBox->setChecked(checked);
}
void TranscodeDialog::setFrameRate(double fps)
{
ui->fpsCheckBox->setChecked(true);
ui->fpsWidget->setFps(fps);
}
void TranscodeDialog::on_horizontalSlider_valueChanged(int position)
{
switch (position) {
case 0:
ui->formatLabel->setText(tr("Lossy: I-frame–only %1").arg("H.264/AC-3 MP4"));
break;
case 1:
ui->formatLabel->setText(tr("Intermediate: %1").arg(m_isProgressive ? "DNxHR/PCM MOV" :
"ProRes/PCM MOV"));
break;
case 2:
ui->formatLabel->setText(tr("Lossless: %1").arg("Ut Video/PCM MKV"));
break;
}
m_format = position;
}
void TranscodeDialog::on_checkBox_clicked(bool checked)
{
m_isChecked = checked;
}
void TranscodeDialog::on_advancedCheckBox_clicked(bool checked)
{
Settings.setConvertAdvanced(checked);
}
| 4,829
|
C++
|
.cpp
| 143
| 29.874126
| 95
| 0.714561
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,171
|
resourcedialog.cpp
|
mltframework_shotcut/src/dialogs/resourcedialog.cpp
|
/*
* Copyright (c) 2023-2024 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "resourcedialog.h"
#include "Logger.h"
#include "mltcontroller.h"
#include "qmltypes/qmlapplication.h"
#include "transcodedialog.h"
#include "transcoder.h"
#include "widgets/resourcewidget.h"
#include <QDialogButtonBox>
#include <QMessageBox>
#include <QVBoxLayout>
#include <QPushButton>
ResourceDialog::ResourceDialog(QWidget *parent)
: QDialog(parent)
{
setWindowTitle(tr("Resources"));
setSizeGripEnabled(true) ;
QVBoxLayout *vlayout = new QVBoxLayout();
m_resourceWidget = new ResourceWidget(this);
vlayout->addWidget(m_resourceWidget);
// Button Box
QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Close);
buttonBox->button(QDialogButtonBox::Close)->setAutoDefault(false);
connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
// Convert button
QPushButton *convertButton = buttonBox->addButton(tr("Convert Selected"),
QDialogButtonBox::ActionRole);
connect(convertButton, SIGNAL(pressed()), this, SLOT(convert()));
vlayout->addWidget(buttonBox);
setLayout(vlayout);
}
void ResourceDialog::search(Mlt::Producer *producer)
{
m_resourceWidget->search(producer);
}
void ResourceDialog::add(Mlt::Producer *producer)
{
m_resourceWidget->add(producer);
}
void ResourceDialog::selectTroubleClips()
{
m_resourceWidget->selectTroubleClips();
}
bool ResourceDialog::hasTroubleClips()
{
return m_resourceWidget->hasTroubleClips();
}
int ResourceDialog::producerCount()
{
return m_resourceWidget->producerCount();
}
Mlt::Producer ResourceDialog::producer(int index)
{
return m_resourceWidget->producer(index);
}
void ResourceDialog::convert()
{
QList<Mlt::Producer> producers(m_resourceWidget->getSelected());
// Only convert avformat producers
QMutableListIterator<Mlt::Producer> i(producers);
while (i.hasNext()) {
Mlt::Producer producer = i.next();
if (!QString(producer.get("mlt_service")).startsWith("avformat"))
i.remove();
}
if (producers.length() < 1) {
QMessageBox::warning(this, windowTitle(), tr("No resources to convert"));
return;
}
TranscodeDialog dialog(
tr("Choose an edit-friendly format below and then click OK to choose a file name. "
"After choosing a file name, a job is created. "
"When it is done, double-click the job to open it.\n"),
MLT.profile().progressive(), this);
dialog.setWindowTitle(tr("Convert..."));
dialog.setWindowModality(QmlApplication::dialogModality());
Transcoder transcoder;
transcoder.setProducers(producers);
transcoder.convert(dialog);
accept();
}
void ResourceDialog::showEvent(QShowEvent *event)
{
m_resourceWidget->updateSize();
resize(m_resourceWidget->width() + 4, m_resourceWidget->height());
QDialog::showEvent(event);
}
| 3,611
|
C++
|
.cpp
| 102
| 31.254902
| 91
| 0.721856
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,172
|
editmarkerdialog.cpp
|
mltframework_shotcut/src/dialogs/editmarkerdialog.cpp
|
/*
* Copyright (c) 2021 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "editmarkerdialog.h"
#include "Logger.h"
#include "widgets/editmarkerwidget.h"
#include <QDebug>
#include <QDialogButtonBox>
#include <QVBoxLayout>
EditMarkerDialog::EditMarkerDialog(QWidget *parent, const QString &text, const QColor &color,
int start, int end, int maxEnd)
: QDialog(parent)
{
setWindowTitle(tr("Edit Marker"));
QVBoxLayout *VLayout = new QVBoxLayout(this);
m_sWidget = new EditMarkerWidget(this, text, color, start, end, maxEnd);
VLayout->addWidget(m_sWidget);
m_buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
VLayout->addWidget(m_buttonBox);
connect(m_buttonBox, SIGNAL(clicked(QAbstractButton *)), this, SLOT(clicked(QAbstractButton *)));
setLayout(VLayout);
setModal(true);
layout()->setSizeConstraint(QLayout::SetFixedSize);
}
QString EditMarkerDialog::getText()
{
return m_sWidget->getText();
}
QColor EditMarkerDialog::getColor()
{
return m_sWidget->getColor();
}
int EditMarkerDialog::getStart()
{
return m_sWidget->getStart();
}
int EditMarkerDialog::getEnd()
{
return m_sWidget->getEnd();
}
void EditMarkerDialog::clicked(QAbstractButton *button)
{
QDialogButtonBox::ButtonRole role = m_buttonBox->buttonRole(button);
if (role == QDialogButtonBox::AcceptRole) {
accept();
} else if (role == QDialogButtonBox::RejectRole) {
reject();
} else {
LOG_DEBUG() << "Unknown role" << role;
}
}
| 2,202
|
C++
|
.cpp
| 64
| 30.796875
| 101
| 0.722824
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
13,173
|
systemsyncdialog.cpp
|
mltframework_shotcut/src/dialogs/systemsyncdialog.cpp
|
/*
* Copyright (c) 2020 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "systemsyncdialog.h"
#include "ui_systemsyncdialog.h"
#include "settings.h"
#include "mltcontroller.h"
SystemSyncDialog::SystemSyncDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::SystemSyncDialog),
m_oldValue(Settings.playerVideoDelayMs())
{
ui->setupUi(this);
ui->syncSlider->setValue(Settings.playerVideoDelayMs());
ui->applyButton->hide();
}
SystemSyncDialog::~SystemSyncDialog()
{
delete ui;
}
void SystemSyncDialog::on_syncSlider_sliderReleased()
{
setDelay(ui->syncSlider->value());
}
void SystemSyncDialog::on_syncSpinBox_editingFinished()
{
ui->syncSlider->setValue(ui->syncSpinBox->value());
setDelay(ui->syncSpinBox->value());
}
void SystemSyncDialog::on_buttonBox_rejected()
{
setDelay(m_oldValue);
}
void SystemSyncDialog::on_undoButton_clicked()
{
ui->syncSlider->setValue(0);
setDelay(0);
}
void SystemSyncDialog::on_syncSpinBox_valueChanged(int arg1)
{
Q_UNUSED(arg1)
ui->applyButton->show();
}
void SystemSyncDialog::on_applyButton_clicked()
{
setDelay(ui->syncSpinBox->value());
}
void SystemSyncDialog::setDelay(int delay)
{
if (delay != Settings.playerVideoDelayMs()) {
Settings.setPlayerVideoDelayMs(delay);
MLT.consumerChanged();
}
ui->applyButton->hide();
}
| 1,991
|
C++
|
.cpp
| 68
| 26.544118
| 72
| 0.744247
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
13,174
|
addencodepresetdialog.cpp
|
mltframework_shotcut/src/dialogs/addencodepresetdialog.cpp
|
/*
* Copyright (c) 2012-2022 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "addencodepresetdialog.h"
#include "ui_addencodepresetdialog.h"
AddEncodePresetDialog::AddEncodePresetDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::AddEncodePresetDialog)
{
ui->setupUi(this);
}
AddEncodePresetDialog::~AddEncodePresetDialog()
{
delete ui;
}
void AddEncodePresetDialog::setProperties(const QString &properties)
{
ui->propertiesEdit->setPlainText(properties);
}
QString AddEncodePresetDialog::presetName() const
{
return ui->nameEdit->text();
}
QString AddEncodePresetDialog::properties() const
{
const auto &extension = ui->extensionEdit->text();
if (!extension.isEmpty()) {
return ui->propertiesEdit->toPlainText() + "\nmeta.preset.extension=" + extension;
}
return ui->propertiesEdit->toPlainText();
}
| 1,488
|
C++
|
.cpp
| 44
| 31.25
| 90
| 0.757302
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
13,175
|
filedatedialog.cpp
|
mltframework_shotcut/src/dialogs/filedatedialog.cpp
|
/*
* Copyright (c) 2019-2022 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "filedatedialog.h"
#include <Logger.h>
#include "shotcut_mlt_properties.h"
#include "mltcontroller.h"
#include "MltProducer.h"
#include "proxymanager.h"
#include <QComboBox>
#include <QDateTimeEdit>
#include <QDebug>
#include <QDialogButtonBox>
#include <QFileInfo>
#include <QVBoxLayout>
void addDateToCombo(QComboBox *combo, const QString &description, const QDateTime &date)
{
QDateTime local = date.toLocalTime();
QString text = local.toString("yyyy-MM-dd HH:mm:ss") + " [" + description + "]";
combo->addItem(text, local);
}
FileDateDialog::FileDateDialog(QString title, Mlt::Producer *producer, QWidget *parent)
: QDialog(parent)
, m_producer(producer)
, m_dtCombo(new QComboBox())
, m_dtEdit(new QDateTimeEdit())
{
setWindowTitle(tr("%1 File Date").arg(title));
int64_t milliseconds = producer->get_creation_time();
QDateTime creation_time;
if (!milliseconds ) {
creation_time = QDateTime::currentDateTime();
} else {
// Set the date to the current producer date.
creation_time = QDateTime::fromMSecsSinceEpoch(milliseconds);
}
QVBoxLayout *VLayout = new QVBoxLayout(this);
populateDateOptions(producer);
m_dtCombo->setCurrentIndex(-1);
VLayout->addWidget(m_dtCombo);
connect(m_dtCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(dateSelected(int)));
m_dtEdit->setDisplayFormat("yyyy-MM-dd HH:mm:ss");
m_dtEdit->setCalendarPopup(true);
m_dtEdit->setTimeSpec(Qt::LocalTime);
m_dtEdit->setDateTime(creation_time);
VLayout->addWidget(m_dtEdit);
QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok
| QDialogButtonBox::Cancel);
VLayout->addWidget(buttonBox);
connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
this->setLayout (VLayout);
this->setModal(true);
}
void FileDateDialog::accept()
{
m_producer->set_creation_time((int64_t)m_dtEdit->dateTime().toTimeSpec(
Qt::LocalTime).toMSecsSinceEpoch());
QDialog::accept();
}
void FileDateDialog::dateSelected(int index)
{
LOG_DEBUG() << index;
if ( index > -1 ) {
m_dtEdit->setDateTime(m_dtCombo->itemData(index).toDateTime());
}
}
void FileDateDialog::populateDateOptions(Mlt::Producer *producer)
{
QDateTime dateTime;
// Add current value
int64_t milliseconds = producer->get_creation_time();
if ( milliseconds ) {
dateTime = QDateTime::fromMSecsSinceEpoch(milliseconds);
addDateToCombo(m_dtCombo, tr("Current Value"), dateTime);
}
// Add now time
addDateToCombo(m_dtCombo, tr("Now"), QDateTime::currentDateTime());
// Add system info for the file.
QString resource = ProxyManager::resource(*producer);
QFileInfo fileInfo(resource);
if (fileInfo.exists()) {
addDateToCombo(m_dtCombo, tr("System - Modified"), fileInfo.lastModified());
addDateToCombo(m_dtCombo, tr("System - Created"), fileInfo.birthTime());
}
// Add metadata dates
Mlt::Producer tmpProducer(MLT.profile(), "avformat", resource.toUtf8().constData());
if (tmpProducer.is_valid()) {
// Standard FFMpeg creation_time
dateTime = QDateTime::fromString(tmpProducer.get("meta.attr.creation_time.markup"),
Qt::ISODateWithMs);
if (dateTime.isValid()) {
addDateToCombo(m_dtCombo, tr("Metadata - Creation Time"), dateTime);
}
// Quicktime create date
dateTime = QDateTime::fromString(
tmpProducer.get("meta.attr.com.apple.quicktime.creationdate.markup"), Qt::ISODateWithMs);
if (dateTime.isValid()) {
addDateToCombo(m_dtCombo, tr("Metadata - QuickTime date"), dateTime);
}
}
}
| 4,612
|
C++
|
.cpp
| 115
| 34.4
| 112
| 0.683259
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,176
|
subtitletrackdialog.cpp
|
mltframework_shotcut/src/dialogs/subtitletrackdialog.cpp
|
/*
* Copyright (c) 2024 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "subtitletrackdialog.h"
#include <QDebug>
#include <QComboBox>
#include <QLabel>
#include <QLineEdit>
#include <QList>
#include <QLocale>
#include <QDialogButtonBox>
#include <QGridLayout>
static void fillLanguages(QComboBox *combo)
{
QList<QLocale> allLocales = QLocale::matchingLocales(QLocale::AnyLanguage, QLocale::AnyScript,
QLocale::AnyTerritory);
QMap<QString, QString> iso639_2LanguageCodes;
for (const QLocale &locale : allLocales) {
QLocale::Language lang = locale.language();
if (lang != QLocale::AnyLanguage && lang != QLocale::C) {
QString langCode = QLocale::languageToCode(lang, QLocale::ISO639Part2);
QString langStr = QLocale::languageToString(lang);
if (!langCode.isEmpty() && !langStr.isEmpty()) {
iso639_2LanguageCodes.insert(langStr, langCode);
}
}
}
for (auto it = iso639_2LanguageCodes.keyValueBegin(); it != iso639_2LanguageCodes.keyValueEnd();
++it) {
QString text = QStringLiteral("%1 (%2)").arg(it->first).arg(it->second);
combo->addItem(text, it->second);
}
}
SubtitleTrackDialog::SubtitleTrackDialog(const QString &name, const QString &lang, QWidget *parent)
: QDialog(parent)
{
setWindowTitle(tr("New Subtitle Track"));
QGridLayout *grid = new QGridLayout();
grid->addWidget(new QLabel(tr("Name")), 0, 0, Qt::AlignRight);
m_name = new QLineEdit(this);
m_name->setText(name);
grid->addWidget(m_name, 0, 1);
grid->addWidget(new QLabel(tr("Language")), 1, 0, Qt::AlignRight);
m_lang = new QComboBox(this);
fillLanguages(m_lang);
for (int i = 0; i < m_lang->count(); i++) {
if (m_lang->itemData(i).toString() == lang) {
m_lang->setCurrentIndex(i);
break;
}
}
grid->addWidget(m_lang, 1, 1);
QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok
| QDialogButtonBox::Cancel);
grid->addWidget(buttonBox, 2, 0, 2, 2);
connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
setLayout(grid);
this->setModal(true);
m_name->setFocus();
}
QString SubtitleTrackDialog::getName()
{
return m_name->text();
}
QString SubtitleTrackDialog::getLanguage()
{
return m_lang->currentData().toString();
}
void SubtitleTrackDialog::accept()
{
QDialog::accept();
}
| 3,253
|
C++
|
.cpp
| 86
| 32.034884
| 100
| 0.662016
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,177
|
durationdialog.cpp
|
mltframework_shotcut/src/dialogs/durationdialog.cpp
|
/*
* Copyright (c) 2012-2022 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "durationdialog.h"
#include "ui_durationdialog.h"
DurationDialog::DurationDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::DurationDialog)
{
ui->setupUi(this);
connect(ui->spinBox, &TimeSpinBox::accepted, this, &QDialog::accept);
}
DurationDialog::~DurationDialog()
{
delete ui;
}
void DurationDialog::setDuration(int frames)
{
ui->spinBox->setValue(frames);
}
int DurationDialog::duration() const
{
return ui->spinBox->value();
}
| 1,176
|
C++
|
.cpp
| 37
| 29.486486
| 73
| 0.748677
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,178
|
longuitask.cpp
|
mltframework_shotcut/src/dialogs/longuitask.cpp
|
/*
* Copyright (c) 2020 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "longuitask.h"
#include "mainwindow.h"
static QMutex g_mutex;
static LongUiTask *g_instance = nullptr;
LongUiTask::LongUiTask(QString title)
: QProgressDialog(title, QString(), 0, 0, &MAIN)
{
setWindowTitle(title);
setModal(true);
setWindowModality(Qt::ApplicationModal);
setMinimumDuration(2000);
setRange(0, 0);
g_instance = this;
}
LongUiTask::~LongUiTask()
{
g_instance = nullptr;
}
void LongUiTask::reportProgress(QString text, int value, int max)
{
setLabelText(text);
setRange(0, max - 1);
setValue(value);
QCoreApplication::processEvents();
}
void LongUiTask::cancel()
{
if (g_instance) {
g_instance->QProgressDialog::cancel();
}
}
| 1,412
|
C++
|
.cpp
| 47
| 27.234043
| 72
| 0.732156
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
13,179
|
listselectiondialog.cpp
|
mltframework_shotcut/src/dialogs/listselectiondialog.cpp
|
/*
* Copyright (c) 2018-2022 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "listselectiondialog.h"
#include "ui_listselectiondialog.h"
#include <QListWidget>
ListSelectionDialog::ListSelectionDialog(const QStringList &list, QWidget *parent) :
QDialog(parent),
ui(new Ui::ListSelectionDialog)
{
ui->setupUi(this);
for (auto &text : list) {
QListWidgetItem *item = new QListWidgetItem(text, ui->listWidget);
item->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled | Qt::ItemIsSelectable);
item->setCheckState(Qt::Unchecked);
connect(ui->listWidget, SIGNAL(itemActivated(QListWidgetItem *)),
SLOT(onItemActivated(QListWidgetItem *)));
}
}
ListSelectionDialog::~ListSelectionDialog()
{
delete ui;
}
void ListSelectionDialog::setColors(const QStringList &list)
{
ui->listWidget->setAlternatingRowColors(false);
ui->listWidget->setSortingEnabled(false);
for (auto &text : list) {
QListWidgetItem *item = new QListWidgetItem(text, ui->listWidget);
item->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled | Qt::ItemIsSelectable);
connect(ui->listWidget, SIGNAL(itemActivated(QListWidgetItem *)),
SLOT(onItemActivated(QListWidgetItem *)));
QColor color(text);
item->setCheckState(Qt::Checked);
if (color.isValid()) {
item->setBackground(color);
}
}
}
void ListSelectionDialog::setSelection(const QStringList &selection)
{
int n = ui->listWidget->count();
for (int i = 0; i < n; ++i) {
QListWidgetItem *item = ui->listWidget->item(i);
if (selection.indexOf(item->text()) > -1)
item->setCheckState(Qt::Checked);
}
}
QStringList ListSelectionDialog::selection() const
{
QStringList result;
int n = ui->listWidget->count();
for (int i = 0; i < n; ++i) {
QListWidgetItem *item = ui->listWidget->item(i);
if (item->checkState() == Qt::Checked)
result << item->text();
}
return result;
}
QDialogButtonBox *ListSelectionDialog::buttonBox() const
{
return ui->buttonBox;
}
void ListSelectionDialog::onItemActivated(QListWidgetItem *item)
{
item->setCheckState(item->checkState() == Qt::Checked ? Qt::Unchecked : Qt::Checked);
}
| 2,924
|
C++
|
.cpp
| 80
| 31.9125
| 91
| 0.696756
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,180
|
unlinkedfilesdialog.cpp
|
mltframework_shotcut/src/dialogs/unlinkedfilesdialog.cpp
|
/*
* Copyright (c) 2016-2023 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "unlinkedfilesdialog.h"
#include "ui_unlinkedfilesdialog.h"
#include "settings.h"
#include "mltxmlchecker.h"
#include "util.h"
#include <Logger.h>
#include <QFileDialog>
#include <QStringList>
UnlinkedFilesDialog::UnlinkedFilesDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::UnlinkedFilesDialog)
{
ui->setupUi(this);
}
UnlinkedFilesDialog::~UnlinkedFilesDialog()
{
delete ui;
}
void UnlinkedFilesDialog::setModel(QStandardItemModel &model)
{
QStringList headers;
headers << tr("Missing");
headers << tr("Replacement");
model.setHorizontalHeaderLabels(headers);
ui->tableView->setModel(&model);
ui->tableView->resizeColumnsToContents();
}
void UnlinkedFilesDialog::on_tableView_doubleClicked(const QModelIndex &index)
{
// Use File Open dialog to choose a replacement.
QString path = Settings.openPath();
#ifdef Q_OS_MAC
path.append("/*");
#endif
QStringList filenames = QFileDialog::getOpenFileNames(this, tr("Open File"), path,
QString(), nullptr, Util::getFileDialogOptions());
if (filenames.length() > 0) {
QAbstractItemModel *model = ui->tableView->model();
QModelIndex firstColIndex = model->index(index.row(), MltXmlChecker::MissingColumn);
QModelIndex secondColIndex = model->index(index.row(), MltXmlChecker::ReplacementColumn);
QString hash = Util::getFileHash(filenames[0]);
if (hash == model->data(firstColIndex, MltXmlChecker::ShotcutHashRole)) {
// If the hashes match set icon to OK.
QIcon icon(":/icons/oxygen/32x32/status/task-complete.png");
model->setData(firstColIndex, icon, Qt::DecorationRole);
} else {
// Otherwise, set icon to warning.
QIcon icon(":/icons/oxygen/32x32/status/task-attempt.png");
model->setData(firstColIndex, icon, Qt::DecorationRole);
}
// Add chosen filename to the model.
QString filePath = QDir::toNativeSeparators(filenames[0]);
model->setData(secondColIndex, filePath);
model->setData(secondColIndex, filePath, Qt::ToolTipRole);
model->setData(secondColIndex, hash, MltXmlChecker::ShotcutHashRole);
QFileInfo fi(QFileInfo(filenames.first()));
Settings.setOpenPath(fi.path());
lookInDir(fi.dir());
}
}
bool UnlinkedFilesDialog::lookInDir(const QDir &dir, bool recurse)
{
LOG_DEBUG() << dir.canonicalPath();
// returns true if outstanding is > 0
unsigned outstanding = 0;
QAbstractItemModel *model = ui->tableView->model();
for (int row = 0; row < model->rowCount(); row++) {
QModelIndex replacementIndex = model->index(row, MltXmlChecker::ReplacementColumn);
if (model->data(replacementIndex, MltXmlChecker::ShotcutHashRole).isNull())
++outstanding;
}
if (outstanding) {
for (const auto &fileName :
dir.entryList(QDir::Files | QDir::Readable | QDir::NoDotAndDotDot)) {
QString hash = Util::getFileHash(dir.absoluteFilePath(fileName));
for (int row = 0; row < model->rowCount(); row++) {
QModelIndex replacementIndex = model->index(row, MltXmlChecker::ReplacementColumn);
if (model->data(replacementIndex, MltXmlChecker::ShotcutHashRole).isNull()) {
QModelIndex missingIndex = model->index(row, MltXmlChecker::MissingColumn);
QFileInfo missingInfo(model->data(missingIndex).toString());
QString missingHash = model->data(missingIndex, MltXmlChecker::ShotcutHashRole).toString();
if (hash == missingHash || fileName == missingInfo.fileName()) {
if (hash == missingHash) {
QIcon icon(":/icons/oxygen/32x32/status/task-complete.png");
model->setData(missingIndex, icon, Qt::DecorationRole);
} else {
QIcon icon(":/icons/oxygen/32x32/status/task-attempt.png");
model->setData(missingIndex, icon, Qt::DecorationRole);
}
QString filePath = QDir::toNativeSeparators(dir.absoluteFilePath(fileName));
model->setData(replacementIndex, filePath);
model->setData(replacementIndex, filePath, Qt::ToolTipRole);
model->setData(replacementIndex, hash, MltXmlChecker::ShotcutHashRole);
QCoreApplication::processEvents();
if (--outstanding)
break;
else
return false;
}
}
}
}
}
if (outstanding && recurse) {
for (const QString &dirName :
dir.entryList(QDir::Dirs | QDir::Executable | QDir::NoDotAndDotDot)) {
if (!lookInDir(dir.absoluteFilePath(dirName), true))
break;
}
}
return outstanding;
}
void UnlinkedFilesDialog::on_searchFolderButton_clicked()
{
QString dirName = QFileDialog::getExistingDirectory(this, windowTitle(), Settings.openPath(),
Util::getFileDialogOptions());
if (!dirName.isEmpty()) {
Settings.setOpenPath(dirName);
lookInDir(dirName);
}
}
| 6,164
|
C++
|
.cpp
| 137
| 35.386861
| 111
| 0.630879
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,181
|
alignclipsmodel.cpp
|
mltframework_shotcut/src/models/alignclipsmodel.cpp
|
/*
* Copyright (c) 2022-2024 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "alignclipsmodel.h"
#include "settings.h"
#include <Logger.h>
#include "mltcontroller.h"
AlignClipsModel::AlignClipsModel(QObject *parent)
: QAbstractItemModel(parent)
{
}
AlignClipsModel::~AlignClipsModel()
{
}
void AlignClipsModel::clear()
{
beginResetModel();
m_clips.clear();
endResetModel();
}
void AlignClipsModel::addClip(const QString &name, int offset, int speed, const QString &error)
{
beginInsertRows(QModelIndex(), m_clips.size(), m_clips.size());
ClipAlignment newClip;
newClip.name = name;
newClip.offset = offset;
newClip.speed = speed;
newClip.error = error;
newClip.progress = 0;
m_clips.append(newClip);
endInsertRows();
}
void AlignClipsModel::updateProgress(int row, int percent)
{
QModelIndex modelIndex = index(row, COLUMN_NAME);
if (!modelIndex.isValid() || modelIndex.column() < 0 || modelIndex.column() >= COLUMN_COUNT
|| modelIndex.row() < 0 || modelIndex.row() >= m_clips.size()) {
LOG_ERROR() << "Invalid Index: " << modelIndex.row() << modelIndex.column();
return;
}
m_clips[modelIndex.row()].progress = percent;
emit dataChanged(modelIndex, modelIndex);
}
int AlignClipsModel::getProgress(int row) const
{
if (row < 0 || row > m_clips.size()) {
LOG_ERROR() << "Invalid row: " << row;
return 0;
}
return m_clips[row].progress;
}
void AlignClipsModel::updateOffsetAndSpeed(int row, int offset, double speed, const QString &error)
{
if (row < 0 || row >= m_clips.size()) {
LOG_ERROR() << "Invalid Row: " << row;
return;
}
m_clips[row].offset = offset;
m_clips[row].speed = speed;
m_clips[row].error = error;
emit dataChanged(index(row, COLUMN_ERROR), index(row, COLUMN_COUNT - 1));
}
int AlignClipsModel::getOffset(int row)
{
int offset = 0;
if (row < 0 || row >= m_clips.size()) {
LOG_ERROR() << "Invalid Row: " << row;
} else {
offset = m_clips[row].offset;
}
return offset;
}
double AlignClipsModel::getSpeed(int row)
{
double speed = 1.0;
if (row < 0 || row >= m_clips.size()) {
LOG_ERROR() << "Invalid Row: " << row;
} else {
speed = m_clips[row].speed;
}
return speed;
}
int AlignClipsModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent)
return m_clips.size();
}
int AlignClipsModel::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent)
return COLUMN_COUNT;
}
QVariant AlignClipsModel::data(const QModelIndex &index, int role) const
{
QVariant result;
switch (role) {
case Qt::StatusTipRole:
case Qt::FontRole:
case Qt::SizeHintRole:
case Qt::DecorationRole:
case Qt::CheckStateRole:
case Qt::BackgroundRole:
case Qt::ForegroundRole:
return result;
}
if (!index.isValid() || index.column() < 0 || index.column() >= COLUMN_COUNT || index.row() < 0
|| index.row() >= m_clips.size()) {
LOG_ERROR() << "Invalid Index: " << index.row() << index.column() << role;
return result;
}
const ClipAlignment &clip = m_clips[index.row()];
switch (role) {
case Qt::DisplayRole:
switch (index.column()) {
case COLUMN_ERROR:
result = clip.error;
break;
case COLUMN_NAME:
result = clip.name;
break;
case COLUMN_OFFSET:
if (clip.progress != 0 && clip.offset != INVALID_OFFSET && MLT.producer()
&& MLT.producer()->is_valid()) {
if (clip.offset >= 0) {
result = QString::fromLatin1(MLT.producer()->frames_to_time(clip.offset, Settings.timeFormat()));
} else {
result = QStringLiteral("-") + MLT.producer()->frames_to_time(-clip.offset, Settings.timeFormat());
}
}
break;
case COLUMN_SPEED:
if (clip.speed != INVALID_OFFSET)
result = QLocale().toString(clip.speed * 100.0, 'g', 4);
break;
default:
LOG_ERROR() << "Invalid Column" << index.row() << index.column() << roleNames()[role] << role;
break;
}
break;
case Qt::ToolTipRole:
return clip.error;
case Qt::TextAlignmentRole:
switch (index.column()) {
case COLUMN_NAME:
result = Qt::AlignLeft;
break;
case COLUMN_ERROR:
case COLUMN_OFFSET:
case COLUMN_SPEED:
result = Qt::AlignCenter;
break;
default:
LOG_ERROR() << "Invalid Column" << index.row() << index.column() << roleNames()[role] << role;
break;
}
break;
default:
LOG_ERROR() << "Invalid Role" << index.row() << index.column() << roleNames()[role] << role;
break;
}
return result;
}
QVariant AlignClipsModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (role == Qt::DisplayRole && orientation == Qt::Horizontal) {
switch (section) {
case COLUMN_ERROR:
return QVariant();
case COLUMN_NAME:
return tr("Clip");
case COLUMN_OFFSET:
return tr("Offset");
case COLUMN_SPEED:
return tr("Speed");
default:
break;
}
}
return QVariant();
}
QModelIndex AlignClipsModel::index(int row, int column, const QModelIndex &parent) const
{
Q_UNUSED(parent)
if (column < 0 || column >= COLUMN_COUNT || row < 0 || row >= m_clips.size())
return QModelIndex();
return createIndex(row, column, (int)0);
}
QModelIndex AlignClipsModel::parent(const QModelIndex &index) const
{
Q_UNUSED(index)
return QModelIndex();
}
| 6,502
|
C++
|
.cpp
| 205
| 25.629268
| 119
| 0.614466
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,182
|
actionsmodel.cpp
|
mltframework_shotcut/src/models/actionsmodel.cpp
|
/*
* Copyright (c) 2022-2024 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "actionsmodel.h"
#include "actions.h"
#include <Logger.h>
#include <QAction>
#include <QGuiApplication>
#include <QKeySequence>
#include <QPalette>
#include <QFont>
ActionsModel::ActionsModel(QObject *parent)
: QAbstractItemModel(parent)
{
const auto keys = Actions.keys();
for (const QString &key : keys) {
m_actions.append(Actions[key]);
}
}
QAction *ActionsModel::action(const QModelIndex &index) const
{
if (index.row() < m_actions.size()) {
return m_actions[index.row()];
}
return nullptr;
}
int ActionsModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent)
return m_actions.size();
}
int ActionsModel::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent)
return COLUMN_COUNT;
}
QVariant ActionsModel::data(const QModelIndex &index, int role) const
{
QVariant result;
switch (role) {
case Qt::StatusTipRole:
case Qt::DecorationRole:
case Qt::TextAlignmentRole:
case Qt::CheckStateRole:
case Qt::SizeHintRole:
case Qt::BackgroundRole:
return result;
}
if (!index.isValid() || index.column() < 0 || index.column() >= COLUMN_COUNT || index.row() < 0
|| index.row() >= m_actions.size()) {
LOG_ERROR() << "Invalid Index: " << index.row() << index.column() << role;
return result;
}
QAction *action = m_actions[index.row()];
switch (role) {
case Qt::EditRole:
case Qt::DisplayRole:
switch (index.column()) {
case COLUMN_ACTION:
result = action->property(Actions.displayProperty).toString();
break;
case COLUMN_SEQUENCE1: {
QList<QKeySequence> sequences = action->shortcuts();
if (sequences.size() > 0)
result = sequences[0].toString(QKeySequence::NativeText);
}
break;
case COLUMN_SEQUENCE2: {
result = action->property(Actions.hardKeyProperty);
if (result.toString().isEmpty()) {
QList<QKeySequence> sequences = action->shortcuts();
if (sequences.size() > 1)
result = sequences[1].toString(QKeySequence::NativeText);
}
}
break;
default:
LOG_ERROR() << "Invalid Column" << index.column() << role;
break;
}
break;
case Qt::ToolTipRole:
result = action->toolTip();
break;
case Qt::FontRole:
if (index.column() == COLUMN_SEQUENCE1) {
QFont font;
QList<QKeySequence> sequences = action->shortcuts();
if (sequences.size() > 0 && sequences[0] != action->property(Actions.defaultKey1Property)) {
font.setBold(true);
}
result = font;
} else if (index.column() == COLUMN_SEQUENCE2) {
QFont font;
QList<QKeySequence> sequences = action->shortcuts();
if (action->property(Actions.hardKeyProperty).isValid()) {
font.setItalic(true);
} else if (sequences.size() > 1 && sequences[1] != action->property(Actions.defaultKey2Property)) {
font.setBold(true);
}
result = font;
}
break;
case Qt::ForegroundRole:
if (index.column() == COLUMN_SEQUENCE2 && action->property(Actions.hardKeyProperty).isValid()) {
result = QGuiApplication::palette().color(QPalette::Disabled, QPalette::Text);
}
break;
case ActionsModel::HardKeyRole:
result = action->property(Actions.hardKeyProperty);
break;
case ActionsModel::DefaultKeyRole:
switch (index.column()) {
case COLUMN_SEQUENCE1:
result = action->property(Actions.defaultKey1Property);
break;
case COLUMN_SEQUENCE2:
result = action->property(Actions.defaultKey2Property);
break;
default:
break;
}
break;
default:
auto names = roleNames();
LOG_ERROR() << "Invalid Role" << index.row() << index.column() << names[role] << role;
break;
}
return result;
}
bool ActionsModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
if (!index.isValid() )
return false;
if (role != Qt::EditRole)
return false;
if (index.column() != COLUMN_SEQUENCE1 && index.column() != COLUMN_SEQUENCE2)
return false;
if (index.row() < 0 || index.row() >= m_actions.size()) {
return false;
}
QKeySequence ks;
if (value.canConvert<QKeySequence>())
ks = value.value<QKeySequence>();
else if (value.canConvert<QString>())
ks = QKeySequence(value.toString());
else
return false;
QAction *action = m_actions[index.row()];
if (!ks.isEmpty()) {
for (const auto a : std::as_const(m_actions)) {
QList<QKeySequence> sequences = a->shortcuts();
for (int i = 0; i < sequences.size(); i++) {
if (sequences[i] == ks) {
if (a != action) {
QString error = tr("Shortcut %1 is used by %2").arg(ks.toString(), a->property(
Actions.displayProperty).toString());
emit editError(error);
}
return false;
}
}
QString hardKey = a->property(Actions.hardKeyProperty).toString();
if (!hardKey.isEmpty() && hardKey == ks.toString()) {
QString error = tr("Shortcut %1 is reserved for use by %2").arg(ks.toString(), a->property(
Actions.displayProperty).toString());
emit editError(error);
return false;
}
}
}
QList<QKeySequence> oldShortcuts = action->shortcuts();
QList<QKeySequence> newShortcuts;
if (index.column() == COLUMN_SEQUENCE1) {
newShortcuts << ks;
if (oldShortcuts.size() > 1 && oldShortcuts[1] != ks) {
newShortcuts << oldShortcuts[1];
}
} else if (index.column() == COLUMN_SEQUENCE2) {
if (oldShortcuts.size() > 0 && oldShortcuts[0] != ks) {
newShortcuts << oldShortcuts[0];
}
newShortcuts << ks;
}
Actions.overrideShortcuts(action->objectName(), newShortcuts);
emit dataChanged(this->index(index.row(), COLUMN_SEQUENCE1), this->index(index.row(),
COLUMN_SEQUENCE2));
return true;
}
QVariant ActionsModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (role == Qt::DisplayRole && orientation == Qt::Horizontal) {
switch (section) {
case COLUMN_ACTION:
return tr("Action");
case COLUMN_SEQUENCE1:
return tr("Shortcut 1");
case COLUMN_SEQUENCE2:
return tr("Shortcut 2");
default:
auto names = roleNames();
LOG_ERROR() << "Invalid section" << section << names[role] << role;
break;
}
}
return QVariant();
}
QModelIndex ActionsModel::index(int row, int column, const QModelIndex &parent) const
{
Q_UNUSED(parent)
if (column < 0 || column >= COLUMN_COUNT || row < 0 || row >= m_actions.size())
return QModelIndex();
return createIndex(row, column, (int)0);
}
QModelIndex ActionsModel::parent(const QModelIndex &index) const
{
Q_UNUSED(index)
return QModelIndex();
}
Qt::ItemFlags ActionsModel::flags(const QModelIndex &index) const
{
Qt::ItemFlags flags = Qt::ItemIsEnabled | Qt::ItemIsSelectable;
if (index.column() == COLUMN_SEQUENCE1 || index.column() == COLUMN_SEQUENCE2) {
flags |= Qt::ItemIsEditable;
}
return flags;
}
QHash<int, QByteArray> ActionsModel::roleNames() const
{
QHash<int, QByteArray> roles = QAbstractItemModel::roleNames();
roles[HardKeyRole] = "hardKey";
roles[DefaultKeyRole] = "defaultKey";
return roles;
}
| 8,901
|
C++
|
.cpp
| 247
| 27.62753
| 121
| 0.591678
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,183
|
attachedfiltersmodel.cpp
|
mltframework_shotcut/src/models/attachedfiltersmodel.cpp
|
/*
* Copyright (c) 2013-2024 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "attachedfiltersmodel.h"
#include "mltcontroller.h"
#include "mainwindow.h"
#include "commands/filtercommands.h"
#include "controllers/filtercontroller.h"
#include "qmltypes/qmlmetadata.h"
#include "shotcut_mlt_properties.h"
#include "util.h"
#include "qmltypes/qmlapplication.h"
#include "settings.h"
#include <QApplication>
#include <QMessageBox>
#include <QTimer>
#include <QGuiApplication>
#include <QClipboard>
#include <Logger.h>
#include <MltChain.h>
#include <MltLink.h>
static int sortOrder(const QmlMetadata *meta)
{
// Sort order is: Link, GPU, Video, Audio
if (meta) {
if (meta->type() == QmlMetadata::Link) {
return 0;
} else if (meta->needsGPU()) {
return 1;
} else if (!meta->isAudio()) {
return 2;
} else if (meta->isAudio()) {
return 3;
}
}
// If there is no metadata, assume the filter is video.
return 2;
}
static int normalFilterCount(Mlt::Producer *producer)
{
int count = 0;
if (producer && producer->is_valid()) {
for (int i = 0; i < producer->filter_count(); i++) {
Mlt::Filter *filter = producer->filter(i);
if (filter->is_valid() && (filter->get_int("_loader") || filter->get_int(kShotcutHiddenProperty))) {
count++;
} else {
i = producer->filter_count();
}
delete filter;
}
}
return count;
}
static int normalLinkCount(Mlt::Producer *producer)
{
int count = 0;
if (producer && producer->is_valid() && producer->type() == mlt_service_chain_type) {
Mlt::Chain chain(*producer);
for (int i = 0; i < chain.link_count(); i++) {
Mlt::Link *link = chain.link(i);
if (link->is_valid() && link->get_int("_loader")) {
count++;
} else {
i = chain.link_count();
}
delete link;
}
}
return count;
}
static int mltFilterIndex(Mlt::Producer *producer, int row)
{
if (row >= 0 && producer && producer->is_valid()) {
int linkCount = 0;
if (producer->type() == mlt_service_chain_type) {
Mlt::Chain chain(*producer);
linkCount = chain.link_count() - normalLinkCount(producer);
if (row < linkCount) {
// This row refers to an MLT link, not a filter
return -1;
}
}
int mltIndex = normalFilterCount(producer) + row - linkCount;
if (mltIndex >= 0 && mltIndex < producer->filter_count()) {
return mltIndex;
}
}
return -1;
}
static int mltLinkIndex(Mlt::Producer *producer, int row)
{
if (row >= 0 && producer && producer->is_valid() && producer->type() == mlt_service_chain_type) {
Mlt::Chain chain(*producer);
int mltIndex = normalLinkCount(producer) + row;
if (mltIndex >= 0 && mltIndex < chain.link_count()) {
return mltIndex;
}
}
return -1;
}
AttachedFiltersModel::AttachedFiltersModel(QObject *parent)
: QAbstractListModel(parent)
, m_dropRow(-1)
{
}
Mlt::Service *AttachedFiltersModel::getService(int row) const
{
Mlt::Service *result = nullptr;
int mltIndex = mltFilterIndex(m_producer.get(), row);
if (mltIndex >= 0) {
// Service is a filter
result = m_producer->filter(mltIndex);
} else {
mltIndex = mltLinkIndex(m_producer.get(), row);
if (mltIndex >= 0) {
// Service is a link
Mlt::Chain chain(*m_producer);
result = chain.link(mltIndex);
}
}
return result;
}
QmlMetadata *AttachedFiltersModel::getMetadata(int row) const
{
if (row < m_metaList.count() && row >= 0) {
return m_metaList[row];
}
return 0;
}
void AttachedFiltersModel::setProducer(Mlt::Producer *producer)
{
if (!producer || !m_producer || (producer->get_parent() != m_producer->get_parent())) {
reset(producer);
}
}
QString AttachedFiltersModel::producerTitle() const
{
if (m_producer)
return Util::producerTitle(*m_producer);
else
return QString();
}
bool AttachedFiltersModel::isProducerSelected() const
{
return !m_producer.isNull() && m_producer->is_valid() && !m_producer->is_blank()
&& MLT.isSeekable(m_producer.get());
}
bool AttachedFiltersModel::supportsLinks() const
{
if (!m_producer.isNull() && m_producer->is_valid()
&& m_producer->type() == mlt_service_chain_type ) {
return true;
}
return false;
}
QString AttachedFiltersModel::name(int row) const
{
QString name;
auto meta = getMetadata(row);
if (meta) {
name = meta->name();
} else {
QScopedPointer<Mlt::Service> service(getService(row));
if (service && service->is_valid() && service->get("mlt_service")) {
name = QString::fromUtf8(service->get("mlt_service"));
}
}
return name;
}
int AttachedFiltersModel::rowCount(const QModelIndex &) const
{
if (m_producer && m_producer->is_valid())
return m_metaList.count();
else
return 0;
}
Qt::ItemFlags AttachedFiltersModel::flags(const QModelIndex &index) const
{
if (index.isValid())
return QAbstractListModel::flags(index) | Qt::ItemIsUserCheckable | Qt::ItemIsDragEnabled;
else
return QAbstractListModel::flags(index) | Qt::ItemIsDropEnabled;
}
QVariant AttachedFiltersModel::data(const QModelIndex &index, int role) const
{
if (!m_producer || !m_producer->is_valid()
|| index.row() >= m_metaList.size())
return QVariant();
switch (role ) {
case Qt::DisplayRole:
return name(index.row());
case Qt::CheckStateRole: {
Mlt::Service *service = getService(index.row());
QVariant result = Qt::Unchecked;
if (service && service->is_valid() && !service->get_int("disable"))
result = Qt::Checked;
delete service;
return result;
}
break;
case TypeDisplayRole: {
QVariant result;
const QmlMetadata *meta = m_metaList[index.row()];
if (meta && meta->isAudio()) {
result = tr("Audio");
} else if (meta && meta->type() == QmlMetadata::Link) {
result = tr("Time");
} else if (meta && meta->needsGPU()) {
result = tr("GPU");
} else {
result = tr("Video");
}
return result;
}
case PluginTypeRole: {
const QmlMetadata *meta = m_metaList[index.row()];
QVariant result = meta ? meta->type() : QmlMetadata::Filter;
return result;
}
break;
default:
break;
}
return QVariant();
}
bool AttachedFiltersModel::setData(const QModelIndex &index, const QVariant &, int role)
{
if (role != Qt::CheckStateRole || !m_producer || !m_producer->is_valid()) {
return false;
}
int mltIndex = mltFilterIndex(m_producer.data(), index.row());
Mlt::Filter *filter = m_producer->filter(mltIndex);
if (filter && filter->is_valid()) {
bool disabled = filter->get_int("disable");
if (isSourceClip()) {
doSetDisabled(*m_producer.data(), index.row(), !disabled);
} else {
MAIN.undoStack()->push(new Filter::DisableCommand(*this, name(index.row()), index.row(),
!disabled));
}
} else {
LOG_ERROR() << "Invalid filter index" << index.row();
}
delete filter;
return true;
}
void AttachedFiltersModel::doSetDisabled(Mlt::Producer &producer, int row, bool disabled)
{
int mltIndex = mltFilterIndex(&producer, row);
Mlt::Filter *filter = producer.filter(mltIndex);
if (filter->is_valid()) {
filter->set("disable", disabled);
emit changed();
if (isProducerLoaded(producer)) {
Q_ASSERT(row >= 0);
QModelIndex modelIndex = createIndex(row, 0);
emit dataChanged(modelIndex, modelIndex, QVector<int>() << Qt::CheckStateRole);
}
} else {
LOG_ERROR() << "Invalid filter index" << row;
}
delete filter;
}
Mlt::Service AttachedFiltersModel::doGetService(Mlt::Producer &producer, int row)
{
Mlt::Service service;
int mltIndex = mltFilterIndex(&producer, row);
if (mltIndex >= 0) {
Mlt::Filter *filter = producer.filter(mltIndex);
if (filter && filter->is_valid()) {
service = Mlt::Service(filter->get_service());
} else {
LOG_ERROR() << "Invalid filter index" << row << mltIndex;
}
delete filter;
} else {
mltIndex = mltLinkIndex(&producer, row);
if (mltIndex >= 0) {
Mlt::Chain chain(producer);
Mlt::Link *link = chain.link(mltIndex);
if (link && link->is_valid()) {
service = Mlt::Service(link->get_service());
} else {
LOG_ERROR() << "Invalid link index" << row << mltIndex;
}
delete link;
} else {
LOG_ERROR() << "Invalid service index" << row << mltIndex;
}
}
return service;
}
QHash<int, QByteArray> AttachedFiltersModel::roleNames() const
{
QHash<int, QByteArray> roles = QAbstractListModel::roleNames();
roles[Qt::CheckStateRole] = "checkState";
roles[TypeDisplayRole] = "typeDisplay";
roles[PluginTypeRole] = "pluginType";
return roles;
}
Qt::DropActions AttachedFiltersModel::supportedDropActions() const
{
return Qt::MoveAction;
}
bool AttachedFiltersModel::insertRows(int row, int, const QModelIndex &)
{
if (m_producer && m_producer->is_valid()) {
if (m_dropRow == -1)
m_dropRow = row;
return true;
} else {
return false;
}
}
bool AttachedFiltersModel::removeRows(int row, int, const QModelIndex &parent)
{
if (m_producer && m_producer->is_valid() && m_dropRow >= 0 && row != m_dropRow) {
bool result = moveRows(parent, row, 1, parent, m_dropRow);
m_dropRow = -1;
return result;
} else {
return false;
}
}
bool AttachedFiltersModel::moveRows(const QModelIndex &sourceParent, int sourceRow, int count,
const QModelIndex &destinationParent, int destinationRow)
{
if (!m_producer || !m_producer->is_valid() || sourceParent != destinationParent || count != 1) {
return false;
}
if (destinationRow == sourceRow) {
return false;
}
if (isSourceClip()) {
doMoveService(*m_producer, sourceRow, destinationRow);
} else {
MAIN.undoStack()->push(new Filter::MoveCommand(*this, name(sourceRow), sourceRow, destinationRow));
}
return true;
}
void AttachedFiltersModel::doMoveService(Mlt::Producer &producer, int fromRow, int toRow)
{
int mltSrcFilterIndex = mltFilterIndex(&producer, fromRow);
int mltDstFilterIndex = mltFilterIndex(&producer, toRow);
int mltSrcLinkIndex = mltLinkIndex(&producer, fromRow);
int mltDstLinkIndex = mltLinkIndex(&producer, toRow);
if (isProducerLoaded(producer)) {
int modelToRow = toRow;
if (modelToRow > fromRow) {
// Satisfy the model move requirements
modelToRow++;
}
QModelIndex fromIndex = createIndex(fromRow, 0);
QModelIndex toIndex = createIndex(modelToRow, 0);
if (!fromIndex.isValid() || !toIndex.isValid()) {
LOG_ERROR() << "Invalid Index" << fromIndex << toIndex;
return;
}
if (!beginMoveRows(fromIndex.parent(), fromRow, fromRow, toIndex.parent(), modelToRow)) {
LOG_ERROR() << "Invalid Move" << fromRow << modelToRow;
return;
}
if (mltSrcFilterIndex >= 0 && mltDstFilterIndex >= 0) {
m_event->block();
producer.move_filter(mltSrcFilterIndex, mltDstFilterIndex);
m_event->unblock();
m_metaList.move(fromRow, toRow);
endMoveRows();
emit changed();
} else if (mltSrcLinkIndex >= 0 && mltDstLinkIndex >= 0) {
m_event->block();
Mlt::Chain chain(producer);
chain.move_link(mltSrcLinkIndex, mltDstLinkIndex);
m_event->unblock();
m_metaList.move(fromRow, toRow);
endMoveRows();
emit changed();
} else {
endMoveRows();
LOG_ERROR() << "Failed to move filter" << fromRow << toRow;
}
} else {
if (mltSrcFilterIndex >= 0 && mltDstFilterIndex >= 0) {
producer.move_filter(mltSrcFilterIndex, mltDstFilterIndex);
emit changed();
} else if (mltSrcLinkIndex >= 0 && mltDstLinkIndex >= 0) {
Mlt::Chain chain(producer);
chain.move_link(mltSrcLinkIndex, mltDstLinkIndex);
emit changed();
} else {
LOG_ERROR() << "Failed to move filter" << fromRow << toRow;
}
}
}
int AttachedFiltersModel::add(QmlMetadata *meta)
{
int insertRow = -1;
if (!m_producer) return -1;
if (!meta->allowMultiple()) {
for (int i = 0; i < m_metaList.count(); i++) {
const QmlMetadata *attachedMeta = m_metaList[i];
if (attachedMeta && meta->uniqueId() == attachedMeta->uniqueId()) {
emit duplicateAddFailed(i);
return -1;
}
}
}
if (m_producer->is_valid() && mlt_service_tractor_type != m_producer->type()
&& !QmlApplication::confirmOutputFilter()) {
return -1;
}
switch (meta->type()) {
case QmlMetadata::Filter: {
Mlt::Filter filter(MLT.profile(), meta->mlt_service().toUtf8().constData());
if (filter.is_valid()) {
insertRow = findInsertRow(meta);
filter.set(kNewFilterProperty, 1);
if (!meta->objectName().isEmpty())
filter.set(kShotcutFilterProperty, meta->objectName().toUtf8().constData());
filter.set_in_and_out(
m_producer->get(kFilterInProperty) ? m_producer->get_int(kFilterInProperty) : m_producer->get_in(),
m_producer->get(kFilterOutProperty) ? m_producer->get_int(kFilterOutProperty) :
m_producer->get_out());
if (isSourceClip()) {
doAddService(*m_producer, filter, insertRow);
} else {
MAIN.undoStack()->push(new Filter::AddCommand(*this, meta->name(), filter, insertRow));
}
}
}
break;
case QmlMetadata::Link: {
if (m_producer->type() != mlt_service_chain_type) {
LOG_ERROR() << "Not a chain";
return -1;
}
if (meta->seekReverse() && m_producer->get_int("meta.media.has_b_frames") != 0) {
emit requestConvert(tr("This file has B-frames, which is not supported by %1.").arg(meta->name()),
false, true);
return -1;
}
Mlt::Link link(meta->mlt_service().toUtf8().constData());
if (link.is_valid()) {
insertRow = findInsertRow(meta);
link.set(kNewFilterProperty, 1);
if (!meta->objectName().isEmpty())
link.set(kShotcutFilterProperty, meta->objectName().toUtf8().constData());
link.set_in_and_out(
m_producer->get(kFilterInProperty) ? m_producer->get_int(kFilterInProperty) : m_producer->get_in(),
m_producer->get(kFilterOutProperty) ? m_producer->get_int(kFilterOutProperty) :
m_producer->get_out());
if (isSourceClip()) {
doAddService(*m_producer, link, insertRow);
} else {
MAIN.undoStack()->push(new Filter::AddCommand(*this, meta->name(), link, insertRow));
}
}
}
break;
case QmlMetadata::FilterSet: {
Mlt::Producer filterSetProducer = getFilterSetProducer(meta);
if (!filterSetProducer.is_valid() || filterSetProducer.filter_count() == 0) {
LOG_ERROR() << "Invalid producer" << meta->name() << filterSetProducer.filter_count();
return -1;
}
for (int i = 0; i < filterSetProducer.filter_count(); i++) {
Mlt::Filter *filter = filterSetProducer.filter(i);
if (filter->is_valid() && !filter->get_int("_loader") && !filter->get_int(kShotcutHiddenProperty)) {
QmlMetadata *tmpMeta = MAIN.filterController()->metadataForService(filter);
insertRow = findInsertRow(tmpMeta);
if (!meta->objectName().isEmpty())
filter->set(kShotcutFilterProperty, meta->objectName().toUtf8().constData());
filter->set_in_and_out(
m_producer->get(kFilterInProperty) ? m_producer->get_int(kFilterInProperty) : m_producer->get_in(),
m_producer->get(kFilterOutProperty) ? m_producer->get_int(kFilterOutProperty) :
m_producer->get_out());
if (isSourceClip()) {
doAddService(*m_producer, *filter, insertRow);
} else {
Filter::AddCommand::AddType type = Filter::AddCommand::AddSet;
if (i == filterSetProducer.filter_count() - 1) {
type = Filter::AddCommand::AddSetLast;
}
MAIN.undoStack()->push(new Filter::AddCommand(*this, meta->name(), *filter, insertRow, type));
}
}
delete filter;
}
}
break;
default:
LOG_ERROR() << "Unknown type" << meta->type();
break;
}
return insertRow;
}
int AttachedFiltersModel::addService(Mlt::Service *service)
{
int insertRow = -1;
if (!m_producer) return -1;
QmlMetadata *meta = MAIN.filterController()->metadataForService(service);
if (!meta->allowMultiple()) {
for (int i = 0; i < m_metaList.count(); i++) {
const QmlMetadata *attachedMeta = m_metaList[i];
if (attachedMeta && meta->uniqueId() == attachedMeta->uniqueId()) {
emit duplicateAddFailed(i);
return -1;
}
}
}
Mlt::Filter filter(*service);
if (filter.is_valid()) {
insertRow = findInsertRow(meta);
if (!meta->objectName().isEmpty())
filter.set(kShotcutFilterProperty, meta->objectName().toUtf8().constData());
filter.set_in_and_out(
m_producer->get(kFilterInProperty) ? m_producer->get_int(kFilterInProperty) : m_producer->get_in(),
m_producer->get(kFilterOutProperty) ? m_producer->get_int(kFilterOutProperty) :
m_producer->get_out());
if (isSourceClip()) {
doAddService(*m_producer, filter, insertRow);
} else {
MAIN.undoStack()->push(new Filter::AddCommand(*this, meta->name(), filter, insertRow));
}
}
return insertRow;
}
void AttachedFiltersModel::doAddService(Mlt::Producer &producer, Mlt::Service &service, int row)
{
LOG_DEBUG() << row;
if (!producer.is_valid()) {
LOG_ERROR() << "Invalid producer";
return;
}
switch (service.type()) {
case mlt_service_filter_type: {
int linkRows = 0;
if (producer.type() == mlt_service_chain_type) {
Mlt::Chain chain(producer);
linkRows = chain.link_count() - normalLinkCount(&producer);
}
int normFilterCount = normalFilterCount(&producer);
int mltIndex = normFilterCount + row - linkRows;
if (mltIndex < 0) {
LOG_ERROR() << "Invalid MLT index" << row;
return;
}
Mlt::Filter filter(service);
if (isProducerLoaded(producer)) {
beginInsertRows(QModelIndex(), row, row);
if (MLT.isSeekable())
MLT.pause();
m_event->block();
producer.attach(filter);
producer.move_filter(m_producer->filter_count() - 1, mltIndex);
m_event->unblock();
QmlMetadata *meta = MAIN.filterController()->metadataForService(&service);
m_metaList.insert(row, meta);
endInsertRows();
emit addedOrRemoved(m_producer.data());
} else {
producer.attach(filter);
producer.move_filter(producer.filter_count() - 1, mltIndex);
}
emit changed();
}
break;
case mlt_service_link_type: {
if (producer.type() != mlt_service_chain_type) {
LOG_ERROR() << "Not a chain";
return;
}
Mlt::Chain chain(producer);
int normLinkCount = normalLinkCount(&producer);
int mltIndex = normLinkCount + row;
Mlt::Link link(service);
if (isProducerLoaded(producer)) {
beginInsertRows(QModelIndex(), row, row);
if (MLT.isSeekable())
MLT.pause();
m_event->block();
chain.attach(link);
chain.move_link(chain.link_count() - 1, mltIndex);
m_event->unblock();
QmlMetadata *meta = MAIN.filterController()->metadataForService(&service);
m_metaList.insert(row, meta);
endInsertRows();
emit addedOrRemoved(m_producer.data());
} else {
chain.attach(link);
chain.move_link(chain.link_count() - 1, mltIndex);
}
emit changed();
}
break;
default:
LOG_ERROR() << "invalid service type" << service.type();
break;
}
}
void AttachedFiltersModel::remove(int row)
{
LOG_DEBUG() << row;
if (isSourceClip()) {
doRemoveService(*m_producer, row);
} else {
int mltIndex = mltLinkIndex(m_producer.get(), row);
if (mltIndex >= 0) {
Mlt::Chain chain(*(m_producer.get()));
Mlt::Link *link = chain.link(mltIndex);
MAIN.undoStack()->push(new Filter::RemoveCommand(*this, name(row), *link, row));
delete link;
} else {
mltIndex = mltFilterIndex(m_producer.get(), row);
if (mltIndex >= 0) {
Mlt::Filter *filter = m_producer->filter(mltIndex);
MAIN.undoStack()->push(new Filter::RemoveCommand(*this, name(row), *filter, row));
delete filter;
}
}
}
}
void AttachedFiltersModel::doRemoveService(Mlt::Producer &producer, int row)
{
int filterIndex = mltFilterIndex(&producer, row);
int linkIndex = mltLinkIndex(&producer, row);
LOG_DEBUG() << row << filterIndex << linkIndex;
if (linkIndex >= 0 ) {
Mlt::Chain chain(producer);
Mlt::Link *link = chain.link(linkIndex);
if (isProducerLoaded(producer)) {
beginRemoveRows(QModelIndex(), row, row);
m_event->block();
chain.detach(*link);
m_event->unblock();
m_metaList.removeAt(row);
endRemoveRows();
emit addedOrRemoved(m_producer.get());
} else {
chain.detach(*link);
}
emit changed();
delete link;
} else if (filterIndex >= 0) {
Mlt::Filter *filter = producer.filter(filterIndex);
if (isProducerLoaded(producer)) {
beginRemoveRows(QModelIndex(), row, row);
m_event->block();
producer.detach(*filter);
m_event->unblock();
m_metaList.removeAt(row);
endRemoveRows();
emit addedOrRemoved(m_producer.get());
} else {
producer.detach(*filter);
}
emit changed();
delete filter;
} else {
LOG_WARNING() << "invalid service:" << producer.type();
}
}
bool AttachedFiltersModel::move(int fromRow, int toRow)
{
QModelIndex parent = QModelIndex();
if (fromRow < 0 || toRow < 0) {
return false;
}
return moveRows(parent, fromRow, 1, parent, toRow);
}
void AttachedFiltersModel::reset(Mlt::Producer *producer)
{
beginResetModel();
m_event.reset();
if (producer && producer->is_valid())
m_producer.reset(new Mlt::Producer(producer));
else if (MLT.isClip() && qstrcmp("_hide", MLT.producer()->get("resource")))
m_producer.reset(new Mlt::Producer(MLT.producer()));
else
m_producer.reset();
m_metaList.clear();
if (m_producer && m_producer->is_valid()) {
Mlt::Event *event = m_producer->listen("service-changed", this,
(mlt_listener)AttachedFiltersModel::producerChanged);
m_event.reset(event);
int count = 0;
if (m_producer->type() == mlt_service_chain_type) {
Mlt::Chain chain(*m_producer.data());
count = chain.link_count();
for (int i = 0; i < count; i++) {
Mlt::Link *link = chain.link(i);
if (link && link->is_valid()) {
if (!link->get_int("_loader")) {
QmlMetadata *newMeta = MAIN.filterController()->metadataForService(link);
m_metaList.append(newMeta);
}
}
delete link;
}
}
count = m_producer->filter_count();
for (int i = 0; i < count; i++) {
Mlt::Filter *filter = m_producer->filter(i);
if (filter && filter->is_valid() && !filter->get_int("_loader")
&& !filter->get_int(kShotcutHiddenProperty)) {
QmlMetadata *newMeta = MAIN.filterController()->metadataForService(filter);
m_metaList.append(newMeta);
}
delete filter;
}
}
endResetModel();
emit trackTitleChanged();
emit isProducerSelectedChanged();
emit supportsLinksChanged();
}
Mlt::Producer AttachedFiltersModel::getFilterSetProducer(QmlMetadata *meta)
{
Mlt::Producer filterSetProducer;
auto name = meta->name();
auto dir = QmlApplication::dataDir();
dir.cd("shotcut");
dir.cd("filter-sets");
if (!QFileInfo::exists(dir.filePath(name))) {
dir = Settings.appDataLocation();
if (!dir.cd("filter-sets"))
return filterSetProducer;
}
auto fileName = QUrl::toPercentEncoding(name.toUtf8());
QFile filtersetFile(dir.filePath(fileName));
QString xml;
if (filtersetFile.open(QIODevice::ReadOnly)) {
xml = QString::fromUtf8(filtersetFile.readAll());
} else {
filtersetFile.setFileName(dir.filePath(name));
if (filtersetFile.open(QIODevice::ReadOnly)) {
xml = QString::fromUtf8(filtersetFile.readAll());
}
}
if (MLT.isMltXml(xml)) {
filterSetProducer = Mlt::Producer(MLT.profile(), "xml-string", xml.toUtf8().constData());
}
return filterSetProducer;
}
int AttachedFiltersModel::findInsertRow(QmlMetadata *meta)
{
// Put the filter after the last filter that is less than or equal in sort order.
int insertRow = 0;
for (int i = m_metaList.count() - 1; i >= 0; i--) {
if (sortOrder(m_metaList[i]) <= sortOrder(meta)) {
insertRow = i + 1;
break;
}
}
return insertRow;
}
void AttachedFiltersModel::producerChanged(mlt_properties, AttachedFiltersModel *model)
{
model->reset(model->m_producer.data());
}
bool AttachedFiltersModel::isProducerLoaded(Mlt::Producer &producer) const
{
return m_producer && m_producer->get_service() == producer.get_service();
}
bool AttachedFiltersModel::isSourceClip() const
{
return MLT.isClip() && !m_producer->get_int(kPlaylistIndexProperty);
}
| 28,432
|
C++
|
.cpp
| 782
| 28.021739
| 119
| 0.58465
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,184
|
markersmodel.cpp
|
mltframework_shotcut/src/models/markersmodel.cpp
|
/*
* Copyright (c) 2021-2024 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "markersmodel.h"
#include "commands/markercommands.h"
#include "mainwindow.h"
#include "settings.h"
#include "shotcut_mlt_properties.h"
#include <Logger.h>
enum Columns {
COLUMN_COLOR = 0,
COLUMN_NAME,
COLUMN_START,
COLUMN_END,
COLUMN_DURATION,
COLUMN_COUNT
};
static void markerToProperties(const Markers::Marker &marker, Mlt::Properties *properties,
Mlt::Producer *producer)
{
properties->set("text", qUtf8Printable(marker.text));
properties->set("start", producer->frames_to_time(marker.start, Settings.timeFormat()));
properties->set("end", producer->frames_to_time(marker.end, Settings.timeFormat()));
auto s = QString::asprintf("#%02X%02X%02X", marker.color.red(), marker.color.green(),
marker.color.blue());
properties->set("color", s.toLatin1().constData());
}
static void propertiesToMarker(Mlt::Properties *properties, Markers::Marker &marker,
Mlt::Producer *producer)
{
marker.text = QString::fromUtf8(properties->get("text"));
marker.start = producer->time_to_frames(properties->get("start"));
marker.end = producer->time_to_frames(properties->get("end"));
mlt_color color = properties->get_color("color");
marker.color = QColor::fromRgb(color.r, color.g, color.b, 0xFF);
}
MarkersModel::MarkersModel(QObject *parent)
: QAbstractItemModel(parent)
, m_producer(nullptr)
{
}
MarkersModel::~MarkersModel()
{
}
void MarkersModel::load(Mlt::Producer *producer)
{
beginResetModel();
m_producer = producer;
m_keys.clear();
if (m_producer) {
Mlt::Properties *markerList = m_producer->get_props(kShotcutMarkersProperty);
if (markerList && markerList->is_valid()) {
int count = markerList->count();
for (int i = 0; i < count; i++) {
Mlt::Properties *markerProperties = markerList->get_props_at(i);
if (markerProperties && markerProperties->is_valid()) {
char *key = markerList->get_name(i);
int intKey = QString(key).toInt();
m_keys << intKey;
Markers::Marker marker;
propertiesToMarker(markerProperties, marker, producer);
updateRecentColors(marker.color);
}
delete markerProperties;
}
}
delete markerList;
}
endResetModel();
}
Markers::Marker MarkersModel::getMarker(int markerIndex)
{
Markers::Marker retMarker;
Mlt::Properties *markerProperties = getMarkerProperties(markerIndex);
if (!markerProperties || !markerProperties->is_valid()) {
LOG_ERROR() << "Marker does not exist" << markerIndex;
delete markerProperties;
} else {
propertiesToMarker(markerProperties, retMarker, m_producer);
}
return retMarker;
}
void MarkersModel::remove(int markerIndex)
{
Mlt::Properties *markerProperties = getMarkerProperties(markerIndex);
if (!markerProperties || !markerProperties->is_valid()) {
LOG_ERROR() << "Marker does not exist" << markerIndex;
delete markerProperties;
return;
}
Markers::Marker oldMarker;
propertiesToMarker(markerProperties, oldMarker, m_producer);
Markers::DeleteCommand *command = new Markers::DeleteCommand(*this, oldMarker, markerIndex);
MAIN.undoStack()->push(command);
delete markerProperties;
}
void MarkersModel::doRemove(int markerIndex)
{
if (!m_producer) {
LOG_ERROR() << "No producer";
return;
}
QModelIndex modelIndex = index(markerIndex, 0);
if (!modelIndex.isValid()) {
LOG_ERROR() << "Invalid Index: " << markerIndex;
return;
}
if (modelIndex.row() >= m_keys.count()) {
LOG_ERROR() << "Index out of bounds: " << modelIndex.row() << m_keys.count();
return;
}
Mlt::Properties *markersListProperties = m_producer->get_props(kShotcutMarkersProperty);
if (!markersListProperties || !markersListProperties->is_valid()) {
LOG_ERROR() << "No Markers";
delete markersListProperties;
return;
}
auto marker = getMarker(markerIndex);
beginRemoveRows(QModelIndex(), modelIndex.row(), modelIndex.row());
markersListProperties->clear(qUtf8Printable(QString::number(m_keys[modelIndex.row()])));
m_keys.removeAt(modelIndex.row());
endRemoveRows();
if (marker.end > marker.start) emit rangesChanged();
delete markersListProperties;
emit modified();
}
void MarkersModel::doInsert(int markerIndex, const Markers::Marker &marker )
{
if (!m_producer) {
LOG_ERROR() << "No producer";
return;
}
QModelIndex modelIndex;
if (markerIndex == markerCount())
// Allow inserting after the last marker
modelIndex = createIndex(markerIndex, 0, (int)0);
else
modelIndex = index(markerIndex, 0);
if (!modelIndex.isValid()) {
LOG_ERROR() << "Invalid Index: " << markerIndex;
return;
}
Mlt::Properties *markersListProperties = m_producer->get_props(kShotcutMarkersProperty);
if (!markersListProperties || !markersListProperties->is_valid()) {
delete markersListProperties;
markersListProperties = new Mlt::Properties;
m_producer->set(kShotcutMarkersProperty, *markersListProperties);
}
Mlt::Properties markerProperties;
markerToProperties(marker, &markerProperties, m_producer);
beginInsertRows(QModelIndex(), modelIndex.row(), modelIndex.row());
int key = uniqueKey();
markersListProperties->set(qUtf8Printable(QString::number(key)), markerProperties);
m_keys.insert(modelIndex.row(), key);
endInsertRows();
updateRecentColors(marker.color);
if (marker.end > marker.start) emit rangesChanged();
delete markersListProperties;
emit modified();
}
void MarkersModel::append( const Markers::Marker &marker )
{
if (!m_producer) {
LOG_ERROR() << "No producer";
return;
}
Markers::AppendCommand *command = new Markers::AppendCommand(*this, marker, markerCount());
MAIN.undoStack()->push(command);
}
void MarkersModel::doAppend( const Markers::Marker &marker )
{
if (!m_producer) {
LOG_ERROR() << "No producer";
return;
}
Mlt::Properties *markersListProperties = m_producer->get_props(kShotcutMarkersProperty);
if (!markersListProperties || !markersListProperties->is_valid()) {
delete markersListProperties;
markersListProperties = new Mlt::Properties;
m_producer->set(kShotcutMarkersProperty, *markersListProperties);
}
Mlt::Properties markerProperties;
markerToProperties(marker, &markerProperties, m_producer);
int count = markerCount();
beginInsertRows(QModelIndex(), count, count);
int key = uniqueKey();
markersListProperties->set(qUtf8Printable(QString::number(key)), markerProperties);
m_keys.append(key);
updateRecentColors(marker.color);
endInsertRows();
if (marker.end > marker.start) emit rangesChanged();
delete markersListProperties;
emit modified();
}
void MarkersModel::update(int markerIndex, const Markers::Marker &marker)
{
Mlt::Properties *markerProperties = getMarkerProperties(markerIndex);
if (!markerProperties || !markerProperties->is_valid()) {
LOG_ERROR() << "Marker does not exist" << markerIndex;
delete markerProperties;
return;
}
Markers::Marker oldMarker;
propertiesToMarker(markerProperties, oldMarker, m_producer);
Markers::UpdateCommand *command = new Markers::UpdateCommand(*this, marker, oldMarker, markerIndex);
MAIN.undoStack()->push(command);
delete markerProperties;
}
void MarkersModel::doUpdate(int markerIndex, const Markers::Marker &marker)
{
QModelIndex startIndex = index(markerIndex, 0);
QModelIndex endIndex = index(markerIndex, COLUMN_COUNT - 1);
if (!startIndex.isValid() || !endIndex.isValid()) {
LOG_ERROR() << "Invalid Index: " << startIndex << endIndex;
return;
}
Mlt::Properties *markerProperties = getMarkerProperties(markerIndex);
if (!markerProperties || !markerProperties->is_valid()) {
LOG_ERROR() << "Marker does not exist" << markerIndex;
delete markerProperties;
return;
}
Markers::Marker markerBefore;
propertiesToMarker(markerProperties, markerBefore, m_producer);
markerToProperties(marker, markerProperties, m_producer);
delete markerProperties;
updateRecentColors(marker.color);
emit dataChanged(startIndex, endIndex,
QVector<int>() << Qt::DisplayRole << TextRole << StartRole << EndRole << ColorRole);
if ((markerBefore.end == markerBefore.start && marker.end > marker.start) ||
(markerBefore.end != markerBefore.start && marker.end == marker.start) ||
(markerBefore.text != marker.text)) {
emit rangesChanged();
}
emit modified();
}
void MarkersModel::doClear()
{
if (!m_producer) {
LOG_ERROR() << "No producer";
return;
}
beginResetModel();
m_keys.clear();
static_cast<Mlt::Properties *>(m_producer)->clear(kShotcutMarkersProperty);
endResetModel();
emit modified();
emit rangesChanged();
}
void MarkersModel::doReplace(QList<Markers::Marker> &markers)
{
if (!m_producer) {
LOG_ERROR() << "No producer";
return;
}
beginResetModel();
m_keys.clear();
Mlt::Properties *markersListProperties = new Mlt::Properties;
m_producer->set(kShotcutMarkersProperty, *markersListProperties);
for (int i = 0; i < markers.size(); i++) {
Mlt::Properties markerProperties;
markerToProperties(markers[i], &markerProperties, m_producer);
markersListProperties->set(qUtf8Printable(QString::number(i)), markerProperties);
m_keys << i;
m_recentColors.insert(markers[i].color.rgb(), markers[i].color.name());
}
endResetModel();
delete markersListProperties;
emit modified();
emit rangesChanged();
emit recentColorsChanged();
}
void MarkersModel::doShift(int shiftPosition, int shiftAmount)
{
if (!m_producer) {
LOG_ERROR() << "No producer";
return;
}
int minIndex = -1;
int maxIndex = -1;
QScopedPointer<Mlt::Properties> markerList(m_producer->get_props(kShotcutMarkersProperty));
if (markerList && markerList->is_valid()) {
for (const auto i : std::as_const(m_keys)) {
QScopedPointer<Mlt::Properties> markerProperties(markerList->get_props(qUtf8Printable(
QString::number(i))));
if (markerProperties && markerProperties->is_valid()) {
Markers::Marker marker;
propertiesToMarker(markerProperties.data(), marker, m_producer);
if (marker.start >= shiftPosition) {
marker.start += shiftAmount;
marker.end += shiftAmount;
markerToProperties(marker, markerProperties.data(), m_producer);
int markerIndex = m_keys[i];
if (minIndex == -1 || markerIndex < minIndex) minIndex = markerIndex;
if (maxIndex == -1 || markerIndex > maxIndex) maxIndex = markerIndex;
}
}
}
}
if (minIndex != -1) {
QModelIndex startIndex = index(minIndex, COLUMN_START);
QModelIndex endIndex = index(maxIndex, COLUMN_END);
emit dataChanged(startIndex, endIndex, QVector<int>() << Qt::DisplayRole << StartRole << EndRole);
emit modified();
emit rangesChanged();
}
}
void MarkersModel::move(int markerIndex, int start, int end)
{
Mlt::Properties *markerProperties = getMarkerProperties(markerIndex);
if (!markerProperties || !markerProperties->is_valid()) {
LOG_ERROR() << "Marker does not exist" << markerIndex;
delete markerProperties;
return;
}
Markers::Marker oldMarker;
propertiesToMarker(markerProperties, oldMarker, m_producer);
Markers::Marker newMarker = oldMarker;
newMarker.start = start;
newMarker.end = end;
Markers::UpdateCommand *command = new Markers::UpdateCommand(*this, newMarker, oldMarker,
markerIndex);
MAIN.undoStack()->push(command);
}
void MarkersModel::setColor(int markerIndex, const QColor &color)
{
Mlt::Properties *markerProperties = getMarkerProperties(markerIndex);
if (!markerProperties || !markerProperties->is_valid()) {
LOG_ERROR() << "Marker does not exist" << markerIndex;
delete markerProperties;
return;
}
Markers::Marker oldMarker;
propertiesToMarker(markerProperties, oldMarker, m_producer);
Markers::Marker newMarker = oldMarker;
newMarker.color = color;
Markers::UpdateCommand *command = new Markers::UpdateCommand(*this, newMarker, oldMarker,
markerIndex);
MAIN.undoStack()->push(command);
}
void MarkersModel::clear()
{
if (!m_producer) {
LOG_ERROR() << "No producer";
return;
}
Mlt::Properties *markersListProperties = m_producer->get_props(kShotcutMarkersProperty);
if (!markersListProperties || !markersListProperties->is_valid()) {
delete markersListProperties;
return;
} else {
int count = markersListProperties->count();
QList<Markers::Marker> markerList;
for (int i = 0; i < count; i++) {
Mlt::Properties *markerProperties = markersListProperties->get_props_at(i);
if (markerProperties && markerProperties->is_valid()) {
Markers::Marker marker;
propertiesToMarker(markerProperties, marker, m_producer);
markerList << marker;
}
delete markerProperties;
}
Markers::ClearCommand *command = new Markers::ClearCommand(*this, markerList);
MAIN.undoStack()->push(command);
}
delete markersListProperties;
}
int MarkersModel::markerCount() const
{
if (!m_producer) {
return 0;
}
return m_keys.count();
}
int MarkersModel::keyIndex(int key) const
{
int index = -1;
for (int i = 0; i < m_keys.size(); i++) {
if (m_keys[i] == key) {
index = i;
break;
}
}
return index;
}
int MarkersModel::uniqueKey() const
{
int key = 0;
while (keyIndex(key) >= 0) {
key++;
}
return key;
}
int MarkersModel::markerIndexForPosition(int position)
{
QScopedPointer<Mlt::Properties> markerList(m_producer->get_props(kShotcutMarkersProperty));
if (markerList && markerList->is_valid()) {
for (const auto i : std::as_const(m_keys)) {
QScopedPointer<Mlt::Properties> marker(markerList->get_props(qUtf8Printable(QString::number(i))));
if (marker && marker->is_valid()) {
if (position == m_producer->time_to_frames(marker->get("start")) ||
position == m_producer->time_to_frames(marker->get("end")))
return keyIndex(i);
}
}
}
return -1;
}
int MarkersModel::markerIndexForRange(int start, int end)
{
QScopedPointer<Mlt::Properties> markerList(m_producer->get_props(kShotcutMarkersProperty));
if (markerList && markerList->is_valid()) {
for (const auto i : std::as_const(m_keys)) {
QScopedPointer<Mlt::Properties> marker(markerList->get_props(qUtf8Printable(QString::number(i))));
if (marker && marker->is_valid()) {
if (start == m_producer->time_to_frames(marker->get("start")) &&
end == m_producer->time_to_frames(marker->get("end")))
return keyIndex(i);
}
}
}
return -1;
}
int MarkersModel::rangeMarkerIndexForPosition(int position)
{
QScopedPointer<Mlt::Properties> markerList(m_producer->get_props(kShotcutMarkersProperty));
if (markerList && markerList->is_valid()) {
for (const auto i : std::as_const(m_keys)) {
QScopedPointer<Mlt::Properties> marker(markerList->get_props(qUtf8Printable(QString::number(i))));
if (marker && marker->is_valid()) {
int start = m_producer->time_to_frames(marker->get("start"));
int end = m_producer->time_to_frames(marker->get("end"));
if (position >= start && position <= end && start != end)
return keyIndex(i);
}
}
}
return -1;
}
int MarkersModel::nextMarkerPosition(int position)
{
int nextPosition = -1;
if (!m_producer) {
LOG_ERROR() << "No producer";
return nextPosition;
}
QScopedPointer<Mlt::Properties> markerList(m_producer->get_props(kShotcutMarkersProperty));
if (markerList && markerList->is_valid()) {
for (const auto i : std::as_const(m_keys)) {
QScopedPointer<Mlt::Properties> marker(markerList->get_props(qUtf8Printable(QString::number(i))));
if (marker && marker->is_valid()) {
int markerPosition = m_producer->time_to_frames(marker->get("start"));
if (markerPosition > position && (nextPosition == -1 || markerPosition < nextPosition)) {
nextPosition = markerPosition;
}
markerPosition = m_producer->time_to_frames(marker->get("end"));
if (markerPosition > position && (nextPosition == -1 || markerPosition < nextPosition)) {
nextPosition = markerPosition;
}
}
}
}
return nextPosition;
}
int MarkersModel::prevMarkerPosition(int position)
{
int prevPosition = -1;
if (!m_producer) {
LOG_ERROR() << "No producer";
return prevPosition;
}
QScopedPointer<Mlt::Properties> markerList(m_producer->get_props(kShotcutMarkersProperty));
if (markerList && markerList->is_valid()) {
for (const auto i : std::as_const(m_keys)) {
QScopedPointer<Mlt::Properties> marker(markerList->get_props(qUtf8Printable(QString::number(i))));
if (marker && marker->is_valid()) {
int markerPosition = m_producer->time_to_frames(marker->get("start"));
if (markerPosition < position && (prevPosition == -1 || markerPosition > prevPosition)) {
prevPosition = markerPosition;
}
markerPosition = m_producer->time_to_frames(marker->get("end"));
if (markerPosition < position && (prevPosition == -1 || markerPosition > prevPosition)) {
prevPosition = markerPosition;
}
}
}
}
return prevPosition;
}
QModelIndex MarkersModel::modelIndexForRow(int row)
{
return index(row, 0);
}
QMap<int, QString> MarkersModel::ranges()
{
QMap<int, QString> result;
QScopedPointer<Mlt::Properties> markerList(m_producer->get_props(kShotcutMarkersProperty));
if (markerList && markerList->is_valid()) {
for (const auto i : std::as_const(m_keys)) {
QScopedPointer<Mlt::Properties> marker(markerList->get_props(qUtf8Printable(QString::number(i))));
if (marker && marker->is_valid()) {
Markers::Marker m;
propertiesToMarker(marker.get(), m, m_producer);
if (m.end > m.start) {
result[keyIndex(i)] = m.text;
}
}
}
}
return result;
}
QStringList MarkersModel::recentColors()
{
return m_recentColors.values();
}
QList<Markers::Marker> MarkersModel::getMarkers() const
{
QList<Markers::Marker> markers;
if (!m_producer || !m_producer->is_valid())
return markers;
QScopedPointer<Mlt::Properties> markerList(m_producer->get_props(kShotcutMarkersProperty));
if (markerList && markerList->is_valid()) {
for (const auto i : std::as_const(m_keys)) {
QScopedPointer<Mlt::Properties> marker(markerList->get_props(qUtf8Printable(QString::number(i))));
if (marker && marker->is_valid()) {
Markers::Marker m;
propertiesToMarker(marker.get(), m, m_producer);
markers << m;
}
}
}
return markers;
}
QList<QColor> MarkersModel::allColors() const
{
QList<QColor> result;
for (auto &m : getMarkers()) {
if (!result.contains(m.color)) {
result << m.color;
}
}
return result;
}
Mlt::Properties *MarkersModel::getMarkerProperties(int markerIndex)
{
Mlt::Properties *markerProperties = nullptr;
if (!m_producer) {
LOG_ERROR() << "No producer";
return markerProperties;
}
QModelIndex modelIndex = index(markerIndex, 0);
if (!modelIndex.isValid()) {
LOG_ERROR() << "Invalid Index: " << markerIndex;
return markerProperties;
}
Mlt::Properties *markersListProperties = m_producer->get_props(kShotcutMarkersProperty);
if (!markersListProperties || !markersListProperties->is_valid()) {
LOG_ERROR() << "No Markers";
} else {
markerProperties = markersListProperties->get_props(qUtf8Printable(QString::number(
m_keys[modelIndex.row()])));
if (!markerProperties || !markerProperties->is_valid()) {
LOG_ERROR() << "Marker does not exist" << modelIndex.row();
delete markerProperties;
markerProperties = nullptr;
}
}
delete markersListProperties;
return markerProperties;
}
void MarkersModel::updateRecentColors(const QColor &color)
{
m_recentColors.insert(color.rgb(), color.name());
Settings.setMarkerColor(color);
emit recentColorsChanged();
}
int MarkersModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent)
return markerCount();
}
int MarkersModel::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent)
return COLUMN_COUNT;
}
QVariant MarkersModel::data(const QModelIndex &index, int role) const
{
QVariant result;
switch (role) {
case Qt::ToolTipRole:
case Qt::StatusTipRole:
case Qt::DecorationRole:
case Qt::FontRole:
case Qt::TextAlignmentRole:
case Qt::CheckStateRole:
case Qt::SizeHintRole:
return result;
}
if (!m_producer) {
LOG_DEBUG() << "No Producer: " << index.row() << index.column() << role;
return result;
}
if (!index.isValid() || index.column() < 0 || index.column() >= COLUMN_COUNT || index.row() < 0
|| index.row() >= markerCount()) {
LOG_ERROR() << "Invalid Index: " << index.row() << index.column() << role;
return result;
}
Mlt::Properties *markersListProperties = m_producer->get_props(kShotcutMarkersProperty);
if (!markersListProperties || !markersListProperties->is_valid()) {
LOG_DEBUG() << "No Markers: " << index.row() << index.column() << role;
delete markersListProperties;
return result;
}
Mlt::Properties *markerProperties = markersListProperties->get_props(qUtf8Printable(QString::number(
m_keys[index.row()])));
if (!markerProperties || !markerProperties->is_valid()) {
LOG_DEBUG() << "Marker does not exist: " << index.row() << index.column() << role <<
m_keys[index.row()];
delete markerProperties;
delete markersListProperties;
return result;
}
Markers::Marker marker;
propertiesToMarker(markerProperties, marker, m_producer);
switch (role) {
case Qt::DisplayRole:
switch (index.column()) {
case COLUMN_COLOR:
result = marker.color;
break;
case COLUMN_NAME:
result = marker.text;
break;
case COLUMN_START:
result = QString(m_producer->frames_to_time(marker.start, Settings.timeFormat()));
break;
case COLUMN_END:
result = QString(m_producer->frames_to_time(marker.end, Settings.timeFormat()));
break;
case COLUMN_DURATION:
result = QString(m_producer->frames_to_time(marker.end - marker.start + 1, Settings.timeFormat()));
break;
default:
LOG_ERROR() << "Invalid Column" << index.column() << role;
break;
}
break;
case Qt::BackgroundRole:
if (index.column() == COLUMN_COLOR) {
result = marker.color;
}
break;
case Qt::ForegroundRole:
if (index.column() == COLUMN_COLOR) {
// Pick a contrasting color
if (marker.color.value() < 127) {
result = QColor(Qt::white);
} else {
result = QColor(Qt::black);
}
}
break;
case TextRole:
result = marker.text;
break;
case StartRole:
result = marker.start;
break;
case EndRole:
result = marker.end;
break;
case ColorRole:
result = marker.color;
break;
default:
LOG_ERROR() << "Invalid Role" << index.row() << index.column() << roleNames()[role] << role;
break;
}
delete markersListProperties;
delete markerProperties;
return result;
}
QVariant MarkersModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (role == Qt::DisplayRole && orientation == Qt::Horizontal) {
switch (section) {
case COLUMN_COLOR:
return tr("Color");
case COLUMN_NAME:
return tr("Name");
case COLUMN_START:
return tr("Start");
case COLUMN_END:
return tr("End");
case COLUMN_DURATION:
return tr("Duration");
default:
break;
}
}
return QVariant();
}
QModelIndex MarkersModel::index(int row, int column, const QModelIndex &parent) const
{
Q_UNUSED(parent)
if (column < 0 || column >= COLUMN_COUNT || row < 0 || row >= markerCount())
return QModelIndex();
return createIndex(row, column, (int)0);
}
QModelIndex MarkersModel::parent(const QModelIndex &index) const
{
Q_UNUSED(index)
return QModelIndex();
}
QHash<int, QByteArray> MarkersModel::roleNames() const
{
QHash<int, QByteArray> roles = QAbstractItemModel::roleNames();
roles[TextRole] = "text";
roles[StartRole] = "start";
roles[EndRole] = "end";
roles[ColorRole] = "color";
return roles;
}
| 27,627
|
C++
|
.cpp
| 737
| 29.884668
| 115
| 0.62665
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,185
|
subtitles.cpp
|
mltframework_shotcut/src/models/subtitles.cpp
|
/*
* Copyright (c) 2024 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "subtitles.h"
#include <cmath>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#ifdef _WIN32
#include <windows.h>
static wchar_t *utf8ToWide(const char *strUtf8)
{
wchar_t *strWide = nullptr;
int n = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, strUtf8, -1, NULL, 0);
if (n > 0) {
strWide = (wchar_t *) calloc(n, sizeof(wchar_t));
if (strWide) {
MultiByteToWideChar(CP_UTF8, 0, strUtf8, -1, strWide, n);
}
}
return strWide;
}
#endif /* ifdef _WIN32 */
static Subtitles::SubtitleVector readFromSrtStream(std::istream &stream)
{
enum {
STATE_SEEKING_NUM,
STATE_READING_TIME,
STATE_READING_TEXT,
};
std::string line;
std::string text;
int state = STATE_SEEKING_NUM;
Subtitles::SubtitleItem item;
Subtitles::SubtitleVector ret;
while (std::getline(stream, line)) {
switch (state) {
case STATE_SEEKING_NUM: {
state = STATE_READING_TIME;
for (char &c : line) {
if (!std::isdigit(c)) {
// Bad line. Keep seeking
state = STATE_SEEKING_NUM;
break;
}
}
break;
}
case STATE_READING_TIME: {
int sHours, sMinutes, sSeconds, sMiliseconds, eHours, eMinutes, eSeconds, eMiliseconds;
const int ret = std::sscanf(line.c_str(),
"%d:%d:%d,%d --> %d:%d:%d,%d",
&sHours,
&sMinutes,
&sSeconds,
&sMiliseconds,
&eHours,
&eMinutes,
&eSeconds,
&eMiliseconds);
if (ret != 8) {
state = STATE_SEEKING_NUM;
break;
}
item.start = (((((sHours * 60) + sMinutes) * 60) + sSeconds) * 1000) + sMiliseconds;
item.end = (((((eHours * 60) + eMinutes) * 60) + eSeconds) * 1000) + eMiliseconds;
item.text.clear();
state = STATE_READING_TEXT;
break;
}
case STATE_READING_TEXT: {
if (!line.empty()) {
if (!item.text.empty()) {
item.text += "\n";
}
item.text += line;
} else {
ret.push_back(item);
state = STATE_SEEKING_NUM;
}
break;
}
}
}
if (state == STATE_READING_TEXT) {
ret.push_back(item);
}
return ret;
}
static std::string msToSrtTime(int64_t ms)
{
int hours = std::floor(ms / 1000.0 / 60.0 / 60.0);
int minutes = std::floor((ms - (hours * 60 * 60 * 1000)) / 1000.0 / 60.0);
int seconds = std::floor((ms - ((hours * 60 + minutes) * 60 * 1000)) / 1000.0);
int miliseconds = ms - (((hours * 60 + minutes) * 60 + seconds) * 1000);
char buff[13];
std::snprintf(buff, sizeof(buff), "%02d:%02d:%02d,%03d", hours, minutes, seconds, miliseconds);
return std::string(buff);
}
static bool writeToSrtStream(std::ostream &stream, const Subtitles::SubtitleVector &items)
{
if (items.size() == 0) {
return true;
}
int i = 1;
for (auto item : items) {
stream << i << "\n";
stream << msToSrtTime(item.start) << " --> " << msToSrtTime(item.end) << "\n";
stream << item.text;
if (!item.text.empty() && item.text.back() != '\n') {
stream << "\n";
}
stream << "\n";
i++;
}
return true;
}
Subtitles::SubtitleVector Subtitles::readFromSrtFile(const std::string &path)
{
#ifdef _WIN32
wchar_t *wpath = utf8ToWide(path.c_str());
std::ifstream fileStream(wpath);
free(wpath);
#else
std::ifstream fileStream(path);
#endif
return readFromSrtStream(fileStream);
}
bool Subtitles::writeToSrtFile(const std::string &path, const SubtitleVector &items)
{
#ifdef _WIN32
wchar_t *wpath = utf8ToWide(path.c_str());
std::ofstream fileStream(wpath, std::ios::out | std::ios::trunc);
free(wpath);
#else
std::ofstream fileStream(path.c_str(), std::ios::out | std::ios::trunc);
#endif
if (!fileStream.is_open()) {
return false;
}
return writeToSrtStream(fileStream, items);
}
Subtitles::SubtitleVector Subtitles::readFromSrtString(const std::string &text)
{
std::istringstream textStream(text);
return readFromSrtStream(textStream);
}
bool Subtitles::writeToSrtString(std::string &text, const Subtitles::SubtitleVector &items)
{
std::ostringstream textStream;
bool result = writeToSrtStream(textStream, items);
text = textStream.str();
return result;
}
int Subtitles::indexForTime(const Subtitles::SubtitleVector &items,
int64_t msTime,
int searchStart,
int msMargin)
{
// Return -1 if there is no subtitle for the time.
int index = -1;
int count = (int) items.size();
if (count == 0) {
// Nothing to search
} else if (count > 0 && (items[0].start - msMargin) > msTime) {
// No text if before the first item;
} else if (count > 1 && items[count - 1].end < msTime) {
// No text if after the last item;
} else if (searchStart > -1 && searchStart < count
&& (items[searchStart].start - msMargin) <= msTime
&& items[searchStart].end >= msTime) {
// First see if this is the same as the last subtitle
index = searchStart;
} else if (searchStart > -1 && (searchStart + 1) < count && items[searchStart].end < msTime
&& (items[searchStart + 1].start - msMargin) > msTime) {
// No text if between the previous and next subtitle
} else if (searchStart > -1 && (searchStart + 1) < count
&& (items[searchStart + 1].start - msMargin) <= msTime
&& items[searchStart + 1].end >= msTime) {
// See if this is the next subtitle
index = searchStart + 1;
} else {
// Perform a full search from the beginning
int i = 0;
for (i = 0; i < count; i++) {
if ((items[i].start - msMargin) <= msTime && items[i].end >= msTime) {
index = i;
break;
} else if (items[i].end > msTime) {
break;
}
}
}
return index;
}
| 7,343
|
C++
|
.cpp
| 209
| 26.401914
| 99
| 0.552558
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,186
|
subtitlesmodel.cpp
|
mltframework_shotcut/src/models/subtitlesmodel.cpp
|
/*
* Copyright (c) 2024 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "subtitlesmodel.h"
#include <Logger.h>
#include "mainwindow.h"
#include "mltcontroller.h"
#include "settings.h"
#include "shotcut_mlt_properties.h"
#include "commands/subtitlecommands.h"
#include <QTimer>
#include <cmath>
static const quintptr NO_PARENT_ID = quintptr(-1);
enum Columns {
COLUMN_TEXT = 0,
COLUMN_START,
COLUMN_END,
COLUMN_DURATION,
COLUMN_COUNT
};
SubtitlesModel::SubtitlesModel(QObject *parent)
: QAbstractItemModel(parent)
, m_producer(nullptr)
, m_commitTrack(-1)
{
connect(&Settings, &ShotcutSettings::timeFormatChanged, this, [&]() {
if (m_items.size() > 0) {
beginResetModel();
endResetModel();
}
});
// The entire SRT document is written to an MLT property for storage.
// So only write it after some delay to avoid frequent property updates.
m_commitTimer = new QTimer(this);
m_commitTimer->setSingleShot(true);
m_commitTimer->setInterval(500);
connect(m_commitTimer, &QTimer::timeout, this, [&]() {
if (m_commitTrack == -1) {
return;
}
commitToFeed(m_commitTrack);
m_commitTrack = -1;
});
}
SubtitlesModel::~SubtitlesModel()
{
}
void SubtitlesModel::load(Mlt::Producer *producer)
{
beginResetModel();
m_producer = producer;
m_items.clear();
m_tracks.clear();
if (m_producer) {
for (int i = 0; i < producer->filter_count(); i++) {
QScopedPointer<Mlt::Filter> filter(producer->filter(i));
if (!filter || !filter->is_valid()) {
continue;
}
if (!::qstrcmp(filter->get("mlt_service"), "subtitle_feed")
&& filter->property_exists("text")) {
SubtitleTrack track;
track.name = QString::fromUtf8(filter->get("feed"));
track.lang = QString::fromUtf8(filter->get("lang"));
m_tracks.push_back(track);
m_items.resize(m_tracks.size());
Subtitles::SubtitleVector items = Subtitles::readFromSrtString(filter->get("text"));
m_items[m_items.size() - 1] = QList(items.cbegin(), items.cend());
}
}
}
endResetModel();
emit tracksChanged(m_tracks.size());
}
bool SubtitlesModel::isValid() const
{
return m_producer && m_producer->is_valid();
}
int64_t SubtitlesModel::maxTime() const
{
int64_t maxTime = 0;
if (m_producer && m_producer->is_valid()) {
maxTime = std::floor((double)m_producer->get_playtime() * 1000.0 / m_producer->get_fps());
}
return maxTime;
}
int SubtitlesModel::trackCount() const
{
return m_tracks.size();
}
QModelIndex SubtitlesModel::trackModelIndex(int trackIndex) const
{
return index(trackIndex, 0);
}
QList<SubtitlesModel::SubtitleTrack> SubtitlesModel::getTracks() const
{
return m_tracks;
}
int SubtitlesModel::getTrackIndex(const QString &name)
{
int index = -1;
for (int i = 0; i < m_tracks.size(); i++) {
if (m_tracks[i].name == name) {
return i;
}
}
return index;
}
SubtitlesModel::SubtitleTrack SubtitlesModel::getTrack(const QString &name)
{
for (auto &track : m_tracks) {
if (track.name == name) {
return track;
}
}
return SubtitlesModel::SubtitleTrack();
}
SubtitlesModel::SubtitleTrack SubtitlesModel::getTrack(int index)
{
if (index < m_tracks.size() && index >= 0) {
return m_tracks[index];
}
return SubtitlesModel::SubtitleTrack();
}
void SubtitlesModel::requestFeedCommit(int trackIndex)
{
if (trackIndex >= m_items.size()) {
LOG_ERROR() << "Invalid track Index" << trackIndex;
return;
}
m_commitTimer->stop();
if (m_commitTrack != -1 && m_commitTrack != trackIndex) {
commitToFeed(m_commitTrack);
}
m_commitTrack = trackIndex;
m_commitTimer->start();
}
void SubtitlesModel::commitToFeed(int trackIndex)
{
if (trackIndex >= m_items.size()) {
LOG_ERROR() << "Invalid track Index" << trackIndex;
return;
}
int feedFilterIndex = 0;
for (int i = 0; i < m_producer->filter_count(); i++) {
QScopedPointer<Mlt::Filter> filter(m_producer->filter(i));
if (!filter || !filter->is_valid()) {
continue;
}
if (filter->get("mlt_service") == QStringLiteral("subtitle_feed")) {
if (feedFilterIndex == trackIndex) {
Subtitles::SubtitleVector items(m_items[trackIndex].constBegin(), m_items[trackIndex].constEnd());
std::string text;
Subtitles::writeToSrtString(text, items);
filter->set("text", text.c_str());
break;
}
feedFilterIndex++;
}
}
emit modified();
}
void SubtitlesModel::addTrack(SubtitlesModel::SubtitleTrack &track)
{
if (!m_producer) {
LOG_DEBUG() << "No producer";
return;
}
Subtitles::InsertTrackCommand *command = new Subtitles::InsertTrackCommand(*this, track,
m_tracks.size());
MAIN.undoStack()->push(command);
}
void SubtitlesModel::removeTrack(QString &name)
{
if (!m_producer) {
LOG_DEBUG() << "No producer";
return;
}
for (int i = 0; i < m_tracks.size(); i++) {
if (m_tracks[i].name == name) {
Subtitles::RemoveTrackCommand *command = new Subtitles::RemoveTrackCommand(*this, i);
MAIN.undoStack()->push(command);
return;
}
}
LOG_ERROR() << "Track not found:" << name;
}
void SubtitlesModel::editTrack(int trackIndex, SubtitlesModel::SubtitleTrack &track)
{
if (!m_producer) {
LOG_DEBUG() << "No producer";
return;
}
Subtitles::EditTrackCommand *command = new Subtitles::EditTrackCommand(*this, track, trackIndex);
MAIN.undoStack()->push(command);
}
int SubtitlesModel::itemCount(int trackIndex) const
{
if (trackIndex < 0 || trackIndex >= m_tracks.size()) {
LOG_DEBUG() << "Invalid track index";
return 0;
}
return m_items[trackIndex].size();
}
int64_t SubtitlesModel::endTime(int trackIndex) const
{
int64_t endTime = 0;
int count = m_items[trackIndex].size();
if (count > 0) {
endTime = m_items[trackIndex][count - 1].end;
}
return endTime;
}
QModelIndex SubtitlesModel::itemModelIndex(int trackIndex, int itemIndex) const
{
return index(itemIndex, 0, index(trackIndex, 0));
}
int SubtitlesModel::itemIndexAtTime(int trackIndex, int64_t msTime) const
{
int ret = -1;
for (int i = 0; i < m_items[trackIndex].size(); i++) {
if (m_items[trackIndex][i].start <= msTime && m_items[trackIndex][i].end >= msTime) {
ret = i;
break;
} else if (m_items[trackIndex][i].start > msTime) {
break;
}
}
return ret;
}
int SubtitlesModel::itemIndexBeforeTime(int trackIndex, int64_t msTime) const
{
int ret = -1;
int itemCount = m_items[trackIndex].size();
for (int i = 0; i < itemCount; i++) {
if (m_items[trackIndex][i].start >= msTime) {
ret = i - 1;
break;
}
}
if (ret == -1 && m_items[trackIndex].size() > 0
&& m_items[trackIndex][itemCount - 1].end < msTime) {
ret = itemCount - 1;
}
return ret;
}
int SubtitlesModel::itemIndexAfterTime(int trackIndex, int64_t msTime) const
{
int ret = -1;
int itemCount = m_items[trackIndex].size();
for (int i = 0; i < itemCount; i++) {
if (m_items[trackIndex][i].start > msTime) {
ret = i;
break;
}
}
return ret;
}
const Subtitles::SubtitleItem &SubtitlesModel::getItem(int trackIndex, int itemIndex) const
{
return m_items[trackIndex][itemIndex];
}
void SubtitlesModel::importSubtitles(int trackIndex, int64_t msTime,
QList<Subtitles::SubtitleItem> &items)
{
if (!m_producer) {
LOG_DEBUG() << "No producer";
return;
}
Subtitles::OverwriteSubtitlesCommand *command = new Subtitles::OverwriteSubtitlesCommand(*this,
trackIndex, items);
command->setText(QObject::tr("Import %1 subtitle items").arg(items.size()));
MAIN.undoStack()->push(command);
}
void SubtitlesModel::importSubtitlesToNewTrack(SubtitlesModel::SubtitleTrack &track,
QList<Subtitles::SubtitleItem> &items)
{
if (!m_producer) {
LOG_DEBUG() << "No producer";
return;
}
int trackIndex = m_tracks.size();
MAIN.undoStack()->beginMacro(QObject::tr("Import %1 subtitle items").arg(items.size()));
Subtitles::InsertTrackCommand *trackCommand = new Subtitles::InsertTrackCommand(*this, track,
trackIndex);
MAIN.undoStack()->push(trackCommand);
Subtitles::OverwriteSubtitlesCommand *overwriteCommand = new Subtitles::OverwriteSubtitlesCommand(
*this, trackIndex, items);
MAIN.undoStack()->push(overwriteCommand);
MAIN.undoStack()->endMacro();
}
void SubtitlesModel::exportSubtitles(const QString &filePath, int trackIndex) const
{
if (!m_producer) {
LOG_DEBUG() << "No producer";
return;
}
Subtitles::SubtitleVector items(m_items[trackIndex].constBegin(), m_items[trackIndex].constEnd());
Subtitles::writeToSrtFile(filePath.toUtf8().toStdString(), items);
}
void SubtitlesModel::overwriteItem(int trackIndex, const Subtitles::SubtitleItem &item)
{
QList<Subtitles::SubtitleItem> items;
items.append(item);
Subtitles::OverwriteSubtitlesCommand *command = new Subtitles::OverwriteSubtitlesCommand(*this,
trackIndex, items);
MAIN.undoStack()->push(command);
}
void SubtitlesModel::appendItem(int trackIndex, const Subtitles::SubtitleItem &item)
{
QList<Subtitles::SubtitleItem> items;
items.append(item);
Subtitles::OverwriteSubtitlesCommand *command = new Subtitles::OverwriteSubtitlesCommand(*this,
trackIndex, items);
command->setText(QObject::tr("Append subtitle"));
MAIN.undoStack()->push(command);
}
void SubtitlesModel::removeItems(int trackIndex, int firstItemIndex, int lastItemIndex)
{
int count = m_items[trackIndex].size();
if (firstItemIndex < 0 || firstItemIndex >= count || lastItemIndex < 0 || lastItemIndex >= count) {
LOG_ERROR() << "Invalid index to remove" << firstItemIndex << lastItemIndex;
}
QList<Subtitles::SubtitleItem> items;
for (int i = firstItemIndex; i <= lastItemIndex; i++) {
items.append(m_items[trackIndex][i]);
}
Subtitles::RemoveSubtitlesCommand *command = new Subtitles::RemoveSubtitlesCommand(*this,
trackIndex, items);
MAIN.undoStack()->push(command);
}
void SubtitlesModel::setItemStart(int trackIndex, int itemIndex, int64_t msTime)
{
if (trackIndex < 0 || trackIndex >= m_items.size()) {
LOG_ERROR() << "Invalid track index" << trackIndex;
return;
}
if (itemIndex < 0 || itemIndex >= m_items[trackIndex].size()) {
LOG_ERROR() << "Invalid item index" << itemIndex;
return;
}
if (msTime >= m_items[trackIndex][itemIndex].end) {
LOG_ERROR() << "Start can not be greater than end" << msTime << m_items[trackIndex][itemIndex].end;
return;
}
if (itemIndex > 0 && msTime < m_items[trackIndex][itemIndex - 1].end) {
LOG_ERROR() << "Start can not precede previous end" << msTime << m_items[trackIndex][itemIndex -
1].end;
return;
}
Subtitles::SetStartCommand *command = new Subtitles::SetStartCommand(*this, trackIndex, itemIndex,
msTime);
MAIN.undoStack()->push(command);
}
void SubtitlesModel::setItemEnd(int trackIndex, int itemIndex, int64_t msTime)
{
if (trackIndex < 0 || trackIndex >= m_items.size()) {
LOG_ERROR() << "Invalid track index" << trackIndex;
return;
}
if (itemIndex < 0 || itemIndex >= m_items[trackIndex].size()) {
LOG_ERROR() << "Invalid item index" << itemIndex;
return;
}
if (msTime <= m_items[trackIndex][itemIndex].start) {
LOG_ERROR() << "End can not be less than start" << msTime << m_items[trackIndex][itemIndex].start;
return;
}
if (itemIndex < (m_items[trackIndex].size() - 1)
&& msTime > m_items[trackIndex][itemIndex + 1].start) {
LOG_ERROR() << "End can not be greater than next start" << msTime << m_items[trackIndex][itemIndex +
1].start;
return;
}
Subtitles::SetEndCommand *command = new Subtitles::SetEndCommand(*this, trackIndex, itemIndex,
msTime);
MAIN.undoStack()->push(command);
}
void SubtitlesModel::setText(int trackIndex, int itemIndex, const QString &text)
{
Subtitles::SetTextCommand *command = new Subtitles::SetTextCommand(*this, trackIndex, itemIndex,
text);
MAIN.undoStack()->push(command);
}
void SubtitlesModel::moveItems(int trackIndex, int firstItemIndex, int lastItemIndex,
int64_t msTime)
{
int count = m_items[trackIndex].size();
if (firstItemIndex < 0 || firstItemIndex >= count || lastItemIndex < 0 || lastItemIndex >= count) {
LOG_ERROR() << "Invalid index to move" << firstItemIndex << lastItemIndex;
}
QList<Subtitles::SubtitleItem> items;
for (int i = firstItemIndex; i <= lastItemIndex; i++) {
items.append(m_items[trackIndex][i]);
}
Subtitles::MoveSubtitlesCommand *command = new Subtitles::MoveSubtitlesCommand(*this, trackIndex,
items, msTime);
MAIN.undoStack()->push(command);
}
bool SubtitlesModel::validateMove(const QModelIndexList &items, int64_t msTime)
{
if (items.size() <= 0) {
return false;
}
if (msTime < 0) {
return false;
}
int trackIndex = items[0].parent().row();
// Check if there is a big enough gap at this location to move without conflict.
int firstItemIndex = items[0].row();
auto firstItem = m_items[trackIndex][firstItemIndex];
int lastItemIndex = items[items.size() - 1].row();
auto lastItem = m_items[trackIndex][lastItemIndex];
int64_t duration = lastItem.end - firstItem.start;
int64_t newEndTime = msTime + duration;
int itemCount = m_items[trackIndex].size();
int gapItemIndex = itemIndexAtTime(trackIndex, msTime);
if (gapItemIndex == - 1) {
gapItemIndex = itemIndexAfterTime(trackIndex, msTime);
}
if (gapItemIndex >= 0) {
while (gapItemIndex < itemCount) {
if (gapItemIndex < firstItemIndex || gapItemIndex > lastItemIndex) {
auto gapItem = m_items[trackIndex][gapItemIndex];
if (gapItem.start >= newEndTime) {
break;
} else if ((msTime >= gapItem.start && msTime < gapItem.end) ||
(newEndTime > gapItem.start && newEndTime <= gapItem.end) ||
(gapItem.start <= msTime && gapItem.end >= newEndTime)) {
return false;
}
}
gapItemIndex++;
}
}
return true;
}
void SubtitlesModel::doInsertTrack(const SubtitlesModel::SubtitleTrack &track, int trackIndex)
{
if (trackIndex < 0 || trackIndex > m_tracks.size()) {
LOG_ERROR() << "Invalid index" << trackIndex;
}
beginInsertRows(QModelIndex(), trackIndex, trackIndex);
m_tracks.insert(trackIndex, track);
m_items.insert(trackIndex, QList<Subtitles::SubtitleItem>());
// Feed filters should be after all normalizers and before any user filters
int filterIndex = m_producer->filter_count();
for (int i = 0; i < m_producer->filter_count(); i++) {
QScopedPointer<Mlt::Filter> filter(m_producer->filter(i));
if (!filter || !filter->is_valid()) {
continue;
}
if (!filter->get_int("_loader") && !filter->get_int(kShotcutHiddenProperty)) {
filterIndex = i;
break;
}
}
Mlt::Filter newFilter(MLT.profile(), "subtitle_feed");
newFilter.set("feed", track.name.toUtf8().constData());
newFilter.set("lang", track.lang.toUtf8().constData());
newFilter.set(kShotcutHiddenProperty, 1);
m_producer->attach(newFilter);
m_producer->move_filter(m_producer->filter_count() - 1, filterIndex);
endInsertRows();
emit tracksChanged(m_tracks.size());
emit modified();
}
void SubtitlesModel::doRemoveTrack(int trackIndex)
{
LOG_DEBUG() << trackIndex;
if (trackIndex < 0 || trackIndex >= m_tracks.size()) {
LOG_ERROR() << "Invalid index" << trackIndex;
}
beginRemoveRows(QModelIndex(), trackIndex, trackIndex);
m_tracks.remove(trackIndex);
m_items.remove(trackIndex);
int feedFilterIndex = 0;
for (int i = 0; i < m_producer->filter_count(); i++) {
QScopedPointer<Mlt::Filter> filter(m_producer->filter(i));
if (!filter || !filter->is_valid()) {
continue;
}
if (filter->get("mlt_service") == QStringLiteral("subtitle_feed")) {
if (feedFilterIndex == trackIndex) {
m_producer->detach(*filter);
break;
}
feedFilterIndex++;
}
}
endRemoveRows();
emit tracksChanged(m_tracks.size());
emit modified();
}
void SubtitlesModel::doEditTrack(const SubtitlesModel::SubtitleTrack &track, int trackIndex)
{
if (trackIndex < 0 || trackIndex > m_tracks.size()) {
LOG_ERROR() << "Invalid index" << trackIndex;
}
// Feed filters should be after all normalizers and before any user filters
int filterIndex = -1;
for (int i = 0; i < m_producer->filter_count(); i++) {
QScopedPointer<Mlt::Filter> filter(m_producer->filter(i));
if (filter && filter->is_valid()) {
QString mlt_service = filter->get("mlt_service");
if (mlt_service == QStringLiteral("subtitle_feed")) {
filterIndex++;
if (filterIndex == trackIndex) {
filter->set("feed", track.name.toUtf8().constData());
filter->set("lang", track.lang.toUtf8().constData());
break;
}
} else if (mlt_service == QStringLiteral("subtitle")) {
// Modify subtitle burn-in filter if present
if (filter->get("feed") == QString(m_tracks[trackIndex].name)) {
filter->set("feed", track.name.toUtf8().constData());
}
}
}
}
if (filterIndex == -1) {
LOG_ERROR() << "Subtitle filter not found" << trackIndex;
return;
}
m_tracks[trackIndex] = track;
emit dataChanged(index(trackIndex), index(trackIndex));
emit tracksChanged(m_tracks.size());
emit modified();
}
void SubtitlesModel::doRemoveSubtitleItems(int trackIndex,
const QList<Subtitles::SubtitleItem> &subtitles)
{
LOG_DEBUG() << trackIndex;
if (trackIndex < 0 || trackIndex >= m_tracks.size()) {
LOG_ERROR() << "Invalid index" << trackIndex;
}
// Find the start and end indexes to remove
int startIndex = -1;
int endIndex = -1;
for (int i = 0; i < m_items[trackIndex].size(); i++) {
if (subtitles[0].start == m_items[trackIndex][i].start) {
startIndex = i;
}
if (subtitles[subtitles.size() - 1].start == m_items[trackIndex][i].start) {
endIndex = i;
}
if (startIndex > -1 && endIndex > -1) {
break;
}
}
if (startIndex == -1 || endIndex == -1) {
LOG_ERROR() << "Failed to find items to remove" << startIndex << endIndex;
return;
}
beginRemoveRows(index(trackIndex), startIndex, endIndex);
m_items[trackIndex].remove(startIndex, endIndex - startIndex + 1);
requestFeedCommit(trackIndex);
endRemoveRows();
}
void SubtitlesModel::doInsertSubtitleItems(int trackIndex,
const QList<Subtitles::SubtitleItem> &subtitles)
{
LOG_DEBUG() << trackIndex;
if (trackIndex < 0 || trackIndex >= m_tracks.size()) {
LOG_ERROR() << "Invalid index" << trackIndex;
return;
}
int oldSize = m_items[trackIndex].size();
// Find the insert index
int insertIndex = oldSize;
for (int i = 0; i < oldSize; i++) {
if (m_items[trackIndex][i].start >= subtitles[0].start) {
insertIndex = i;
break;
}
}
QModelIndex parent = index(trackIndex);
beginInsertRows(parent, insertIndex, insertIndex + subtitles.size() - 1);
// Resize the list to fit the new items
m_items[trackIndex].resize(m_items[trackIndex].size() + subtitles.size());
// Move existing items to make room for the new items
if (insertIndex < oldSize) {
for (int i = oldSize - 1; i >= insertIndex; i--) {
m_items[trackIndex].move(i, i + subtitles.size());
}
}
// Put in the new items
for (int i = 0; i < subtitles.size(); i++) {
m_items[trackIndex][insertIndex + i] = subtitles[i];
}
requestFeedCommit(trackIndex);
endInsertRows();
}
void SubtitlesModel::doSetText(int trackIndex, int itemIndex, const QString &text)
{
if (trackIndex < 0 || trackIndex >= m_tracks.size()) {
LOG_ERROR() << "Invalid track" << trackIndex;
return;
}
if (itemIndex >= 0 && itemIndex < m_items[trackIndex].size()) {
m_items[trackIndex][itemIndex].text = text.toStdString();
requestFeedCommit(trackIndex);
QModelIndex parent = index(trackIndex);
emit dataChanged(index(itemIndex, COLUMN_TEXT, parent), index(itemIndex, COLUMN_TEXT, parent));
} else {
LOG_ERROR() << "Invalid index" << itemIndex;
}
}
void SubtitlesModel::doSetTime(int trackIndex, int itemIndex, int64_t startTime, int64_t endTime)
{
if (trackIndex < 0 || trackIndex >= m_tracks.size()) {
LOG_ERROR() << "Invalid track" << trackIndex;
return;
}
if (itemIndex >= 0 && itemIndex < m_items[trackIndex].size()) {
m_items[trackIndex][itemIndex].start = startTime;
m_items[trackIndex][itemIndex].end = endTime;
requestFeedCommit(trackIndex);
QModelIndex parent = index(trackIndex);
emit dataChanged(index(itemIndex, COLUMN_START, parent), index(itemIndex, COLUMN_DURATION, parent));
} else {
LOG_ERROR() << "Invalid index" << itemIndex;
}
}
int SubtitlesModel::rowCount(const QModelIndex &parent) const
{
int count = 0;
if (!parent.isValid()) {
count = m_tracks.size();
} else if (parent.internalId() != NO_PARENT_ID) {
count = 0;
} else if (parent.row() >= 0 && parent.row() < m_items.size()) {
count = m_items[parent.row()].size();
}
return count;
}
int SubtitlesModel::columnCount(const QModelIndex &parent) const
{
return COLUMN_COUNT;
}
QVariant SubtitlesModel::data(const QModelIndex &index, int role) const
{
QVariant result;
switch (role) {
case Qt::ToolTipRole:
case Qt::StatusTipRole:
case Qt::DecorationRole:
case Qt::FontRole:
case Qt::TextAlignmentRole:
case Qt::CheckStateRole:
case Qt::SizeHintRole:
case Qt::BackgroundRole:
case Qt::ForegroundRole:
return result;
}
if (!m_producer) {
LOG_DEBUG() << "No Producer: " << index.row() << index.column() << role;
return result;
}
if (!index.parent().isValid()) {
// Subtitle track
if (index.row() >= 0 && index.row() < m_tracks.size()) {
result = m_tracks[index.row()].name;
} else {
LOG_ERROR() << "Invalid root index: " << index.row() << index.column() << role;
}
return result;
}
// Subtitle item
if (!index.isValid() || index.column() < 0 || index.column() >= COLUMN_COUNT || index.row() < 0
|| index.row() >= itemCount(index.parent().row())) {
LOG_ERROR() << "Invalid Index: " << index.row() << index.column() << role;
return result;
}
Subtitles::SubtitleItem item = m_items[index.parent().row()][index.row()];
switch (role) {
case Qt::DisplayRole:
switch (index.column()) {
case COLUMN_TEXT:
result = QString::fromStdString(item.text).replace('\n', ' ');
break;
case COLUMN_START: {
mlt_position frames = item.start * MLT.profile().fps() / 1000;
result = QString(m_producer->frames_to_time(frames, Settings.timeFormat()));
break;
}
case COLUMN_END: {
mlt_position frames = item.end * MLT.profile().fps() / 1000;
result = QString(m_producer->frames_to_time(frames, Settings.timeFormat()));
break;
}
case COLUMN_DURATION: {
mlt_position frames = (item.end - item.start) * MLT.profile().fps() / 1000;
result = QString(m_producer->frames_to_time(frames, Settings.timeFormat()));
break;
}
default:
LOG_ERROR() << "Invalid Column" << index.column() << role;
break;
}
break;
case TextRole:
result = QString::fromStdString(item.text);
break;
case StartRole:
result = (qlonglong)item.start;
break;
case EndRole:
result = (qlonglong)item.end;
break;
case DurationRole:
result = (qlonglong)(item.end - item.start);
break;
case SimpleText:
result = QString::fromStdString(item.text).replace('\n', ' ');
break;
case StartFrameRole:
result = (int)std::round(item.start * MLT.profile().fps() / 1000);
break;
case EndFrameRole:
result = (int)std::round(item.end * MLT.profile().fps() / 1000);
break;
case SiblingCountRole:
result = m_items[index.parent().row()].size();
break;
default:
LOG_ERROR() << "Invalid Role" << index.row() << index.column() << roleNames()[role] << role;
break;
}
return result;
}
QVariant SubtitlesModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (role == Qt::DisplayRole) {
switch (section) {
case COLUMN_TEXT:
return tr("Text");
case COLUMN_START:
return tr("Start");
case COLUMN_END:
return tr("End");
case COLUMN_DURATION:
return tr("Duration");
default:
break;
}
}
return QVariant();
}
QModelIndex SubtitlesModel::index(int row, int column, const QModelIndex &parent) const
{
QModelIndex result;
if (parent.isValid()) {
// subtitle item
result = createIndex(row, column, parent.row());
} else if (row >= 0 && row < m_tracks.size() && column == 0) {
// subtitle track
result = createIndex(row, column, NO_PARENT_ID);
}
return result;
}
QModelIndex SubtitlesModel::parent(const QModelIndex &index) const
{
if (!index.isValid() || index.internalId() == NO_PARENT_ID)
return QModelIndex();
else
return createIndex(index.internalId(), 0, NO_PARENT_ID);
}
QHash<int, QByteArray> SubtitlesModel::roleNames() const
{
QHash<int, QByteArray> roles = QAbstractItemModel::roleNames();
roles[TextRole] = "text";
roles[StartRole] = "start";
roles[EndRole] = "end";
roles[DurationRole] = "duration";
roles[SimpleText] = "simpleText";
roles[StartFrameRole] = "startFrame";
roles[EndFrameRole] = "endFrame";
roles[SiblingCountRole] = "siblingCount";
return roles;
}
| 29,329
|
C++
|
.cpp
| 794
| 29.100756
| 114
| 0.598412
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,187
|
audiolevelstask.cpp
|
mltframework_shotcut/src/models/audiolevelstask.cpp
|
/*
* Copyright (c) 2013-2024 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "audiolevelstask.h"
#include "database.h"
#include "shotcut_mlt_properties.h"
#include "settings.h"
#include "mainwindow.h"
#include "util.h"
#include <QString>
#include <QVariantList>
#include <QImage>
#include <QCryptographicHash>
#include <QRgb>
#include <QThreadPool>
#include <QMutex>
#include <QTime>
#include <QElapsedTimer>
#include <Logger.h>
static QList<AudioLevelsTask *> tasksList;
static QMutex tasksListMutex;
static void deleteQVariantList(QVariantList *list)
{
delete list;
}
AudioLevelsTask::AudioLevelsTask(Mlt::Producer &producer, QObject *object, const QModelIndex &index)
: QRunnable()
, m_object(object)
, m_isCanceled(false)
, m_isForce(false)
{
m_producers << ProducerAndIndex(new Mlt::Producer(producer), index);
}
AudioLevelsTask::~AudioLevelsTask()
{
foreach (ProducerAndIndex p, m_producers)
delete p.first;
}
void AudioLevelsTask::start(Mlt::Producer &producer, QObject *object, const QModelIndex &index,
bool force)
{
if (Settings.timelineShowWaveforms() && producer.is_valid()) {
QString serviceName = producer.get("mlt_service");
if (serviceName == "pixbuf" || serviceName == "qimage" || serviceName == "webvfx" ||
serviceName == "color" || serviceName.startsWith("frei0r") || serviceName == "glaxnimate" ||
(serviceName.startsWith("avformat") && producer.get_int("audio_index") == -1)) {
return;
}
AudioLevelsTask *task = new AudioLevelsTask(producer, object, index);
tasksListMutex.lock();
// See if there is already a task for this MLT service and resource.
foreach (AudioLevelsTask *t, tasksList) {
if (*t == *task) {
// If so, then just add ourselves to be notified upon completion.
delete task;
task = 0;
t->m_producers << ProducerAndIndex(new Mlt::Producer(producer), index);
break;
}
}
if (task) {
// Otherwise, start a new audio levels generation thread.
task->m_isForce = force;
tasksList << task;
QThreadPool::globalInstance()->start(task);
}
tasksListMutex.unlock();
}
}
void AudioLevelsTask::closeAll()
{
// Tell all of the audio levels tasks to stop.
tasksListMutex.lock();
while (!tasksList.isEmpty()) {
AudioLevelsTask *task = tasksList.first();
task->m_isCanceled = true;
tasksList.removeFirst();
}
tasksListMutex.unlock();
}
bool AudioLevelsTask::operator==(AudioLevelsTask &b)
{
if (!m_producers.isEmpty() && !b.m_producers.isEmpty()) {
Mlt::Producer *a_producer = m_producers.first().first;
Mlt::Producer *b_producer = b.m_producers.first().first;
return a_producer && a_producer->is_valid() && b_producer && b_producer->is_valid()
&& !qstrcmp(a_producer->get("resource"), b_producer->get("resource"))
&& a_producer->get_int("audio_index") == b_producer->get_int("audio_index");
}
return false;
}
Mlt::Producer *AudioLevelsTask::tempProducer()
{
if (!m_tempProducer) {
Mlt::Producer *producer = m_producers.first().first;
QString service = producer->get("mlt_service");
if (service == "avformat-novalidate")
service = "avformat";
else if (service.startsWith("xml"))
service = "xml-nogl";
m_tempProducer.reset(new Mlt::Producer(m_profile, service.toUtf8().constData(),
producer->get("resource")));
if (m_tempProducer->is_valid()) {
Mlt::Filter channels(m_profile, "audiochannels");
Mlt::Filter converter(m_profile, "audioconvert");
Mlt::Filter levels(m_profile, "audiolevel");
m_tempProducer->attach(channels);
m_tempProducer->attach(converter);
m_tempProducer->attach(levels);
if (producer->get("audio_index")) {
m_tempProducer->pass_property(*producer, "audio_index");
}
m_tempProducer->set("video_index", -1);
}
}
return m_tempProducer.data();
}
QString AudioLevelsTask::cacheKey()
{
QString key = QStringLiteral("%1 audiolevels");
Mlt::Producer *producer = m_producers.first().first;
if (producer->get(kShotcutHashProperty)) {
key = key.arg(producer->get(kShotcutHashProperty));
} else {
key = key.arg(producer->get("resource"));
QCryptographicHash hash(QCryptographicHash::Sha1);
hash.addData(key.toUtf8());
key = hash.result().toHex();
}
if (producer->get("audio_index")) {
// Add the audio index only if different than default to avoid cache miss.
if (m_isForce || (producer->get(kDefaultAudioIndexProperty) &&
producer->get_int("audio_index") != producer->get_int(kDefaultAudioIndexProperty))) {
key += QStringLiteral(" %1").arg(producer->get("audio_index"));
}
}
return key;
}
void AudioLevelsTask::run()
{
// 2 channels interleaved of uchar values
QVariantList levels;
QImage image = DB.getThumbnail(cacheKey());
if (image.isNull() || m_isForce) {
const char *key[2] = { "meta.media.audio_level.0", "meta.media.audio_level.1"};
QElapsedTimer updateTime;
updateTime.start();
// TODO: use project channel count
int channels = 2;
auto message = QStringLiteral("%1 %2").arg(QObject::tr("generating audio waveforms for"),
Util::baseName(tempProducer()->get("resource"), true));
if (tempProducer()->get("audio_index")) {
LOG_DEBUG() << message << " with audio_index =" << tempProducer()->get("audio_index");
} else {
LOG_DEBUG() << message;
}
// for each frame
int n = tempProducer()->get_playtime();
for (int i = 0; i < n && !m_isCanceled; i++) {
Mlt::Frame *frame = tempProducer()->get_frame();
if (frame && frame->is_valid() && !frame->get_int("test_audio")) {
mlt_audio_format format = mlt_audio_s16;
int frequency = 48000;
int samples = mlt_audio_calculate_frame_samples(m_producers.first().first->get_fps(), frequency, i);
frame->get_audio(format, frequency, channels, samples);
// for each channel
for (int channel = 0; channel < channels; channel++)
// Convert real to uint for caching as image.
// Scale by 0.9 because values may exceed 1.0 to indicate clipping.
levels << 256 * qMin(frame->get_double(key[channel]) * 0.9, 1.0);
} else if (!levels.isEmpty()) {
for (int channel = 0; channel < channels; channel++)
levels << levels.last();
}
delete frame;
// Incrementally update the audio levels every 3 seconds.
if (updateTime.elapsed() > 3 * 1000 && !m_isCanceled) {
updateTime.restart();
foreach (ProducerAndIndex p, m_producers) {
QVariantList *levelsCopy = new QVariantList(levels);
p.first->lock();
p.first->set(kAudioLevelsProperty, levelsCopy, 0, (mlt_destructor) deleteQVariantList);
p.first->unlock();
if (-1 != m_object->metaObject()->indexOfMethod("audioLevelsReady(QPersistentModelIndex)"))
QMetaObject::invokeMethod(m_object, "audioLevelsReady", Q_ARG(const QPersistentModelIndex &,
p.second));
}
}
}
if (!m_isCanceled) {
// Put into an image for caching.
int count = levels.size();
QImage image((count + 3) / 4 / channels, channels, QImage::Format_ARGB32);
n = image.width() * image.height();
for (int i = 0; i < n; i ++) {
QRgb p;
if ((4 * i + 3) < count) {
p = qRgba(levels.at(4 * i).toInt(), levels.at(4 * i + 1).toInt(), levels.at(4 * i + 2).toInt(),
levels.at(4 * i + 3).toInt());
} else {
int last = levels.last().toInt();
int r = (4 * i + 0) < count ? levels.at(4 * i + 0).toInt() : last;
int g = (4 * i + 1) < count ? levels.at(4 * i + 1).toInt() : last;
int b = (4 * i + 2) < count ? levels.at(4 * i + 2).toInt() : last;
int a = last;
p = qRgba(r, g, b, a);
}
image.setPixel(i / 2, i % channels, p);
}
if (!image.isNull()) {
DB.putThumbnail(cacheKey(), image);
} else {
// If the produducer does not produce audio, make a special 1x1 RGBA(0,0,0,0) image,
// which is used to prevent QImage::isNull() from being true and continually trying
// to regenerate audio levels for this file.
QImage image(1, 1, QImage::Format_ARGB32);
DB.putThumbnail(cacheKey(), image);
}
}
message = QStringLiteral("%1 %2").arg(QObject::tr("Done"), message);
QMetaObject::invokeMethod(&MAIN, "showStatusMessage", Qt::QueuedConnection,
Q_ARG(QString, message));
} else if (!m_isCanceled && !image.isNull()) {
// convert cached image
int channels = 2;
int n = image.width() * image.height();
for (int i = 0; n > 1 && i < n; i++) {
QRgb p = image.pixel(i / 2, i % channels);
levels << qRed(p);
levels << qGreen(p);
levels << qBlue(p);
levels << qAlpha(p);
}
}
// Remove ourself from the global list of audio tasks.
tasksListMutex.lock();
for (int i = 0; i < tasksList.size(); ++i) {
if (*tasksList[i] == *this) {
tasksList.removeAt(i);
break;
}
}
tasksListMutex.unlock();
if (levels.size() > 0 && !m_isCanceled) {
foreach (ProducerAndIndex p, m_producers) {
QVariantList *levelsCopy = new QVariantList(levels);
p.first->lock();
p.first->set(kAudioLevelsProperty, levelsCopy, 0, (mlt_destructor) deleteQVariantList);
p.first->unlock();
if (-1 != m_object->metaObject()->indexOfMethod("audioLevelsReady(QPersistentModelIndex)"))
QMetaObject::invokeMethod(m_object, "audioLevelsReady", Q_ARG(const QPersistentModelIndex &,
p.second));
}
}
}
| 11,698
|
C++
|
.cpp
| 268
| 33.309701
| 116
| 0.568174
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,188
|
motiontrackermodel.cpp
|
mltframework_shotcut/src/models/motiontrackermodel.cpp
|
/*
* Copyright (c) 2023 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "motiontrackermodel.h"
#include "shotcut_mlt_properties.h"
#include "qmltypes/qmlfilter.h"
#include "mltcontroller.h"
#include <QUuid>
#include <Mlt.h>
#include <Logger.h>
// This is hard-coded for now (minimum viable product).
static const int KEYFRAME_INTERVAL_FRAMES = 5;
class FindTrackersParser : public Mlt::Parser
{
private:
MotionTrackerModel &m_model;
public:
FindTrackersParser(MotionTrackerModel &model)
: Mlt::Parser()
, m_model{model}
{}
int on_start_filter(Mlt::Filter *filter)
{
if (QString::fromUtf8(filter->get("mlt_service")) == "opencv.tracker") {
auto results = QString::fromLatin1(filter->get("results"));
if (!results.isEmpty()) {
auto name = QString::fromUtf8(filter->get(kTrackNameProperty));
if (name.isEmpty()) {
name = m_model.nextName();
filter->set(kTrackNameProperty, name.toUtf8().constData());
}
auto key = m_model.add(name, results);
if (!key.isEmpty()) {
filter->set(kUuidProperty, key.toUtf8().constData());
}
}
}
return 0;
}
int on_start_producer(Mlt::Producer *)
{
return 0;
}
int on_end_producer(Mlt::Producer *)
{
return 0;
}
int on_start_playlist(Mlt::Playlist *)
{
return 0;
}
int on_end_playlist(Mlt::Playlist *)
{
return 0;
}
int on_start_tractor(Mlt::Tractor *)
{
return 0;
}
int on_end_tractor(Mlt::Tractor *)
{
return 0;
}
int on_start_multitrack(Mlt::Multitrack *)
{
return 0;
}
int on_end_multitrack(Mlt::Multitrack *)
{
return 0;
}
int on_start_track()
{
return 0;
}
int on_end_track()
{
return 0;
}
int on_end_filter(Mlt::Filter *)
{
return 0;
}
int on_start_transition(Mlt::Transition *)
{
return 0;
}
int on_end_transition(Mlt::Transition *)
{
return 0;
}
int on_start_chain(Mlt::Chain *)
{
return 0;
}
int on_end_chain(Mlt::Chain *)
{
return 0;
}
int on_start_link(Mlt::Link *)
{
return 0;
}
int on_end_link(Mlt::Link *)
{
return 0;
}
};
MotionTrackerModel::MotionTrackerModel(QObject *parent)
: QAbstractListModel(parent)
{
m_data[""] = {""}; // To show nothing in a combo
}
void MotionTrackerModel::load(Mlt::Producer *producer, bool reset)
{
if (!producer) producer = MLT.producer();
if (reset) {
beginResetModel();
m_data.clear();
beginInsertRows(QModelIndex(), 0, 0);
m_data[""] = {""};
endInsertRows();
}
if (producer && producer->is_valid()) {
FindTrackersParser(*this).start(*producer);
Mlt::Properties retainList((mlt_properties) producer->get_data("xml_retain"));
if (retainList.is_valid()) {
Mlt::Playlist playlist((mlt_playlist) retainList.get_data(kPlaylistTrackId));
if (playlist.is_valid() && playlist.type() == mlt_service_playlist_type) {
FindTrackersParser(*this).start(playlist);
}
}
}
if (reset) endResetModel();
}
QString MotionTrackerModel::add(const QString &name, const QString &data)
{
auto key = QUuid::createUuid().toString();
if (!m_data.contains(key)) {
auto row = rowCount();
beginInsertRows(QModelIndex(), row, row);
m_data[key] = {name, data, KEYFRAME_INTERVAL_FRAMES};
LOG_DEBUG() << key << m_data[key].name;
endInsertRows();
return key;
}
return QString();
}
void MotionTrackerModel::updateData(const QString &key, const QString &data)
{
auto keys = m_data.keys();
auto row = keys.indexOf(key);
if (row >= 0) {
m_data[key].trackingData = data;
auto i = createIndex(row, 0);
emit dataChanged(i, i, {TrackingDataRole});
}
}
void MotionTrackerModel::remove(const QString &key)
{
if (m_data.contains(key)) {
auto i = m_data.constBegin();
for (int row = 0; i != m_data.constEnd(); ++i, ++row) {
if (i.key() == key) {
beginRemoveRows(QModelIndex(), row, row);
m_data.remove(key);
endInsertRows();
break;
}
}
}
}
void MotionTrackerModel::removeFromService(Mlt::Service *service)
{
// look for an attached filter with mlt_service = opencv.tracker
if (service && service->is_valid()) {
auto producer = Mlt::Producer(*service).parent();
for (int i = 0; i < producer.filter_count(); i++) {
auto filter = producer.filter(i);
if (filter && filter->is_valid()) {
if (QString::fromUtf8(filter->get("mlt_service")) == "opencv.tracker") {
auto key = keyForFilter(filter);
if (!key.isEmpty())
remove(key);
}
}
}
}
}
void MotionTrackerModel::setName(QmlFilter *filter, const QString &name)
{
if (filter && filter->service().is_valid()) {
auto key = keyForFilter(&filter->service());
if (!key.isEmpty() && m_data.contains(key)) {
m_data[key].name = name;
}
}
}
QString MotionTrackerModel::nextName() const
{
return tr("Tracker %1").arg(rowCount());
}
QString MotionTrackerModel::keyForRow(int row) const
{
QString key;
auto keys = m_data.keys();
if (row >= 0 && row < keys.size()) {
key = keys.at(row);
}
return key;
}
QString MotionTrackerModel::keyForFilter(Mlt::Service *service)
{
QString key;
if (service && service->is_valid())
key = service->get(kUuidProperty);
return key;
}
void MotionTrackerModel::reset(QmlFilter *filter, const QString &property, int row)
{
auto key = keyForRow(row);
if (!key.isEmpty() && filter && filter->service().is_valid() && !property.isEmpty()) {
auto data = trackingData(key);
if (!data.isEmpty()) {
// Use a shotcut property to backup current values
if (filter->get(kBackupProperty).isEmpty()) {
filter->set(kBackupProperty, filter->get(property));
} else {
filter->set(property, filter->get(kBackupProperty));
}
}
}
}
QList<MotionTrackerModel::TrackingItem> MotionTrackerModel::trackingData(const QString &key) const
{
QList<TrackingItem> result;
auto s = m_data.value(key, {}).trackingData;
auto l = s.split(';');
bool ok {false};
Mlt::Properties props;
for (const auto &i : l) {
auto pair = i.split("~=");
if (pair.size() == 2) {
auto frame = pair.at(0).toInt(&ok);
props.set("", pair.at(1).toLatin1().constData());
auto rect = props.get_rect("");
if (ok) {
result << TrackingItem{frame, QRectF(rect.x, rect.y, rect.w, rect.h)};
}
}
}
return result;
}
QList<QRectF> MotionTrackerModel::trackingData(int row) const
{
auto key = keyForRow(row);
QList<QRectF> result;
if (!key.isEmpty() && m_data.contains(key)) {
for (const auto &a : trackingData(key)) {
result << a.rect;
}
}
return result;
}
int MotionTrackerModel::keyframeIntervalFrames(int row) const
{
auto key = keyForRow(row);
if (!key.isEmpty() && m_data.contains(key))
return m_data.value(key).intervalFrames;
return KEYFRAME_INTERVAL_FRAMES;
}
int MotionTrackerModel::rowCount(const QModelIndex &parent) const
{
// For list models only the root node (an invalid parent) should return the list's size. For all
// other (valid) parents, rowCount() should return 0 so that it does not become a tree model.
if (parent.isValid())
return 0;
return m_data.size();
}
QVariant MotionTrackerModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();
auto key = keyForRow(index.row());
if (!key.isEmpty()) {
switch (role) {
case Qt::DisplayRole:
return m_data.value(key).name;
case TrackingDataRole:
return m_data.value(key).trackingData;
default:
break;
}
}
return QVariant();
}
bool MotionTrackerModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
if (data(index, role) != value) {
auto key = index.data(Qt::UserRole).toString();
if (m_data.contains(key)) {
switch (role) {
case Qt::DisplayRole:
m_data[key].name = value.toString();
emit dataChanged(index, index, {role});
break;
case TrackingDataRole:
m_data[key].trackingData = value.toString();
emit dataChanged(index, index, {role});
break;
default:
break;
}
return true;
}
}
return false;
}
Qt::ItemFlags MotionTrackerModel::flags(const QModelIndex &index) const
{
if (!index.isValid())
return Qt::NoItemFlags;
return QAbstractItemModel::flags(index) | Qt::ItemIsEditable;
}
void MotionTrackerModel::undo(QmlFilter *filter, const QString &propertyName)
{
if (filter && !propertyName.isEmpty()) {
filter->set(propertyName, filter->get(kBackupProperty));
filter->resetProperty(kBackupProperty);
}
}
| 10,348
|
C++
|
.cpp
| 344
| 23.299419
| 100
| 0.593543
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,189
|
keyframesmodel.cpp
|
mltframework_shotcut/src/models/keyframesmodel.cpp
|
/*
* Copyright (c) 2018-2024 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "keyframesmodel.h"
#include "qmltypes/qmlapplication.h"
#include "qmltypes/qmlmetadata.h"
#include "qmltypes/qmlfilter.h"
#include "mltcontroller.h"
#include <Logger.h>
#include <QTimer>
#include <QRegularExpression>
static const quintptr NO_PARENT_ID = quintptr(-1);
KeyframesModel::KeyframesModel(QObject *parent)
: QAbstractItemModel(parent)
{
}
KeyframesModel::~KeyframesModel()
{
}
int KeyframesModel::rowCount(const QModelIndex &parent) const
{
if (parent.isValid()) {
// keyframes
if (parent.row() < m_keyframeCounts.count())
return m_keyframeCounts[parent.row()];
return 0;
}
// parameters
return m_propertyNames.count();
}
int KeyframesModel::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent)
return 1;
}
QVariant KeyframesModel::data(const QModelIndex &index, int role) const
{
if (!m_metadata || !index.isValid())
return QVariant();
if (index.parent().isValid()) {
// LOG_DEBUG() << "keyframe" << index.internalId() << index.row() << role;
// keyframes
if (m_filter && index.internalId() < quintptr(m_propertyNames.count())) {
QString name = m_propertyNames[index.internalId()];
Mlt::Animation animation = m_filter->getAnimation(name);
if (animation.is_valid()) {
int position = const_cast<Mlt::Animation &>(animation).key_get_frame(index.row());
if (position >= 0) {
switch (role) {
case Qt::DisplayRole:
case NameRole: {
QString type = tr("Linear");
switch (const_cast<Mlt::Animation &>(animation).key_get_type(index.row())) {
case mlt_keyframe_discrete:
type = tr("Hold");
break;
#if LIBMLT_VERSION_INT >= ((7<<16)+(21<<8))
case mlt_keyframe_smooth_loose:
case mlt_keyframe_smooth_natural:
case mlt_keyframe_smooth_tight:
type = tr("Smooth");
break;
case mlt_keyframe_sinusoidal_in:
type = tr("Ease In Sinusoidal");
break;
case mlt_keyframe_sinusoidal_out:
type = tr("Ease Out Sinusoidal");
break;
case mlt_keyframe_sinusoidal_in_out:
type = tr("Ease In/Out Sinusoidal");
break;
case mlt_keyframe_quadratic_in:
type = tr("Ease In Quadratic");
break;
case mlt_keyframe_quadratic_out:
type = tr("Ease Out Quadratic");
break;
case mlt_keyframe_quadratic_in_out:
type = tr("Ease In/Out Quadratic");
break;
case mlt_keyframe_cubic_in:
type = tr("Ease In Cubic");
break;
case mlt_keyframe_cubic_out:
type = tr("Ease Out Cubic");
break;
case mlt_keyframe_cubic_in_out:
type = tr("Ease In/Out Cubic");
break;
case mlt_keyframe_quartic_in:
type = tr("Ease In Quartic");
break;
case mlt_keyframe_quartic_out:
type = tr("Ease Out Quartic");
break;
case mlt_keyframe_quartic_in_out:
type = tr("Ease In/Out Quartic");
break;
case mlt_keyframe_quintic_in:
type = tr("Ease In Quintic");
break;
case mlt_keyframe_quintic_out:
type = tr("Ease Out Quintic");
break;
case mlt_keyframe_quintic_in_out:
type = tr("Ease In/Out Quintic");
break;
case mlt_keyframe_exponential_in:
type = tr("Ease In Exponential");
break;
case mlt_keyframe_exponential_out:
type = tr("Ease Out Exponential");
break;
case mlt_keyframe_exponential_in_out:
type = tr("Ease In/Out Exponential");
break;
case mlt_keyframe_circular_in:
type = tr("Ease In Circular");
break;
case mlt_keyframe_circular_out:
type = tr("Ease Out Circular");
break;
case mlt_keyframe_circular_in_out:
type = tr("Ease In/Out Circular");
break;
case mlt_keyframe_back_in:
type = tr("Ease In Back");
break;
case mlt_keyframe_back_out:
type = tr("Ease Out Back");
break;
case mlt_keyframe_back_in_out:
type = tr("Ease In/Out Back");
break;
case mlt_keyframe_elastic_in:
type = tr("Ease In Elastic");
break;
case mlt_keyframe_elastic_out:
type = tr("Ease Out Elastic");
break;
case mlt_keyframe_elastic_in_out:
type = tr("Ease In/Out Elastic");
break;
case mlt_keyframe_bounce_in:
type = tr("Ease In Bounce");
break;
case mlt_keyframe_bounce_out:
type = tr("Ease Out Bounce");
break;
case mlt_keyframe_bounce_in_out:
type = tr("Ease In/Out Bounce");
break;
#else
case mlt_keyframe_smooth:
type = tr("Smooth");
break;
#endif
default:
break;
}
double value = m_filter->getDouble(name, position);
QString units = m_metadata->keyframes()->parameter(m_metadataIndex[index.internalId()])->units();
return QStringLiteral("%1 - %2\n%3%4").arg(QmlApplication::singleton().timeFromFrames(
position)).arg(
type).arg(value).arg(units);
}
case FrameNumberRole:
return position;
case KeyframeTypeRole:
if (index.row() >= animation.key_count() - 1) {
return DiscreteInterpolation;
}
return const_cast<Mlt::Animation &>(animation).key_get_type(index.row());
case PrevKeyframeTypeRole:
if (index.row() <= 0) {
return DiscreteInterpolation;
}
return const_cast<Mlt::Animation &>(animation).key_get_type(index.row() - 1);
case NumericValueRole:
return m_filter->getDouble(name, position);
case MinimumFrameRole: {
int result = 0;
if (animation.previous_key(position - 1, result)) {
// first Keyframe
result = 0;
} else {
result += 1;
}
// LOG_DEBUG() << "keyframeIndex" << index.row() << "minimumFrame" << result;
return result;
}
case MaximumFrameRole: {
int result = 0;
if (animation.next_key(position + 1, result)) {
// Last Keyframe
result = m_filter->producer().get_out();
} else {
result -= 1;
}
// LOG_DEBUG() << "keyframeIndex" << index.row() << "maximumFrame" << result;
return result;
}
default:
break;
}
}
}
}
} else if (index.row() < m_metadata->keyframes()->parameterCount()) {
// LOG_DEBUG() << "parameter" << index.row() << role;
// parameters
switch (role) {
case Qt::DisplayRole:
case NameRole:
return m_metadata->keyframes()->parameter(m_metadataIndex[index.row()])->name();
case PropertyNameRole:
return m_metadata->keyframes()->parameter(m_metadataIndex[index.row()])->property();
case IsCurveRole:
return m_metadata->keyframes()->parameter(m_metadataIndex[index.row()])->isCurve();
case MinimumValueRole: {
QmlKeyframesParameter *param = m_metadata->keyframes()->parameter(m_metadataIndex[index.row()]);
if (param->rangeType() == QmlKeyframesParameter::MinMax) {
return m_metadata->keyframes()->parameter(m_metadataIndex[index.row()])->minimum();
} else if (param->rangeType() == QmlKeyframesParameter::ClipLength) {
return 0.0;
}
return 0.0;
}
case MaximumValueRole: {
QmlKeyframesParameter *param = m_metadata->keyframes()->parameter(m_metadataIndex[index.row()]);
if (param->rangeType() == QmlKeyframesParameter::MinMax) {
return m_metadata->keyframes()->parameter(m_metadataIndex[index.row()])->maximum();
} else if (param->rangeType() == QmlKeyframesParameter::ClipLength) {
int length = m_filter->producer().get_length() - m_filter->in();
return (double)length / MLT.profile().fps();
}
return 0.0;
}
case LowestValueRole: {
QmlKeyframesParameter *param = m_metadata->keyframes()->parameter(m_metadataIndex[index.row()]);
Mlt::Animation animation = m_filter->getAnimation(param->property());
double min = std::numeric_limits<double>::max();
if (animation.is_valid()) {
for (int i = 0; i < animation.key_count(); i++) {
int frame = animation.key_get_frame(i);
if (frame >= 0) {
double value = m_filter->getDouble(param->property(), frame);
if (value < min) min = value;
}
}
}
if (min == std::numeric_limits<double>::max()) min = 0;
return min;
}
case HighestValueRole: {
QmlKeyframesParameter *param = m_metadata->keyframes()->parameter(m_metadataIndex[index.row()]);
Mlt::Animation animation = m_filter->getAnimation(param->property());
double max = std::numeric_limits<double>::lowest();
if (animation.is_valid()) {
for (int i = 0; i < animation.key_count(); i++) {
int frame = animation.key_get_frame(i);
if (frame >= 0) {
double value = m_filter->getDouble(param->property(), frame);
if (value > max) max = value;
}
}
}
if (max == std::numeric_limits<double>::lowest()) max = 0;
return max;
}
default:
break;
}
}
return QVariant();
}
QModelIndex KeyframesModel::index(int row, int column, const QModelIndex &parent) const
{
if (column > 0)
return QModelIndex();
QModelIndex result;
if (parent.isValid()) {
// keyframes
result = createIndex(row, column, parent.row());
} else if (row < m_propertyNames.count()) {
result = createIndex(row, column, NO_PARENT_ID);
}
return result;
}
QModelIndex KeyframesModel::parent(const QModelIndex &index) const
{
if (!index.isValid() || index.internalId() == NO_PARENT_ID)
return QModelIndex();
else
return createIndex(index.internalId(), 0, NO_PARENT_ID);
}
QHash<int, QByteArray> KeyframesModel::roleNames() const
{
QHash<int, QByteArray> roles;
roles[NameRole] = "name";
roles[PropertyNameRole] = "property";
roles[IsCurveRole] = "isCurve";
roles[MinimumValueRole] = "minimum";
roles[MaximumValueRole] = "maximum";
roles[LowestValueRole] = "lowest";
roles[HighestValueRole] = "highest";
roles[FrameNumberRole] = "frame";
roles[KeyframeTypeRole] = "interpolation";
roles[PrevKeyframeTypeRole] = "prevInterpolation";
roles[NumericValueRole] = "value";
roles[MinimumFrameRole] = "minimumFrame";
roles[MaximumFrameRole] = "maximumFrame";
return roles;
}
void KeyframesModel::load(QmlFilter *filter, QmlMetadata *meta)
{
beginResetModel();
m_propertyNames.clear();
m_keyframeCounts.clear();
m_metadataIndex.clear();
m_filter = filter;
m_metadata = meta;
if (m_filter && m_metadata && m_filter->animateIn() <= 0 && m_filter->animateOut() <= 0)
for (int i = 0; i < m_metadata->keyframes()->parameterCount(); i++) {
if (m_filter->keyframeCount(m_metadata->keyframes()->parameter(i)->property()) > 0) {
m_propertyNames << m_metadata->keyframes()->parameter(i)->property();
m_keyframeCounts << keyframeCount(m_propertyNames.count() - 1);
m_metadataIndex << i;
// LOG_DEBUG() << m_propertyNames.last() << m_filter->get(m_propertyNames.last()) << keyframeCount(i);
}
}
endResetModel();
emit loaded();
}
bool KeyframesModel::remove(int parameterIndex, int keyframeIndex)
{
bool error = true;
if (m_filter && parameterIndex < m_propertyNames.count()) {
QString name = m_propertyNames[parameterIndex];
Mlt::Animation animation = m_filter->getAnimation(name);
// Do not allow the user to delete the last keyframe.
// Keyframes should be disabled in the filter panel instead
if (animation.is_valid() && animation.key_count() > 1) {
int frame_num = animation.key_get_frame(keyframeIndex);
error = animation.remove(frame_num);
if (!error) {
m_filter->startUndoRemoveKeyframeCommand();
animation.interpolate();
m_filter->updateUndoCommand(name);
beginRemoveRows(index(parameterIndex), keyframeIndex, keyframeIndex);
m_keyframeCounts[parameterIndex] -= 1;
endRemoveRows();
for (auto &key : gangedProperties(parameterIndex)) {
Mlt::Animation animation = m_filter->getAnimation(key);
if (animation.is_valid() && !animation.remove(frame_num)) {
animation.interpolate();
m_filter->updateUndoCommand(key);
}
}
mlt_event_data eventData = mlt_event_data_from_string(name.toUtf8().constData());
mlt_events_fire(m_filter->service().get_properties(), "property-changed", eventData);
QModelIndex modelIndex;
if (keyframeIndex > 0) {
modelIndex = index(keyframeIndex - 1, 0, index(parameterIndex));
emit dataChanged(modelIndex, modelIndex, QVector<int>() << MaximumFrameRole);
}
if (keyframeIndex < keyframeCount(parameterIndex)) {
modelIndex = index(keyframeIndex, 0, index(parameterIndex));
emit dataChanged(modelIndex, modelIndex, QVector<int>() << MinimumFrameRole);
}
emit dataChanged(index(parameterIndex), index(parameterIndex),
QVector<int>() << LowestValueRole << HighestValueRole);
emit m_filter->changed(name.toUtf8().constData());
m_filter->endUndoCommand();
}
}
}
return error;
}
int KeyframesModel::previousKeyframePosition(int parameterIndex, int currentPosition)
{
int result = -1;
if (m_filter && parameterIndex < m_propertyNames.count()) {
QString name = m_propertyNames[parameterIndex];
Mlt::Animation animation = m_filter->getAnimation(name);
if (animation.is_valid()) {
currentPosition -= m_filter->in();
bool error = animation.previous_key(animation.is_key(currentPosition) ? currentPosition - 1 :
currentPosition, result);
if (!error)
result += m_filter->in();
}
}
return result;
}
int KeyframesModel::nextKeyframePosition(int parameterIndex, int currentPosition)
{
int result = -1;
if (m_filter && parameterIndex < m_propertyNames.count()) {
QString name = m_propertyNames[parameterIndex];
Mlt::Animation animation = m_filter->getAnimation(name);
if (animation.is_valid()) {
currentPosition -= m_filter->in();
bool error = animation.next_key(animation.is_key(currentPosition) ? currentPosition + 1 :
currentPosition, result);
if (!error)
result += m_filter->in();
}
}
return result;
}
int KeyframesModel::keyframeIndex(int parameterIndex, int currentPosition)
{
int result = -1;
if (m_filter && parameterIndex < m_propertyNames.count()) {
QString name = m_propertyNames[parameterIndex];
Mlt::Animation animation = m_filter->getAnimation(name);
if (animation.is_valid()) {
for (int i = 0; i < animation.key_count() && result == -1; i++) {
int frame = animation.key_get_frame(i);
if (frame == currentPosition)
result = i;
else if (frame > currentPosition)
break;
}
}
}
return result;
}
int KeyframesModel::parameterIndex(const QString &propertyName) const
{
return m_propertyNames.indexOf(propertyName);
}
bool KeyframesModel::setInterpolation(int parameterIndex, int keyframeIndex, InterpolationType type)
{
bool error = true;
if (m_filter && parameterIndex < m_propertyNames.count()) {
QString name = m_propertyNames[parameterIndex];
Mlt::Animation animation = m_filter->getAnimation(name);
if (animation.is_valid()) {
if (!animation.key_set_type(keyframeIndex, mlt_keyframe_type(type))) {
// LOG_DEBUG() << "keyframe index" << keyframeIndex << "keyframe type" << type;
m_filter->startUndoModifyKeyframeCommand(parameterIndex, keyframeIndex);
m_filter->updateUndoCommand(name);
for (auto &key : gangedProperties(parameterIndex)) {
Mlt::Animation animation = m_filter->getAnimation(key);
if (animation.is_valid()) {
animation.key_set_type(keyframeIndex, mlt_keyframe_type(type));
m_filter->updateUndoCommand(key);
}
}
mlt_event_data eventData = mlt_event_data_from_string(name.toUtf8().constData());
mlt_events_fire(m_filter->service().get_properties(), "property-changed", eventData);
QModelIndex modelIndex = index(keyframeIndex, 0, index(parameterIndex));
emit dataChanged(modelIndex, modelIndex, QVector<int>() << KeyframeTypeRole << NameRole);
QModelIndex nextModelIndex = index(keyframeIndex + 1, 0, index(parameterIndex));
emit dataChanged(nextModelIndex, nextModelIndex, QVector<int>() << PrevKeyframeTypeRole);
error = false;
emit m_filter->changed(name.toUtf8().constData());
emit m_filter->propertyChanged(name.toUtf8().constData());
m_filter->endUndoCommand();
}
}
}
if (error)
LOG_ERROR() << "failed to set keyframe" << "at parameter index" << parameterIndex << "keyframeIndex"
<< keyframeIndex << "to type" << type;
return error;
}
void KeyframesModel::setKeyframePosition(int parameterIndex, int keyframeIndex, int position)
{
if (!m_filter) {
LOG_ERROR() << "Invalid Filter" << parameterIndex;
return;
}
if (parameterIndex >= m_propertyNames.count()) {
LOG_ERROR() << "Invalid parameter index" << parameterIndex;
return;
}
QString name = m_propertyNames[parameterIndex];
Mlt::Animation animation = m_filter->getAnimation(name);
if (!animation.is_valid()) {
LOG_ERROR() << "Invalid animation" << parameterIndex;
return;
}
if (keyframeIndex >= animation.key_count()) {
LOG_ERROR() << "Invalid key index" << parameterIndex << keyframeIndex;
return;
}
if (position < 0) {
LOG_ERROR() << "Invalid key position" << parameterIndex << keyframeIndex << position;
return;
}
int prevPosition = animation.key_get_frame(keyframeIndex);
if (position == prevPosition) {
LOG_ERROR() << "Position did not change" << parameterIndex << keyframeIndex << position;
return;
}
if (animation.key_set_frame(keyframeIndex, position)) {
LOG_ERROR() << "Failed to set position" << parameterIndex << keyframeIndex << position;
return;
}
m_filter->startUndoModifyKeyframeCommand(parameterIndex, keyframeIndex);
m_filter->updateUndoCommand(name);
for (auto &key : gangedProperties(parameterIndex)) {
Mlt::Animation animation = m_filter->getAnimation(key);
if (animation.is_valid()) {
animation.key_set_frame(keyframeIndex, position);
m_filter->updateUndoCommand(key);
}
}
mlt_event_data eventData = mlt_event_data_from_string(name.toUtf8().constData());
mlt_events_fire(m_filter->service().get_properties(), "property-changed", eventData);
QModelIndex modelIndex = index(keyframeIndex, 0, index(parameterIndex));
emit dataChanged(modelIndex, modelIndex, QVector<int>() << FrameNumberRole << NameRole);
updateNeighborsMinMax(parameterIndex, keyframeIndex);
emit m_filter->changed(name.toUtf8().constData());
emit m_filter->propertyChanged(name.toUtf8().constData());
m_filter->endUndoCommand();
}
void KeyframesModel::addKeyframe(int parameterIndex, double value, int position,
KeyframesModel::InterpolationType type)
{
if (m_filter && parameterIndex < m_propertyNames.count()) {
QString name = m_propertyNames[parameterIndex];
m_filter->startUndoAddKeyframeCommand();
m_filter->set(name, value, position, mlt_keyframe_type(type));
m_filter->updateUndoCommand(name);
for (auto &key : gangedProperties(parameterIndex)) {
m_filter->set(key, value, position, mlt_keyframe_type(type));
m_filter->updateUndoCommand(key);
}
m_filter->endUndoCommand();
}
}
void KeyframesModel::addKeyframe(int parameterIndex, int position)
{
if (m_filter && parameterIndex < m_propertyNames.count()) {
QString name = m_propertyNames[parameterIndex];
auto parameter = m_metadata->keyframes()->parameter(m_metadataIndex[parameterIndex]);
if (parameter->isRectangle()) {
m_filter->startUndoAddKeyframeCommand();
auto value = m_filter->getRect(name, position);
Mlt::Animation anim = m_filter->getAnimation(name);
if (anim.is_valid() && !anim.is_key(position)) {
mlt_keyframe_type keyframeType = m_filter->getKeyframeType(anim, position, mlt_keyframe_type(-1));
m_filter->blockSignals(true);
m_filter->set(name, value, position, keyframeType);
m_filter->blockSignals(false);
emit keyframeAdded(name, position);
}
m_filter->endUndoCommand();
} else if (parameter->isColor()) {
m_filter->startUndoAddKeyframeCommand();
// Color values
auto value = m_filter->getColor(name, position);
Mlt::Animation anim = m_filter->getAnimation(name);
if (anim.is_valid() && !anim.is_key(position)) {
mlt_keyframe_type keyframeType = m_filter->getKeyframeType(anim, position, mlt_keyframe_type(-1));
m_filter->blockSignals(true);
m_filter->set(name, value, position, keyframeType);
for (auto &key : parameter->gangedProperties()) {
value = m_filter->get(key, position);
m_filter->set(key, value, position, keyframeType);
}
m_filter->blockSignals(false);
}
emit keyframeAdded(name, position);
m_filter->endUndoCommand();
} else {
m_filter->startUndoAddKeyframeCommand();
// Get the value from the existing position.
double value = m_filter->getDouble(name, position);
Mlt::Animation anim = m_filter->getAnimation(name);
if (anim.is_valid() && !anim.is_key(position)) {
mlt_keyframe_type keyframeType = m_filter->getKeyframeType(anim, position, mlt_keyframe_type(-1));
// Simply adding a keyframe does not change the current value of
// the filter parameter. So, no need to trigger a bunch of signals
// and refresh the consumer. Besides, refreshing the consumer is
// some how causing the player to seek ahead by one frame inadvertently
// such that changing the parameter value causes the addition of a
// keyframe just after this one. MLT.refreshConsumer() with
// frame-dropping enabled may have dropped video of the most recent
// frame from the producer, but Shotcut does not know about it
// because it did not receive a "consumer-frame-show" event for it.
m_filter->blockSignals(true);
m_filter->set(name, value, position, keyframeType);
for (auto &key : parameter->gangedProperties()) {
value = m_filter->getDouble(key, position);
m_filter->set(key, value, position, keyframeType);
}
m_filter->blockSignals(false);
emit keyframeAdded(name, position);
m_filter->endUndoCommand();
}
}
onFilterChanged(name);
}
}
void KeyframesModel::setKeyframeValue(int parameterIndex, int keyframeIndex, double value)
{
if (!m_filter) {
LOG_ERROR() << "Invalid Filter" << parameterIndex;
return;
}
if (parameterIndex >= m_propertyNames.count()) {
LOG_ERROR() << "Invalid parameter index" << parameterIndex;
return;
}
QString name = m_propertyNames[parameterIndex];
Mlt::Animation animation = m_filter->getAnimation(name);
if (!animation.is_valid()) {
LOG_ERROR() << "Invalid animation" << parameterIndex;
return;
}
if (keyframeIndex >= animation.key_count()) {
LOG_ERROR() << "Invalid key index" << parameterIndex << keyframeIndex;
return;
}
int position = animation.key_get_frame(keyframeIndex);
if (position < 0) {
LOG_ERROR() << "Invalid position" << parameterIndex << keyframeIndex;
return;
}
m_filter->startUndoModifyKeyframeCommand(parameterIndex, keyframeIndex);
mlt_keyframe_type type = animation.key_get_type(keyframeIndex);
m_filter->service().anim_set(name.toUtf8().constData(), value, position, m_filter->duration(),
type);
m_filter->updateUndoCommand(name);
for (auto &key : gangedProperties(parameterIndex)) {
m_filter->service().anim_set(key.toUtf8().constData(), value, position, m_filter->duration(), type);
m_filter->updateUndoCommand(key);
}
emit m_filter->changed(name.toUtf8().constData());
emit m_filter->propertyChanged(name.toUtf8().constData());
QModelIndex modelIndex = index(keyframeIndex, 0, index(parameterIndex));
emit dataChanged(modelIndex, modelIndex, QVector<int>() << NumericValueRole << NameRole);
emit dataChanged(index(parameterIndex), index(parameterIndex),
QVector<int>() << LowestValueRole << HighestValueRole);
m_filter->endUndoCommand();
}
void KeyframesModel::setKeyframeValuePosition(int parameterIndex, int keyframeIndex, double value,
int position)
{
if (!m_filter) {
LOG_ERROR() << "Invalid Filter" << parameterIndex;
return;
}
if (parameterIndex >= m_propertyNames.count()) {
LOG_ERROR() << "Invalid parameter index" << parameterIndex;
return;
}
QString name = m_propertyNames[parameterIndex];
Mlt::Animation animation = m_filter->getAnimation(name);
if (!animation.is_valid()) {
LOG_ERROR() << "Invalid animation" << parameterIndex;
return;
}
if (keyframeIndex >= animation.key_count()) {
LOG_ERROR() << "Invalid key index" << parameterIndex << keyframeIndex;
return;
}
if (position < 0) {
LOG_ERROR() << "Invalid key position" << parameterIndex << keyframeIndex << position;
return;
}
m_filter->startUndoModifyKeyframeCommand(parameterIndex, keyframeIndex);
QVector<int> roles;
int prevPosition = animation.key_get_frame(keyframeIndex);
if (position != prevPosition) {
if (animation.key_set_frame(keyframeIndex, position)) {
LOG_ERROR() << "Failed to set position" << parameterIndex << keyframeIndex << position;
return;
}
for (auto &key : gangedProperties(parameterIndex)) {
Mlt::Animation animation = m_filter->getAnimation(key);
if (animation.is_valid()) {
animation.key_set_frame(keyframeIndex, position);
}
}
roles << FrameNumberRole;
updateNeighborsMinMax(parameterIndex, keyframeIndex);
}
mlt_keyframe_type type = animation.key_get_type(keyframeIndex);
m_filter->service().anim_set(name.toUtf8().constData(), value, position, m_filter->duration(),
type);
m_filter->updateUndoCommand(name);
for (auto &key : gangedProperties(parameterIndex)) {
m_filter->service().anim_set(key.toUtf8().constData(), value, position, m_filter->duration(), type);
m_filter->updateUndoCommand(key);
}
emit m_filter->changed(name.toUtf8().constData());
emit m_filter->propertyChanged(name.toUtf8().constData());
roles << NumericValueRole << NameRole;
QModelIndex modelIndex = index(keyframeIndex, 0, index(parameterIndex));
emit dataChanged(modelIndex, modelIndex, roles);
emit dataChanged(index(parameterIndex), index(parameterIndex),
QVector<int>() << LowestValueRole << HighestValueRole);
m_filter->endUndoCommand();
}
bool KeyframesModel::isKeyframe(int parameterIndex, int position)
{
if (m_filter && parameterIndex < m_propertyNames.count()) {
QString name = m_propertyNames[parameterIndex];
Mlt::Animation anim = m_filter->getAnimation(name);
return anim.is_valid() && anim.is_key(position);
}
return false;
}
bool KeyframesModel::advancedKeyframesInUse()
{
if (m_filter && m_metadata && m_filter->animateIn() <= 0 && m_filter->animateOut() <= 0)
for (int i = 0; i < m_metadata->keyframes()->parameterCount(); i++) {
if (m_filter->keyframeCount(m_metadata->keyframes()->parameter(i)->property()) > 0) {
return true;
}
}
return false;
}
void KeyframesModel::removeAdvancedKeyframes()
{
if (m_filter && m_metadata && m_filter->animateIn() <= 0 && m_filter->animateOut() <= 0) {
for (int i = 0; i < m_metadata->keyframes()->parameterCount(); i++) {
QString name = m_metadata->keyframes()->parameter(i)->property();
if (m_filter->keyframeCount(name) > 0) {
m_filter->set(name, m_filter->get(name, 0));
m_filter->updateUndoCommand(name);
for (auto &key : m_metadata->keyframes()->parameter(i)->gangedProperties()) {
m_filter->set(key, m_filter->get(key, 0));
m_filter->updateUndoCommand(key);
}
}
}
reload();
}
}
bool KeyframesModel::simpleKeyframesInUse()
{
return m_filter && m_metadata && (m_filter->animateIn() > 0 || m_filter->animateOut() > 0);
}
void KeyframesModel::removeSimpleKeyframes()
{
if (simpleKeyframesInUse()) {
for (int i = 0; i < m_metadata->keyframes()->parameterCount(); i++) {
QString name = m_metadata->keyframes()->parameter(i)->property();
auto parameter = m_metadata->keyframes()->parameter(i);
if (parameter->gangedProperties().count() > 0) {
// Do not attempt to detect all matching keyframes for ganged properties.
// Always convert to advanced.
continue;
}
bool clearKeyframes = true;
// Find out if all keyframe values are the same. If they are all the same,
// then clear keyframes and set the parameter to a single value.
if (parameter->isRectangle()) {
auto firstValue = m_filter->getRect(name, 0);
Mlt::Animation anim = m_filter->getAnimation(name);
if (anim.is_valid()) {
for (int k = 1; k < anim.key_count(); k++) {
auto value = m_filter->getRect(name, anim.key_get_frame(k));
if (value != firstValue) {
clearKeyframes = false;
break;
}
}
}
if (clearKeyframes) {
m_filter->set(name, firstValue);
m_filter->updateUndoCommand(name);
}
} else if (parameter->isColor()) {
auto firstValue = m_filter->getColor(name, 0);
Mlt::Animation anim = m_filter->getAnimation(name);
if (anim.is_valid()) {
for (int k = 1; k < anim.key_count(); k++) {
auto value = m_filter->getColor(name, anim.key_get_frame(k));
if (value != firstValue) {
clearKeyframes = false;
break;
}
}
}
if (clearKeyframes) {
m_filter->set(name, firstValue);
m_filter->updateUndoCommand(name);
m_filter->blockSignals(true);
for (auto &key : parameter->gangedProperties()) {
m_filter->set(key, m_filter->getColor(key, 0));
m_filter->updateUndoCommand(key);
}
m_filter->blockSignals(false);
}
} else {
double firstValue = m_filter->getDouble(name, 0);
Mlt::Animation anim = m_filter->getAnimation(name);
if (anim.is_valid()) {
for (int k = 1; k < anim.key_count(); k++) {
auto value = m_filter->getDouble(name, anim.key_get_frame(k));
if (value != firstValue) {
clearKeyframes = false;
break;
}
}
}
if (clearKeyframes) {
m_filter->set(name, firstValue);
m_filter->updateUndoCommand(name);
m_filter->blockSignals(true);
for (auto &key : parameter->gangedProperties()) {
m_filter->set(key, m_filter->getDouble(key, 0));
m_filter->updateUndoCommand(key);
}
m_filter->blockSignals(false);
}
}
}
m_filter->clearAnimateInOut();
}
}
void KeyframesModel::reload()
{
beginResetModel();
m_propertyNames.clear();
m_keyframeCounts.clear();
m_metadataIndex.clear();
if (m_filter && m_metadata && m_filter->animateIn() <= 0 && m_filter->animateOut() <= 0)
for (int i = 0; i < m_metadata->keyframes()->parameterCount(); i++) {
if (m_filter->keyframeCount(m_metadata->keyframes()->parameter(i)->property()) > 0) {
m_propertyNames << m_metadata->keyframes()->parameter(i)->property();
m_keyframeCounts << keyframeCount(m_propertyNames.count() - 1);
m_metadataIndex << i;
}
}
endResetModel();
}
void KeyframesModel::onFilterChanged(const QString &property)
{
bool isKeyframeProperty = false;
for (int p = 0; p < m_metadata->keyframes()->parameterCount() && isKeyframeProperty == false; p++) {
if (m_metadata->keyframes()->parameter(p)->property() == property) {
isKeyframeProperty = true;
break;
}
}
if (!isKeyframeProperty) {
// Does not affect this model.
return;
}
int i = m_propertyNames.indexOf(property);
if (i < 0) {
// First keyframe added. Reset model to add this parameter.
reload();
return;
}
int prevCount = m_keyframeCounts[i];
m_keyframeCounts[i] = keyframeCount(i);
if (m_keyframeCounts[i] == 0) {
// All keyframes removed. Reset model to remove this parameter.
reload();
} else if (prevCount != m_keyframeCounts[i]) {
// Keyframe count changed. Remove all old and insert all new.
if (prevCount > 0) {
beginRemoveRows(index(i), 0, prevCount - 1);
endRemoveRows();
}
beginInsertRows(index(i), 0, m_keyframeCounts[i] - 1);
endInsertRows();
emit dataChanged(index(i), index(i), QVector<int>() << LowestValueRole << HighestValueRole);
} else {
// Keyframe count is unchanged. A value must have changed.
emit dataChanged(index(i), index(i), QVector<int>() << LowestValueRole << HighestValueRole);
emit dataChanged(index(0, 0, index(i)), index(m_keyframeCounts[i] - 1, 0, index(i)),
QVector<int>() << NumericValueRole << NameRole);
}
}
void KeyframesModel::onFilterInChanged(int /*delta*/)
{
QTimer::singleShot(0, this, SLOT(reload()));
}
void KeyframesModel::trimFilterIn(int in)
{
Mlt::Service &service = m_filter->service();
if (service.is_valid() && service.type() == mlt_service_filter_type) {
Mlt::Filter filter = service;
MLT.adjustFilter(&filter, filter.get_in(), filter.get_out(), in - filter.get_in(), 0,
in - filter.get_in());
m_filter->updateUndoCommand("in");
}
}
void KeyframesModel::trimFilterOut(int out)
{
Mlt::Service &service = m_filter->service();
if (service.is_valid() && service.type() == mlt_service_filter_type) {
Mlt::Filter filter = service;
MLT.adjustFilter(&filter, filter.get_in(), filter.get_out(), 0, filter.get_out() - out, 0);
m_filter->updateUndoCommand("out");
}
}
int KeyframesModel::keyframeCount(int index) const
{
if (index < m_propertyNames.count())
return qMax(const_cast<QmlFilter *>(m_filter)->keyframeCount(m_propertyNames[index]), 0);
else
return 0;
}
void KeyframesModel::updateNeighborsMinMax(int parameterIndex, int keyframeIndex)
{
QModelIndex modelIndex;
if (keyframeIndex > 0) {
modelIndex = index(keyframeIndex - 1, 0, index(parameterIndex));
emit dataChanged(modelIndex, modelIndex, QVector<int>() << MaximumFrameRole);
}
if (keyframeIndex < keyframeCount(parameterIndex) - 1) {
modelIndex = index(keyframeIndex + 1, 0, index(parameterIndex));
emit dataChanged(modelIndex, modelIndex, QVector<int>() << MinimumFrameRole);
}
}
QStringList KeyframesModel::gangedProperties(int parameterIndex) const
{
return m_metadata->keyframes()->parameter(m_metadataIndex[parameterIndex])->gangedProperties();
}
| 42,459
|
C++
|
.cpp
| 934
| 32.70985
| 121
| 0.551753
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,190
|
metadatamodel.cpp
|
mltframework_shotcut/src/models/metadatamodel.cpp
|
/*
* Copyright (c) 2014-2024 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "metadatamodel.h"
#include "controllers/filtercontroller.h"
#include "mainwindow.h"
#include "qmltypes/qmlmetadata.h"
#include "settings.h"
#include <Logger.h>
#include <QGuiApplication>
#include <QClipboard>
#include <QSaveFile>
MetadataModel::MetadataModel(QObject *parent)
: QSortFilterProxyModel(parent)
, m_filter(FavoritesFilter)
, m_isClipProducer(true)
, m_filterMask(HiddenMaskBit)
{
if (Settings.playerGPU()) {
m_filterMask |= gpuIncompatibleMaskBit;
} else {
m_filterMask |= needsGPUMaskBit;
}
setSourceModel(new InternalMetadataModel(this));
}
int MetadataModel::rowCount(const QModelIndex &parent) const
{
return QSortFilterProxyModel::rowCount(parent);
}
int MetadataModel::sourceRowCount(const QModelIndex &parent) const
{
return static_cast<InternalMetadataModel *>(sourceModel())->rowCount();
}
int InternalMetadataModel::rowCount(const QModelIndex &) const
{
return m_list.size();
}
QVariant InternalMetadataModel::data(const QModelIndex &index, int role) const
{
QVariant result;
QmlMetadata *meta = m_list.at(index.row());
if (meta) {
switch (role) {
case Qt::DisplayRole:
case MetadataModel::NameRole:
result = meta->name();
break;
case MetadataModel::HiddenRole:
result = meta->isHidden();
break;
case MetadataModel::FavoriteRole:
result = meta->isFavorite();
break;
case MetadataModel::ServiceRole:
result = meta->mlt_service();
break;
case MetadataModel::IsAudioRole:
result = meta->isAudio();
break;
case MetadataModel::NeedsGpuRole:
result = meta->needsGPU();
break;
case MetadataModel::PluginTypeRole:
result = meta->type();
break;
}
}
return result;
}
bool InternalMetadataModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
if (!index.isValid()) return false;
switch (role) {
case MetadataModel::FavoriteRole: {
QmlMetadata *meta = m_list.at(index.row());
meta->setIsFavorite(value.value<bool>());
emit dataChanged(index, index);
break;
}
}
return true;
}
QHash<int, QByteArray> InternalMetadataModel::roleNames() const
{
QHash<int, QByteArray> roles = QAbstractListModel::roleNames();
roles[MetadataModel::NameRole] = "name";
roles[MetadataModel::HiddenRole] = "hidden";
roles[MetadataModel::FavoriteRole] = "favorite";
roles[MetadataModel::ServiceRole] = "service";
roles[MetadataModel::IsAudioRole] = "isAudio";
roles[MetadataModel::NeedsGpuRole] = "needsGpu";
roles[MetadataModel::PluginTypeRole] = "pluginType";
return roles;
}
Qt::ItemFlags InternalMetadataModel::flags(const QModelIndex &index) const
{
if (!index.isValid())
return Qt::NoItemFlags;
return QAbstractListModel::flags(index) | Qt::ItemIsEditable | Qt::ItemIsSelectable;
}
void MetadataModel::add(QmlMetadata *data)
{
static_cast<InternalMetadataModel *>(sourceModel())->add(data);
}
void InternalMetadataModel::add(QmlMetadata *data)
{
int i = 0;
for ( i = 0; i < m_list.size(); i++ ) {
if (m_list[i]->name().toLower() > data->name().toLower() ) {
break;
}
}
data->filterMask = computeFilterMask(data);
beginInsertRows(QModelIndex(), i, i);
m_list.insert(i, data);
endInsertRows();
data->setParent(this);
}
QmlMetadata *MetadataModel::get(int row) const
{
auto sourceIndex = mapToSource(index(row, 0));
return getFromSource(sourceIndex.row());
}
QmlMetadata *MetadataModel::getFromSource(int index) const
{
return static_cast<InternalMetadataModel *>(sourceModel())->get(index);
}
QmlMetadata *InternalMetadataModel::get(int index) const
{
if (index >= 0 && index < m_list.size()) {
return m_list[index];
}
return nullptr;
}
void InternalMetadataModel::remove(int index)
{
beginRemoveRows(QModelIndex(), index, index);
m_list.remove(index);
endRemoveRows();
}
void MetadataModel::setFilter(MetadataFilter filter)
{
m_filter = filter;
emit filterChanged();
invalidateFilter();
}
void MetadataModel::setSearch(const QString &search)
{
m_search = search;
emit searchChanged();
invalidateFilter();
}
bool MetadataModel::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const
{
auto meta = getFromSource(sourceRow);
if (meta->filterMask & m_filterMask) {
return false;
}
if (Settings.playerGPU() && meta->needsGPU() && MAIN.filterController()->isOutputTrackSelected()) {
return false;
}
if (m_search.isEmpty()) {
switch (m_filter) {
case FavoritesFilter:
if (!meta->isFavorite()) return false;
break;
case VideoFilter:
if (meta->isAudio() || meta->needsGPU() || meta->type() == QmlMetadata::Link
|| meta->type() == QmlMetadata::FilterSet) return false;
break;
case AudioFilter:
if (!meta->isAudio()) return false;
break;
case LinkFilter:
if (meta->type() != QmlMetadata::Link) return false;
break;
case FilterSetFilter:
if (meta->type() != QmlMetadata::FilterSet) return false;
break;
case GPUFilter:
if (!meta->needsGPU()) return false;
break;
default:
break;
}
} else if (!meta->name().contains(m_search, Qt::CaseInsensitive)
&& !meta->keywords().contains(m_search, Qt::CaseInsensitive)) {
return false;
}
return true;
}
void MetadataModel::updateFilterMask(bool isClipProducer, bool isChainProducer,
bool isTrackProducer, bool isOutputProducer)
{
beginResetModel();
m_isClipProducer = isClipProducer;
if (m_isClipProducer) {
m_filterMask &= ~clipOnlyMaskBit;
} else {
m_filterMask |= clipOnlyMaskBit;
}
m_isChainProducer = isChainProducer;
if (m_isChainProducer) {
m_filterMask &= ~linkMaskBit;
} else {
m_filterMask |= linkMaskBit;
}
m_isTrackProducer = isTrackProducer;
if (m_isTrackProducer) {
m_filterMask &= ~trackOnlyMaskBit;
} else {
m_filterMask |= trackOnlyMaskBit;
}
m_isOutputProducer = isOutputProducer;
if (m_isOutputProducer) {
m_filterMask &= ~outputOnlyMaskBit;
} else {
m_filterMask |= outputOnlyMaskBit;
}
endResetModel();
}
unsigned InternalMetadataModel::computeFilterMask(const QmlMetadata *meta)
{
unsigned mask = 0;
if (meta->isHidden()) mask |= MetadataModel::HiddenMaskBit;
if (meta->isClipOnly()) mask |= MetadataModel::clipOnlyMaskBit;
if (meta->isTrackOnly()) mask |= MetadataModel::trackOnlyMaskBit;
if (meta->isOutputOnly()) mask |= MetadataModel::outputOnlyMaskBit;
if (!meta->isGpuCompatible()) mask |= MetadataModel::gpuIncompatibleMaskBit;
if (meta->needsGPU()) mask |= MetadataModel::needsGPUMaskBit;
if (meta->type() == QmlMetadata::Link) mask |= MetadataModel::linkMaskBit;
return mask;
}
void MetadataModel::saveFilterSet(const QString &name)
{
QDir dir(Settings.appDataLocation());
const auto folder = QString::fromLatin1("filter-sets");
if (!dir.exists())
dir.mkpath(dir.path());
if (!dir.cd(folder)) {
if (dir.mkdir(folder))
dir.cd(folder);
}
auto filename = QString::fromUtf8(QUrl::toPercentEncoding(name));
auto exists = dir.exists(filename);
QSaveFile file(dir.filePath(filename));
file.setDirectWriteFallback(true);
if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
LOG_ERROR() << "failed to open filter set file for writing" << file.fileName();
return;
}
QTextStream stream(&file);
stream.setEncoding(QStringConverter::Utf8);
stream << QGuiApplication::clipboard()->text();
if (file.error() != QFileDevice::NoError) {
LOG_ERROR() << "error while writing filter set file" << file.fileName() << ":" <<
file.errorString();
return;
}
if (file.commit() && !exists) {
auto meta = new QmlMetadata;
meta->setType(QmlMetadata::FilterSet);
meta->setName(name);
auto model = static_cast<InternalMetadataModel *>(sourceModel());
model->add(meta);
}
}
void MetadataModel::deleteFilterSet(const QString &name)
{
QDir dir(Settings.appDataLocation());
if (!dir.cd("filter-sets"))
return;
auto fileName = QUrl::toPercentEncoding(name.toUtf8());
if (QFile::remove(dir.filePath(fileName)) || QFile::remove(dir.filePath(name))) {
auto i = 0;
auto source = static_cast<InternalMetadataModel *>(sourceModel());
auto list = source->list();
for (const auto &meta : list) {
if (meta->type() == QmlMetadata::FilterSet && meta->name() == name)
source->remove(i);
++i;
}
}
}
| 9,880
|
C++
|
.cpp
| 297
| 27.400673
| 103
| 0.656966
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,191
|
multitrackmodel.cpp
|
mltframework_shotcut/src/models/multitrackmodel.cpp
|
/*
* Copyright (c) 2013-2024 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "multitrackmodel.h"
#include "mltcontroller.h"
#include "mainwindow.h"
#include "settings.h"
#include "docks/playlistdock.h"
#include "util.h"
#include "audiolevelstask.h"
#include "shotcut_mlt_properties.h"
#include "controllers/filtercontroller.h"
#include "qmltypes/qmlmetadata.h"
#include "proxymanager.h"
#include "dialogs/longuitask.h"
#include <QScopedPointer>
#include <QApplication>
#include <qmath.h>
#include <QTimer>
#include <QMessageBox>
#include <Logger.h>
static const quintptr NO_PARENT_ID = quintptr(-1);
static const char *kShotcutDefaultTransition = "lumaMix";
MultitrackModel::MultitrackModel(QObject *parent)
: QAbstractItemModel(parent)
, m_tractor(0)
, m_isMakingTransition(false)
{
connect(this, SIGNAL(modified()), SLOT(adjustBackgroundDuration()));
connect(this, SIGNAL(modified()), SLOT(adjustTrackFilters()));
connect(this, SIGNAL(reloadRequested()), SLOT(reload()), Qt::QueuedConnection);
connect(this, &MultitrackModel::created, this, &MultitrackModel::scaleFactorChanged);
}
MultitrackModel::~MultitrackModel()
{
delete m_tractor;
m_tractor = 0;
}
int MultitrackModel::rowCount(const QModelIndex &parent) const
{
if (!m_tractor)
return 0;
if (parent.isValid()) {
if (parent.internalId() != NO_PARENT_ID)
return 0;
int i = m_trackList.at(parent.row()).mlt_index;
QScopedPointer<Mlt::Producer> track(m_tractor->track(i));
if (track) {
Mlt::Playlist playlist(*track);
int n = playlist.count();
// LOG_DEBUG() << __FUNCTION__ << parent << i << n;
return n;
} else {
return 0;
}
}
return m_trackList.count();
}
int MultitrackModel::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return 1;
}
QVariant MultitrackModel::data(const QModelIndex &index, int role) const
{
if (!m_tractor || !index.isValid())
return QVariant();
if (index.parent().isValid()) {
// Get data for a clip.
int i = m_trackList.at(index.internalId()).mlt_index;
QScopedPointer<Mlt::Producer> track(m_tractor->track(i));
if (track) {
Mlt::Playlist playlist(*track);
// LOG_DEBUG() << __FUNCTION__ << index.row();
QScopedPointer<Mlt::ClipInfo> info(playlist.clip_info(index.row()));
if (info)
switch (role) {
case NameRole: {
QString result;
if (info->producer && info->producer->is_valid()) {
result = info->producer->get(kShotcutCaptionProperty);
if (result.isNull()) {
result = Util::baseName(ProxyManager::resource(*info->producer));
if (!::qstrcmp(info->producer->get("mlt_service"), "timewarp")) {
double speed = ::fabs(info->producer->get_double("warp_speed"));
result = QStringLiteral("%1 (%2x)").arg(result).arg(speed);
}
}
if (result == "<producer>") {
result = QString::fromUtf8(info->producer->get("mlt_service"));
}
if (info->producer->get_int(kIsProxyProperty)) {
result.append("\n" + tr("(PROXY)"));
}
}
return result;
}
case CommentRole: {
QString result;
if (info->producer && info->producer->is_valid()) {
result = info->producer->get(kCommentProperty);
}
return result;
}
case ResourceRole:
case Qt::DisplayRole: {
QString result = QString::fromUtf8(info->resource);
if (result == "<producer>" && info->producer
&& info->producer->is_valid() && info->producer->get("mlt_service"))
result = QString::fromUtf8(info->producer->get("mlt_service"));
return result;
}
case ServiceRole:
if (info->producer && info->producer->is_valid())
return QString::fromUtf8(info->producer->get("mlt_service"));
break;
case IsBlankRole:
return playlist.is_blank(index.row());
case StartRole:
return info->start;
case DurationRole:
return info->frame_count;
case InPointRole:
return info->frame_in;
case OutPointRole:
return info->frame_out;
case FramerateRole:
return info->fps;
case IsAudioRole:
return m_trackList[index.internalId()].type == AudioTrackType;
case AudioLevelsRole: {
QVariant result;
if (info->producer && info->producer->is_valid()) {
info->producer->lock();
if (info->producer->get_data(kAudioLevelsProperty)) {
result = QVariant::fromValue(*((QVariantList *) info->producer->get_data(kAudioLevelsProperty)));
}
info->producer->unlock();
}
return result;
}
case FadeInRole: {
QScopedPointer<Mlt::Filter> filter(getFilter("fadeInVolume", info->producer));
if (!filter || !filter->is_valid())
filter.reset(getFilter("fadeInBrightness", info->producer));
if (!filter || !filter->is_valid())
filter.reset(getFilter("fadeInMovit", info->producer));
if (filter && filter->is_valid() && filter->get(kShotcutAnimInProperty))
return filter->get_int(kShotcutAnimInProperty);
else
return (filter && filter->is_valid()) ? filter->get_length() : 0;
}
case FadeOutRole: {
QScopedPointer<Mlt::Filter> filter(getFilter("fadeOutVolume", info->producer));
if (!filter || !filter->is_valid())
filter.reset(getFilter("fadeOutBrightness", info->producer));
if (!filter || !filter->is_valid())
filter.reset(getFilter("fadeOutMovit", info->producer));
if (filter && filter->is_valid() && filter->get(kShotcutAnimOutProperty))
return filter->get_int(kShotcutAnimOutProperty);
else
return (filter && filter->is_valid()) ? filter->get_length() : 0;
}
case IsTransitionRole:
return isTransition(playlist, index.row());
case FileHashRole:
return Util::getHash(*info->producer);
case SpeedRole: {
double speed = 1.0;
if (info->producer && info->producer->is_valid()) {
if (!qstrcmp("timewarp", info->producer->get("mlt_service")))
speed = info->producer->get_double("warp_speed");
}
return speed;
}
case IsFilteredRole:
return isFiltered(info->producer);
case AudioIndexRole:
return QString::fromLatin1(info->producer->get("audio_index"));
case GroupRole:
if (info->cut->property_exists(kShotcutGroupProperty))
return info->cut->get_int(kShotcutGroupProperty);
else
return -1;
default:
break;
}
}
} else {
// Get data for a track.
int i = m_trackList.at(index.row()).mlt_index;
QScopedPointer<Mlt::Producer> track(m_tractor->track(i));
if (track) {
Mlt::Playlist playlist(*track);
switch (role) {
case NameRole:
case Qt::DisplayRole:
return QString::fromUtf8(track->get(kTrackNameProperty));
case DurationRole:
return playlist.get_playtime();
case IsMuteRole:
return playlist.get_int("hide") & 2;
case IsHiddenRole:
return playlist.get_int("hide") & 1;
case IsAudioRole:
return m_trackList[index.row()].type == AudioTrackType;
case IsLockedRole:
return track->get_int(kTrackLockProperty);
case IsCompositeRole: {
QScopedPointer<Mlt::Transition> transition(getVideoBlendTransition(i));
if (transition && transition->is_valid()) {
if (!transition->get_int("disable"))
return true;
}
return false;
}
case IsFilteredRole:
return isFiltered(track.data());
case IsTopVideoRole:
if (m_trackList[index.row()].type == AudioTrackType) return false;
foreach (const Track &t, m_trackList) {
if (t.type == VideoTrackType && t.number > m_trackList[index.row()].number) {
return false;
}
}
return true;
case IsBottomVideoRole:
return m_trackList[index.row()].number == 0 && m_trackList[index.row()].type == VideoTrackType;
case IsTopAudioRole:
return m_trackList[index.row()].number == 0 && m_trackList[index.row()].type == AudioTrackType;
case IsBottomAudioRole:
if (m_trackList[index.row()].type == VideoTrackType) return false;
foreach (const Track &t, m_trackList) {
if (t.type == AudioTrackType && t.number > m_trackList[index.row()].number) {
return false;
}
}
return true;
default:
break;
}
}
}
return QVariant();
}
QModelIndex MultitrackModel::index(int row, int column, const QModelIndex &parent) const
{
if (column > 0)
return QModelIndex();
// LOG_DEBUG() << __FUNCTION__ << row << column << parent;
QModelIndex result;
if (parent.isValid()) {
int i = m_trackList.at(parent.row()).mlt_index;
QScopedPointer<Mlt::Producer> track(m_tractor->track(i));
if (track) {
Mlt::Playlist playlist((mlt_playlist) track->get_producer());
if (row < playlist.count())
result = createIndex(row, column, parent.row());
}
} else if (row < m_trackList.count()) {
result = createIndex(row, column, NO_PARENT_ID);
}
return result;
}
QModelIndex MultitrackModel::makeIndex(int trackIndex, int clipIndex) const
{
return index(clipIndex, 0, index(trackIndex));
}
QModelIndex MultitrackModel::parent(const QModelIndex &index) const
{
// LOG_DEBUG() << __FUNCTION__ << index;
if (!index.isValid() || index.internalId() == NO_PARENT_ID)
return QModelIndex();
else
return createIndex(index.internalId(), 0, NO_PARENT_ID);
}
QHash<int, QByteArray> MultitrackModel::roleNames() const
{
QHash<int, QByteArray> roles;
roles[NameRole] = "name";
roles[CommentRole] = "comment";
roles[ResourceRole] = "resource";
roles[ServiceRole] = "mlt_service";
roles[IsBlankRole] = "blank";
roles[StartRole] = "start";
roles[DurationRole] = "duration";
roles[InPointRole] = "in";
roles[OutPointRole] = "out";
roles[FramerateRole] = "fps";
roles[IsMuteRole] = "mute";
roles[IsHiddenRole] = "hidden";
roles[IsAudioRole] = "audio";
roles[AudioLevelsRole] = "audioLevels";
roles[IsCompositeRole] = "composite";
roles[IsLockedRole] = "locked";
roles[FadeInRole] = "fadeIn";
roles[FadeOutRole] = "fadeOut";
roles[IsTransitionRole] = "isTransition";
roles[FileHashRole] = "hash";
roles[SpeedRole] = "speed";
roles[IsFilteredRole] = "filtered";
roles[IsTopVideoRole] = "isTopVideo";
roles[IsBottomVideoRole] = "isBottomVideo";
roles[IsTopAudioRole] = "isTopAudio";
roles[IsBottomAudioRole] = "isBottomAudio";
roles[AudioIndexRole] = "audioIndex";
roles[GroupRole] = "group";
return roles;
}
void MultitrackModel::setTrackName(int row, const QString &value)
{
if (row < m_trackList.size()) {
int i = m_trackList.at(row).mlt_index;
QScopedPointer<Mlt::Producer> track(m_tractor->track(i));
if (track) {
track->set(kTrackNameProperty, value.toUtf8().constData());
QModelIndex modelIndex = index(row, 0);
QVector<int> roles;
roles << NameRole;
emit dataChanged(modelIndex, modelIndex, roles);
emit modified();
}
}
}
void MultitrackModel::setTrackMute(int row, bool mute)
{
if (row < m_trackList.size()) {
int i = m_trackList.at(row).mlt_index;
QScopedPointer<Mlt::Producer> track(m_tractor->track(i));
if (track) {
int hide = track->get_int("hide");
if (mute)
hide |= 2;
else
hide ^= 2;
track->set("hide", hide);
QModelIndex modelIndex = index(row, 0);
QVector<int> roles;
roles << IsMuteRole;
emit dataChanged(modelIndex, modelIndex, roles);
emit modified();
}
}
}
void MultitrackModel::setTrackHidden(int row, bool hidden)
{
if (row < m_trackList.size()) {
int i = m_trackList.at(row).mlt_index;
QScopedPointer<Mlt::Producer> track(m_tractor->track(i));
if (track) {
int hide = track->get_int("hide");
if (hidden)
hide |= 1;
else
hide ^= 1;
track->set("hide", hide);
MLT.refreshConsumer();
QModelIndex modelIndex = index(row, 0);
QVector<int> roles;
roles << IsHiddenRole;
emit dataChanged(modelIndex, modelIndex, roles);
emit modified();
}
}
}
void MultitrackModel::setTrackComposite(int row, bool composite)
{
if (row < m_trackList.size()) {
int i = m_trackList.at(row).mlt_index;
QScopedPointer<Mlt::Transition> transition(getVideoBlendTransition(i));
if (transition && transition->is_valid()) {
transition->set("disable", !composite);
}
MLT.refreshConsumer();
QModelIndex modelIndex = index(row, 0);
QVector<int> roles;
roles << IsCompositeRole;
emit dataChanged(modelIndex, modelIndex, roles);
emit modified();
}
}
void MultitrackModel::setTrackLock(int row, bool lock)
{
if (row < m_trackList.size()) {
int i = m_trackList.at(row).mlt_index;
QScopedPointer<Mlt::Producer> track(m_tractor->track(i));
track->set(kTrackLockProperty, lock);
QModelIndex modelIndex = index(row, 0);
QVector<int> roles;
roles << IsLockedRole;
emit dataChanged(modelIndex, modelIndex, roles);
emit modified();
}
}
bool MultitrackModel::trimClipInValid(int trackIndex, int clipIndex, int delta, bool ripple)
{
bool result = true;
int i = m_trackList.at(trackIndex).mlt_index;
QScopedPointer<Mlt::Producer> track(m_tractor->track(i));
if (track) {
Mlt::Playlist playlist(*track);
QScopedPointer<Mlt::ClipInfo> info(playlist.clip_info(clipIndex));
if (!info || (info->frame_in + delta) < 0 || (info->frame_in + delta) > info->frame_out)
result = false;
else if (!ripple && delta < 0 && clipIndex <= 0)
result = false;
else if (!ripple && delta < 0 && clipIndex > 0 && !playlist.is_blank(clipIndex - 1))
result = false;
else if (!ripple && delta > 0 && clipIndex > 0 && isTransition(playlist, clipIndex - 1))
result = false;
}
return result;
}
int MultitrackModel::trimClipIn(int trackIndex, int clipIndex, int delta, bool ripple,
bool rippleAllTracks)
{
int result = clipIndex;
QList<int> otherTracksToRipple;
int otherTracksPosition = -1;
for (int i = 0; i < m_trackList.count(); ++i) {
int mltIndex = m_trackList.at(i).mlt_index;
QScopedPointer<Mlt::Producer> track(m_tractor->track(mltIndex));
if (!track)
continue;
//when not rippling, never touch the other tracks
if (trackIndex != i && (!ripple || !rippleAllTracks))
continue;
if (rippleAllTracks) {
if (track->get_int(kTrackLockProperty))
continue;
if (trackIndex != i && ripple) {
otherTracksToRipple << i;
continue;
}
}
Mlt::Playlist playlist(*track);
if (!playlist.is_valid()) {
LOG_DEBUG() << "Invalid Playlist" << trackIndex;
continue;
}
if (clipIndex >= playlist.count()) {
LOG_DEBUG() << "Invalid Clip Index" << clipIndex;
continue;
}
QScopedPointer<Mlt::ClipInfo> info(playlist.clip_info(clipIndex));
if (!info) {
LOG_DEBUG() << "Invalid clip info";
continue;
}
// These are used to adjust filters but must be retrieved before changing clip length.
int filterIn = MLT.filterIn(playlist, clipIndex);
int filterOut = MLT.filterOut(playlist, clipIndex);
Q_ASSERT(otherTracksPosition == -1);
otherTracksPosition = info->start;
if (info->frame_in + delta < 0)
// clamp to clip start
delta = -info->frame_in;
if (clipIndex > 0 && playlist.is_blank(clipIndex - 1)
&& -delta > playlist.clip_length(clipIndex - 1))
// clamp to duration of blank space
delta = -playlist.clip_length(clipIndex - 1);
// LOG_DEBUG() << "delta" << delta;
playlist.resize_clip(clipIndex, info->frame_in + delta, info->frame_out);
// Adjust filters.
MLT.adjustClipFilters(*info->producer, filterIn, filterOut, delta, 0, delta);
QModelIndex modelIndex = createIndex(clipIndex, 0, i);
QVector<int> roles;
roles << DurationRole;
roles << InPointRole;
emit dataChanged(modelIndex, modelIndex, roles);
AudioLevelsTask::start(*info->producer, this, modelIndex);
if (!ripple) {
// Adjust left of the clip.
if (clipIndex > 0 && playlist.is_blank(clipIndex - 1)) {
int out = playlist.clip_length(clipIndex - 1) + delta - 1;
if (out < 0) {
// LOG_DEBUG() << "remove blank at left";
beginRemoveRows(index(i), clipIndex - 1, clipIndex - 1);
playlist.remove(clipIndex - 1);
endRemoveRows();
--result;
} else {
// LOG_DEBUG() << "adjust blank on left to" << out;
playlist.resize_clip(clipIndex - 1, 0, out);
QModelIndex index = createIndex(clipIndex - 1, 0, i);
QVector<int> roles;
roles << DurationRole;
emit dataChanged(index, index, roles);
}
} else if (delta > 0) {
// LOG_DEBUG() << "add blank on left duration" << delta - 1;
beginInsertRows(index(i), clipIndex, clipIndex);
playlist.insert_blank(clipIndex, delta - 1);
endInsertRows();
++result;
}
} else if (isTransition(playlist, clipIndex - 1)) {
// Adjust a transition on the left
std::unique_ptr<Mlt::Producer> producer(playlist.get_clip(clipIndex - 1));
Mlt::Tractor tractor(producer->parent());
std::unique_ptr<Mlt::Producer> track_b(tractor.track(1));
playlist.block();
track_b->set_in_and_out(track_b->get_in() + delta, track_b->get_out() + delta);
playlist.unblock();
}
emit modified();
}
if (delta > 0) {
foreach (int idx, otherTracksToRipple) {
Q_ASSERT(otherTracksPosition != -1);
removeRegion(idx, otherTracksPosition, delta);
}
} else {
insertOrAdjustBlankAt(otherTracksToRipple, otherTracksPosition, -delta);
}
return result;
}
void MultitrackModel::notifyClipIn(int trackIndex, int clipIndex)
{
if (trackIndex >= 0 && trackIndex < m_trackList.size() && clipIndex >= 0) {
QModelIndex index = createIndex(clipIndex, 0, trackIndex);
QVector<int> roles;
roles << AudioLevelsRole;
emit dataChanged(index, index, roles);
MLT.refreshConsumer();
}
m_isMakingTransition = false;
}
bool MultitrackModel::trimClipOutValid(int trackIndex, int clipIndex, int delta, bool ripple)
{
bool result = true;
int i = m_trackList.at(trackIndex).mlt_index;
QScopedPointer<Mlt::Producer> track(m_tractor->track(i));
if (track) {
Mlt::Playlist playlist(*track);
QScopedPointer<Mlt::ClipInfo> info(playlist.clip_info(clipIndex));
if (!info || (info->frame_out - delta) >= info->length
|| (info->frame_out - delta) < info->frame_in)
result = false;
else if (!ripple && delta < 0 && (clipIndex + 1) < playlist.count()
&& !playlist.is_blank(clipIndex + 1))
result = false;
else if (!ripple && delta > 0 && (clipIndex + 1) < playlist.count()
&& isTransition(playlist, clipIndex + 1))
return false;
}
return result;
}
int MultitrackModel::trackHeight() const
{
int result = m_tractor ? m_tractor->get_int(kTrackHeightProperty) : Settings.timelineTrackHeight();
return qBound(10, result ? result : Settings.timelineTrackHeight(), 150);
}
void MultitrackModel::setTrackHeight(int height)
{
if (m_tractor) {
Settings.setTimelineTrackHeight(qBound(10, height, 150));
m_tractor->set(kTrackHeightProperty, Settings.timelineTrackHeight());
emit trackHeightChanged();
}
}
double MultitrackModel::scaleFactor() const
{
double result = m_tractor ? m_tractor->get_double(kTimelineScaleProperty) : 0;
return (result > 0) ? qBound(0.0, result, 27.01) : (qPow(1.0, 3.0) + 0.01);
}
void MultitrackModel::setScaleFactor(double scale)
{
if (m_tractor) {
m_tractor->set(kTimelineScaleProperty, qBound(0.0, scale, 27.01));
emit scaleFactorChanged();
}
}
int MultitrackModel::trimClipOut(int trackIndex, int clipIndex, int delta, bool ripple,
bool rippleAllTracks)
{
QList<int> otherTracksToRipple;
int result = clipIndex;
int otherTracksPosition = -1;
for (int i = 0; i < m_trackList.count(); ++i) {
int mltIndex = m_trackList.at(i).mlt_index;
QScopedPointer<Mlt::Producer> track(m_tractor->track(mltIndex));
if (!track)
continue;
Mlt::Playlist playlist(*track);
QScopedPointer<Mlt::ClipInfo> info(playlist.clip_info(clipIndex));
// These are used to adjust filters but must be retrieved before changing clip length.
int filterIn = MLT.filterIn(playlist, clipIndex);
int filterOut = MLT.filterOut(playlist, clipIndex);
//when not rippling, never touch the other tracks
if (trackIndex != i && (!ripple || !rippleAllTracks))
continue;
if (rippleAllTracks) {
if (track->get_int(kTrackLockProperty))
continue;
if (trackIndex != i && ripple) {
otherTracksToRipple << i;
continue;
}
}
Q_ASSERT(otherTracksPosition == -1);
otherTracksPosition = info->start + info->frame_count;
if ((info->frame_out - delta) >= info->length)
// clamp to clip duration
delta = info->frame_out - info->length + 1;
if ((clipIndex + 1) < playlist.count() && playlist.is_blank(clipIndex + 1)
&& -delta > playlist.clip_length(clipIndex + 1))
delta = -playlist.clip_length(clipIndex + 1);
// LOG_DEBUG() << "delta" << delta;
if (!ripple) {
// Adjust right of the clip.
if (clipIndex >= 0 && (clipIndex + 1) < playlist.count() && playlist.is_blank(clipIndex + 1)) {
int out = playlist.clip_length(clipIndex + 1) + delta - 1;
if (out < 0) {
// LOG_DEBUG() << "remove blank at right";
beginRemoveRows(index(i), clipIndex + 1, clipIndex + 1);
playlist.remove(clipIndex + 1);
endRemoveRows();
} else {
// LOG_DEBUG() << "adjust blank on right to" << out;
playlist.resize_clip(clipIndex + 1, 0, out);
QModelIndex index = createIndex(clipIndex + 1, 0, i);
QVector<int> roles;
roles << DurationRole;
emit dataChanged(index, index, roles);
}
} else if (delta > 0 && (clipIndex + 1) < playlist.count()) {
// Add blank to right.
// LOG_DEBUG() << "add blank on right duration" << (delta - 1);
int newIndex = clipIndex + 1;
beginInsertRows(index(i), newIndex, newIndex);
playlist.insert_blank(newIndex, delta - 1);
endInsertRows();
}
} else if (isTransition(playlist, clipIndex + 1)) {
// Adjust a transition on the right
std::unique_ptr<Mlt::Producer> producer(playlist.get_clip(clipIndex + 1));
Mlt::Tractor tractor(producer->parent());
std::unique_ptr<Mlt::Producer> track_a(tractor.track(0));
playlist.block();
track_a->set_in_and_out(track_a->get_in() - delta, track_a->get_out() - delta);
playlist.unblock();
}
playlist.resize_clip(clipIndex, info->frame_in, info->frame_out - delta);
// Adjust filters.
MLT.adjustClipFilters(*info->producer, filterIn, filterOut, 0, delta, 0);
QModelIndex index = createIndex(clipIndex, 0, i);
QVector<int> roles;
roles << DurationRole;
roles << OutPointRole;
emit dataChanged(index, index, roles);
AudioLevelsTask::start(*info->producer, this, index);
emit modified();
}
if (delta > 0) {
foreach (int idx, otherTracksToRipple) {
Q_ASSERT(otherTracksPosition != -1);
removeRegion(idx, otherTracksPosition - delta, delta);
}
} else {
insertOrAdjustBlankAt(otherTracksToRipple, otherTracksPosition, -delta);
}
return result;
}
void MultitrackModel::notifyClipOut(int trackIndex, int clipIndex)
{
if (trackIndex >= 0 && trackIndex < m_trackList.size() && clipIndex >= 0) {
QModelIndex index = createIndex(clipIndex, 0, trackIndex);
QVector<int> roles;
roles << AudioLevelsRole;
emit dataChanged(index, index, roles);
MLT.refreshConsumer();
}
m_isMakingTransition = false;
}
bool MultitrackModel::moveClip(int fromTrack, int toTrack, int clipIndex,
int position, bool ripple, bool rippleAllTracks)
{
// LOG_DEBUG() << __FUNCTION__ << clipIndex << "fromTrack" << fromTrack << "toTrack" << toTrack;
bool result = false;
int i = m_trackList.at(fromTrack).mlt_index;
QScopedPointer<Mlt::Producer> track(m_tractor->track(i));
if (track) {
Mlt::Playlist playlist(*track);
QScopedPointer<Mlt::ClipInfo> info(playlist.clip_info(clipIndex));
QString xml = MLT.XML(info->producer);
Mlt::Producer clip(MLT.profile(), "xml-string", xml.toUtf8().constData());
if (clip.is_valid()) {
clearMixReferences(fromTrack, clipIndex);
clip.set_in_and_out(info->frame_in, info->frame_out);
if (ripple) {
int targetIndex = playlist.get_clip_index_at(position);
int length = playlist.clip_length(clipIndex);
int targetIndexEnd = playlist.get_clip_index_at(position + length - 1);
if ((clipIndex + 1) < playlist.count() && position >= playlist.get_playtime()) {
// Clip relocated to end of playlist.
moveClipToEnd(playlist, toTrack, clipIndex, position, ripple, rippleAllTracks);
emit modified();
} else if (fromTrack == toTrack && targetIndex >= clipIndex) {
// Push the clips.
int clipStart = playlist.clip_start(clipIndex);
int duration = position - clipStart;
QList<int> trackList;
trackList << fromTrack;
if (rippleAllTracks) {
for (int i = 0; i < m_trackList.count(); ++i) {
if (i == fromTrack)
continue;
int mltIndex = m_trackList.at(i).mlt_index;
QScopedPointer<Mlt::Producer> otherTrack(m_tractor->track(mltIndex));
if (otherTrack && otherTrack->get_int(kTrackLockProperty))
continue;
trackList << i;
}
}
insertOrAdjustBlankAt(trackList, clipStart, duration);
consolidateBlanks(playlist, fromTrack);
emit modified();
} else if (fromTrack == toTrack && (playlist.is_blank_at(position) || targetIndex == clipIndex) &&
(playlist.is_blank_at(position + length - 1) || targetIndexEnd == clipIndex)) {
// Reposition the clip within its current blank spot.
moveClipInBlank(playlist, toTrack, clipIndex, position, ripple, rippleAllTracks);
emit modified();
} else {
int clipPlaytime = clip.get_playtime();
int clipStart = playlist.clip_start(clipIndex);
// Remove clip
clearMixReferences(fromTrack, clipIndex);
emit removing(playlist.get_clip(clipIndex));
beginRemoveRows(index(fromTrack), clipIndex, clipIndex);
playlist.remove(clipIndex);
endRemoveRows();
consolidateBlanks(playlist, fromTrack);
// Ripple delete on all unlocked tracks.
if (clipPlaytime > 0 && rippleAllTracks)
for (int j = 0; j < m_trackList.count(); ++j) {
if (j == fromTrack)
continue;
int mltIndex = m_trackList.at(j).mlt_index;
QScopedPointer<Mlt::Producer> otherTrack(m_tractor->track(mltIndex));
if (otherTrack) {
if (otherTrack->get_int(kTrackLockProperty))
continue;
removeRegion(j, clipStart, clipPlaytime);
}
}
consolidateBlanks(playlist, fromTrack);
// Insert clip
insertClip(toTrack, clip, position, rippleAllTracks, false);
}
} else {
// Lift clip
emit removing(playlist.get_clip(clipIndex));
delete playlist.replace_with_blank(clipIndex);
QModelIndex index = createIndex(clipIndex, 0, fromTrack);
QVector<int> roles;
roles << ResourceRole;
roles << ServiceRole;
roles << IsBlankRole;
roles << IsTransitionRole;
emit dataChanged(index, index, roles);
consolidateBlanks(playlist, fromTrack);
// Overwrite with clip
if (position + clip.get_playtime() >= 0)
overwrite(toTrack, clip, position, false /* seek */);
else
emit modified();
}
}
result = true;
}
return result;
}
int MultitrackModel::overwriteClip(int trackIndex, Mlt::Producer &clip, int position, bool seek)
{
createIfNeeded();
int result = -1;
int i = m_trackList.at(trackIndex).mlt_index;
QScopedPointer<Mlt::Producer> track(m_tractor->track(i));
if (track) {
Mlt::Playlist playlist(*track);
if (position >= playlist.get_playtime() - 1) {
// LOG_DEBUG() << __FUNCTION__ << "appending";
removeBlankPlaceholder(playlist, trackIndex);
int n = playlist.count();
int length = position - playlist.clip_start(n - 1) - playlist.clip_length(n - 1);
// Add blank to end if needed.
if (length > 0) {
beginInsertRows(index(trackIndex), n, n);
playlist.blank(length - 1);
endInsertRows();
++n;
}
// Append clip.
int in = clip.get_in();
int out = clip.get_out();
clip.set_in_and_out(0, clip.get_length() - 1);
beginInsertRows(index(trackIndex), n, n);
playlist.append(clip.parent(), in, out);
endInsertRows();
AudioLevelsTask::start(clip.parent(), this, createIndex(n, 0, trackIndex));
result = playlist.count() - 1;
} else if (position + clip.get_playtime() > playlist.get_playtime()
// Handle straddling - new clip larger than another with blanks on both sides.
|| playlist.get_clip_index_at(position) == playlist.get_clip_index_at(
position + clip.get_playtime() - 1)) {
// LOG_DEBUG() << __FUNCTION__ << "overwriting blank space" << clip.get_playtime();
int targetIndex = playlist.get_clip_index_at(position);
if (position > playlist.clip_start(targetIndex)) {
splitClip(trackIndex, targetIndex, position);
// Notify item on left was adjusted.
QModelIndex modelIndex = createIndex(targetIndex, 0, trackIndex);
QVector<int> roles;
roles << DurationRole;
emit dataChanged(modelIndex, modelIndex, roles);
AudioLevelsTask::start(clip.parent(), this, modelIndex);
++targetIndex;
} else if (position < 0) {
clip.set_in_and_out(-position, clip.get_out());
QModelIndex modelIndex = createIndex(targetIndex, 0, trackIndex);
// Notify clip on right was adjusted.
QVector<int> roles;
roles << InPointRole;
roles << DurationRole;
emit dataChanged(modelIndex, modelIndex, roles);
}
// Adjust clip on right.
int duration = playlist.clip_length(targetIndex) - clip.get_playtime();
if (duration > 0) {
// LOG_DEBUG() << "adjust item on right" << (targetIndex) << " to" << duration;
playlist.resize_clip(targetIndex, 0, duration - 1);
QModelIndex modelIndex = createIndex(targetIndex, 0, trackIndex);
// Notify clip on right was adjusted.
QVector<int> roles;
roles << DurationRole;
emit dataChanged(modelIndex, modelIndex, roles);
AudioLevelsTask::start(clip.parent(), this, modelIndex);
} else {
// LOG_DEBUG() << "remove item on right";
clearMixReferences(trackIndex, targetIndex);
beginRemoveRows(index(trackIndex), targetIndex, targetIndex);
playlist.remove(targetIndex);
endRemoveRows();
}
// Insert clip between subclips.
int in = clip.get_in();
int out = clip.get_out();
clip.set_in_and_out(0, clip.get_length() - 1);
beginInsertRows(index(trackIndex), targetIndex, targetIndex);
playlist.insert(clip.parent(), targetIndex, in, out);
endInsertRows();
result = targetIndex;
}
if (result >= 0) {
QModelIndex index = createIndex(result, 0, trackIndex);
AudioLevelsTask::start(clip.parent(), this, index);
emit modified();
if (seek)
emit seeked(playlist.clip_start(result) + playlist.clip_length(result));
}
}
return result;
}
QString MultitrackModel::overwrite(int trackIndex, Mlt::Producer &clip, int position, bool seek,
bool notify)
{
createIfNeeded();
Mlt::Playlist result(MLT.profile());
int i = m_trackList.at(trackIndex).mlt_index;
QScopedPointer<Mlt::Producer> track(m_tractor->track(i));
if (track) {
Mlt::Playlist playlist(*track);
removeBlankPlaceholder(playlist, trackIndex);
int targetIndex = playlist.get_clip_index_at(position);
if (position >= playlist.get_playtime() - 1) {
// LOG_DEBUG() << __FUNCTION__ << "appending";
int n = playlist.count();
int length = position - playlist.clip_start(n - 1) - playlist.clip_length(n - 1);
// Add blank to end if needed.
if (length > 0) {
beginInsertRows(index(trackIndex), n, n);
playlist.blank(length - 1);
endInsertRows();
++n;
}
// Append clip.
int in = clip.get_in();
int out = clip.get_out();
clip.set_in_and_out(0, clip.get_length() - 1);
beginInsertRows(index(trackIndex), n, n);
playlist.append(clip.parent(), in, out);
endInsertRows();
targetIndex = playlist.count() - 1;
} else {
int lastIndex = playlist.get_clip_index_at(position + clip.get_playtime());
// LOG_DEBUG() << __FUNCTION__ << "overwriting with duration" << clip.get_playtime()
// << "from" << targetIndex << "to" << lastIndex;
// Add affected clips to result playlist.
int i = targetIndex;
if (position == playlist.clip_start(targetIndex))
--i;
for (; i <= lastIndex; i++) {
Mlt::Producer *producer = playlist.get_clip(i);
if (producer)
result.append(*producer);
delete producer;
}
if (position > playlist.clip_start(targetIndex)) {
// LOG_DEBUG() << "split starting item" << targetIndex;
splitClip(trackIndex, targetIndex, position);
++targetIndex;
} else if (position < 0) {
clip.set_in_and_out(clip.get_in() - position, clip.get_out());
position = 0;
QModelIndex modelIndex = createIndex(targetIndex, 0, trackIndex);
// Notify clip was adjusted.
QVector<int> roles;
roles << InPointRole;
roles << DurationRole;
emit dataChanged(modelIndex, modelIndex, roles);
}
int length = clip.get_playtime();
while (length > 0 && targetIndex < playlist.count()) {
if (playlist.clip_length(targetIndex) > length) {
// LOG_DEBUG() << "split last item" << targetIndex;
splitClip(trackIndex, targetIndex, position + length);
}
// LOG_DEBUG() << "length" << length << "item length" << playlist.clip_length(targetIndex);
length -= playlist.clip_length(targetIndex);
// LOG_DEBUG() << "delete item" << targetIndex;
clearMixReferences(trackIndex, targetIndex);
beginRemoveRows(index(trackIndex), targetIndex, targetIndex);
playlist.remove(targetIndex);
endRemoveRows();
}
// Insert clip between subclips.
int in = clip.get_in();
int out = clip.get_out();
clip.set_in_and_out(0, clip.get_length() - 1);
beginInsertRows(index(trackIndex), targetIndex, targetIndex);
playlist.insert(clip.parent(), targetIndex, in, out);
endInsertRows();
}
QModelIndex index = createIndex(targetIndex, 0, trackIndex);
AudioLevelsTask::start(clip.parent(), this, index);
if (notify) {
emit overWritten(trackIndex, targetIndex);
emit modified();
emit seeked(playlist.clip_start(targetIndex) + playlist.clip_length(targetIndex), seek);
}
}
return MLT.XML(&result);
}
int MultitrackModel::insertClip(int trackIndex, Mlt::Producer &clip, int position,
bool rippleAllTracks, bool seek, bool notify)
{
createIfNeeded();
int result = -1;
int i = m_trackList.at(trackIndex).mlt_index;
int clipPlaytime = clip.get_playtime();
QScopedPointer<Mlt::Producer> track(m_tractor->track(i));
if (track) {
Mlt::Playlist playlist(*track);
if (position >= playlist.get_playtime() - 1) {
// LOG_DEBUG() << __FUNCTION__ << "appending";
removeBlankPlaceholder(playlist, trackIndex);
int n = playlist.count();
int length = position - playlist.clip_start(n - 1) - playlist.clip_length(n - 1);
// Add blank to end if needed.
if (length > 0) {
beginInsertRows(index(trackIndex), n, n);
playlist.blank(length - 1);
endInsertRows();
++n;
}
// Append clip.
int in = clip.get_in();
int out = clip.get_out();
clip.set_in_and_out(0, clip.get_length() - 1);
beginInsertRows(index(trackIndex), n, n);
playlist.append(clip.parent(), in, out);
endInsertRows();
result = playlist.count() - 1;
} else {
// LOG_DEBUG() << __FUNCTION__ << "inserting" << position << MLT.XML(&clip);
int targetIndex = playlist.get_clip_index_at(position);
if (position > playlist.clip_start(targetIndex)) {
splitClip(trackIndex, targetIndex, position);
// Notify item on left was adjusted.
QModelIndex modelIndex = createIndex(targetIndex, 0, trackIndex);
QVector<int> roles;
roles << DurationRole;
emit dataChanged(modelIndex, modelIndex, roles);
AudioLevelsTask::start(clip.parent(), this, modelIndex);
++targetIndex;
// Notify item on right was adjusted.
modelIndex = createIndex(targetIndex, 0, trackIndex);
emit dataChanged(modelIndex, modelIndex, roles);
AudioLevelsTask::start(clip.parent(), this, modelIndex);
} else if (position < 0) {
clip.set_in_and_out(clip.get_in() - position, clip.get_out());
position = 0;
QModelIndex modelIndex = createIndex(targetIndex, 0, trackIndex);
// Notify clip was adjusted.
QVector<int> roles;
roles << InPointRole;
roles << DurationRole;
emit dataChanged(modelIndex, modelIndex, roles);
}
// Insert clip between split blanks.
beginInsertRows(index(trackIndex), targetIndex, targetIndex);
if (qstrcmp("blank", clip.get("mlt_service"))) {
int in = clip.get_in();
int out = clip.get_out();
clip.set_in_and_out(0, clip.get_length() - 1);
playlist.insert(clip.parent(), targetIndex, in, out);
} else {
playlist.insert_blank(targetIndex, clipPlaytime - 1);
}
endInsertRows();
result = targetIndex;
}
if (result >= 0) {
if (rippleAllTracks) {
//fill in/expand blanks in all the other tracks
QList<int> tracksToInsertBlankInto;
for (int j = 0; j < m_trackList.count(); ++j) {
if (j == trackIndex)
continue;
int mltIndex = m_trackList.at(j).mlt_index;
QScopedPointer<Mlt::Producer> otherTrack(m_tractor->track(mltIndex));
if (otherTrack->get_int(kTrackLockProperty))
continue;
tracksToInsertBlankInto << j;
}
if (!tracksToInsertBlankInto.isEmpty())
insertOrAdjustBlankAt(tracksToInsertBlankInto, position, clipPlaytime);
}
QModelIndex index = createIndex(result, 0, trackIndex);
AudioLevelsTask::start(clip.parent(), this, index);
if (notify) {
emit inserted(trackIndex, result);
emit modified();
emit seeked(playlist.clip_start(result) + playlist.clip_length(result), seek);
}
}
}
return result;
}
int MultitrackModel::appendClip(int trackIndex, Mlt::Producer &clip, bool seek, bool notify)
{
if (!createIfNeeded()) {
return -1;
}
int i = m_trackList.at(trackIndex).mlt_index;
QScopedPointer<Mlt::Producer> track(m_tractor->track(i));
if (track) {
Mlt::Playlist playlist(*track);
qDebug() << playlist.count() << "Before blank remove";
removeBlankPlaceholder(playlist, trackIndex);
i = playlist.count();
int in = clip.get_in();
int out = clip.get_out();
qDebug() << playlist.count() << clip.get_length() - 1 << clip.is_blank();
clip.set_in_and_out(0, clip.get_length() - 1);
beginInsertRows(index(trackIndex), i, i);
playlist.append(clip.parent(), in, out);
endInsertRows();
QModelIndex index = createIndex(i, 0, trackIndex);
AudioLevelsTask::start(clip.parent(), this, index);
if (notify) {
emit appended(trackIndex, i);
emit modified();
emit seeked(playlist.clip_start(i) + playlist.clip_length(i), seek);
}
return i;
}
return -1;
}
void MultitrackModel::removeClip(int trackIndex, int clipIndex, bool rippleAllTracks)
{
if (trackIndex >= m_trackList.size()) {
return;
}
int i = m_trackList.at(trackIndex).mlt_index;
QScopedPointer<Mlt::Producer> track(m_tractor->track(i));
int clipPlaytime = -1;
int clipStart = -1;
if (track) {
Mlt::Playlist playlist(*track);
if (clipIndex < playlist.count()) {
// Shotcut does not like the behavior of remove() on a
// transition (MLT mix clip). So, we null mlt_mix to prevent it.
clearMixReferences(trackIndex, clipIndex);
QScopedPointer<Mlt::Producer> producer(playlist.get_clip(clipIndex));
if (producer) {
clipPlaytime = producer->get_playtime();
clipStart = playlist.clip_start(clipIndex);
}
emit removing(playlist.get_clip(clipIndex));
beginRemoveRows(index(trackIndex), clipIndex, clipIndex);
playlist.remove(clipIndex);
endRemoveRows();
consolidateBlanks(playlist, trackIndex);
// Ripple all unlocked tracks.
if (clipPlaytime > 0 && rippleAllTracks)
for (int j = 0; j < m_trackList.count(); ++j) {
if (j == trackIndex)
continue;
int mltIndex = m_trackList.at(j).mlt_index;
QScopedPointer<Mlt::Producer> otherTrack(m_tractor->track(mltIndex));
if (otherTrack) {
if (otherTrack->get_int(kTrackLockProperty))
continue;
removeRegion(j, clipStart, clipPlaytime);
}
}
consolidateBlanks(playlist, trackIndex);
emit modified();
}
}
}
void MultitrackModel::liftClip(int trackIndex, int clipIndex)
{
if (trackIndex >= m_trackList.size()) {
return;
}
int i = m_trackList.at(trackIndex).mlt_index;
QScopedPointer<Mlt::Producer> track(m_tractor->track(i));
if (track) {
Mlt::Playlist playlist(*track);
if (clipIndex < playlist.count()) {
// Shotcut does not like the behavior of replace_with_blank() on a
// transition (MLT mix clip). So, we null mlt_mix to prevent it.
clearMixReferences(trackIndex, clipIndex);
emit removing(playlist.get_clip(clipIndex));
delete playlist.replace_with_blank(clipIndex);
QModelIndex index = createIndex(clipIndex, 0, trackIndex);
QVector<int> roles;
roles << ResourceRole;
roles << ServiceRole;
roles << IsBlankRole;
roles << IsTransitionRole;
emit dataChanged(index, index, roles);
consolidateBlanks(playlist, trackIndex);
emit modified();
}
}
}
void MultitrackModel::splitClip(int trackIndex, int clipIndex, int position)
{
if (trackIndex < 0 || trackIndex >= rowCount()) {
LOG_ERROR() << "Invalid track index" << trackIndex;
}
int i = m_trackList.at(trackIndex).mlt_index;
QScopedPointer<Mlt::Producer> track(m_tractor->track(i));
if (track) {
Mlt::Playlist playlist(*track);
QScopedPointer<Mlt::ClipInfo> info(playlist.clip_info(clipIndex));
if (info.isNull()) {
LOG_ERROR() << "Invalid clip index" << trackIndex << clipIndex;
}
int in = info->frame_in;
int out = info->frame_out;
int filterIn = MLT.filterIn(playlist, clipIndex);
int filterOut = MLT.filterOut(playlist, clipIndex);
int duration = position - playlist.clip_start(clipIndex);
int delta = info->frame_count - duration;
if (playlist.is_blank(clipIndex)) {
beginInsertRows(index(trackIndex), clipIndex, clipIndex);
playlist.insert_blank(clipIndex, duration - 1);
endInsertRows();
} else {
// Make copy of clip.
Mlt::Producer producer(MLT.profile(), "xml-string",
MLT.XML(info->producer).toUtf8().constData());
// Connect a transition on the left to the new producer.
if (isTransition(playlist, clipIndex - 1) && !playlist.is_blank(clipIndex)) {
QScopedPointer<Mlt::Producer> p(playlist.get_clip(clipIndex - 1));
Mlt::Tractor tractor(p->parent());
if (tractor.is_valid()) {
QScopedPointer<Mlt::Producer> track_b(tractor.track(1));
track_b.reset(producer.cut(track_b->get_in(), track_b->get_out()));
tractor.set_track(*track_b, 1);
}
}
// Remove fades that are usually not desired after split.
QScopedPointer<Mlt::Filter> filter(getFilter("fadeOutVolume", &producer));
if (filter && filter->is_valid())
producer.detach(*filter);
filter.reset(getFilter("fadeOutBrightness", &producer));
if (filter && filter->is_valid())
producer.detach(*filter);
filter.reset(getFilter("fadeOutMovit", &producer));
if (filter && filter->is_valid())
producer.detach(*filter);
filter.reset(getFilter("fadeInVolume", info->producer));
if (filter && filter->is_valid())
info->producer->detach(*filter);
filter.reset(getFilter("fadeInBrightness", info->producer));
if (filter && filter->is_valid())
info->producer->detach(*filter);
filter.reset(getFilter("fadeInMovit", info->producer));
if (filter && filter->is_valid())
info->producer->detach(*filter);
beginInsertRows(index(trackIndex), clipIndex, clipIndex);
playlist.insert(producer, clipIndex, in, in + duration - 1);
endInsertRows();
QModelIndex modelIndex = createIndex(clipIndex, 0, trackIndex);
AudioLevelsTask::start(producer.parent(), this, modelIndex);
MLT.adjustClipFilters(producer, filterIn, out, 0, delta, 0);
}
playlist.resize_clip(clipIndex + 1, in + duration, out);
QModelIndex modelIndex = createIndex(clipIndex + 1, 0, trackIndex);
QVector<int> roles;
roles << DurationRole;
roles << InPointRole;
roles << FadeInRole;
emit dataChanged(modelIndex, modelIndex, roles);
if (!playlist.is_blank(clipIndex + 1)) {
AudioLevelsTask::start(*info->producer, this, modelIndex);
MLT.adjustClipFilters(*info->producer, in, filterOut, duration, 0, duration);
}
emit modified();
}
}
void MultitrackModel::joinClips(int trackIndex, int clipIndex)
{
if (clipIndex < 0) return;
int i = m_trackList.at(trackIndex).mlt_index;
QScopedPointer<Mlt::Producer> track(m_tractor->track(i));
if (track) {
Mlt::Playlist playlist(*track);
if (clipIndex >= playlist.count() - 1) return;
QScopedPointer<Mlt::ClipInfo> info(playlist.clip_info(clipIndex));
int in = info->frame_in;
int out = info->frame_out;
int delta = -playlist.clip_length(clipIndex + 1);
// Move a fade out on the right clip onto the left clip.
QScopedPointer<Mlt::Producer> clip(playlist.get_clip(clipIndex));
info.reset(playlist.clip_info(clipIndex + 1));
QScopedPointer<Mlt::Filter> filter(getFilter("fadeOutVolume", info->producer));
if (filter && filter->is_valid())
clip->parent().attach(*filter);
filter.reset(getFilter("fadeOutBrightness", info->producer));
if (filter && filter->is_valid())
clip->parent().attach(*filter);
filter.reset(getFilter("fadeOutMovit", info->producer));
if (filter && filter->is_valid())
clip->parent().attach(*filter);
playlist.resize_clip(clipIndex, in, out - delta);
QModelIndex modelIndex = createIndex(clipIndex, 0, trackIndex);
QVector<int> roles;
roles << DurationRole;
roles << OutPointRole;
roles << FadeOutRole;
emit dataChanged(modelIndex, modelIndex, roles);
AudioLevelsTask::start(clip->parent(), this, modelIndex);
clearMixReferences(trackIndex, clipIndex + 1);
emit removing(playlist.get_clip(clipIndex + 1));
beginRemoveRows(index(trackIndex), clipIndex + 1, clipIndex + 1);
playlist.remove(clipIndex + 1);
endRemoveRows();
MLT.adjustClipFilters(clip->parent(), in, out, 0, delta, 0);
emit modified();
}
}
static void moveBeforeFirstAudioFilter(Mlt::Producer *producer)
{
int n = producer->filter_count();
int index = 0;
for (; index < n; index++) {
QScopedPointer<Mlt::Filter> filter(producer->filter(index));
if (filter && filter->is_valid() && !filter->get_int("_loader")
&& !filter->get_int(kShotcutHiddenProperty)) {
QmlMetadata *meta = MAIN.filterController()->metadataForService(filter.data());
if (meta && meta->isAudio()) {
break;
}
}
}
producer->move_filter(n - 1, index);
}
void MultitrackModel::fadeIn(int trackIndex, int clipIndex, int duration)
{
int i = m_trackList.at(trackIndex).mlt_index;
QScopedPointer<Mlt::Producer> track(m_tractor->track(i));
if (track) {
Mlt::Playlist playlist(*track);
QScopedPointer<Mlt::ClipInfo> info(playlist.clip_info(clipIndex));
if (info && info->producer && info->producer->is_valid()) {
bool isChanged = false;
QScopedPointer<Mlt::Filter> filter;
duration = qBound(0, duration, info->frame_count);
if (m_trackList[trackIndex].type == VideoTrackType
// If video track index is not None.
&& (!info->producer->get("video_index") || info->producer->get_int("video_index") != -1)) {
// Get video filter.
if (Settings.playerGPU())
filter.reset(getFilter("fadeInMovit", info->producer));
else
filter.reset(getFilter("fadeInBrightness", info->producer));
if (duration > 0) {
// Add video filter if needed.
if (!filter) {
if (Settings.playerGPU()) {
Mlt::Filter f(MLT.profile(), "movit.opacity");
f.set(kShotcutFilterProperty, "fadeInMovit");
f.set("alpha", i == bottomVideoTrackMltIndex() ? 1 : -1);
info->producer->attach(f);
filter.reset(new Mlt::Filter(f));
} else {
Mlt::Filter f(MLT.profile(), "brightness");
f.set(kShotcutFilterProperty, "fadeInBrightness");
if (i == bottomVideoTrackMltIndex()) {
f.set("alpha", 1);
} else {
f.set("alpha", 0);
f.set("level", 1);
}
info->producer->attach(f);
filter.reset(new Mlt::Filter(f));
}
moveBeforeFirstAudioFilter(info->producer);
filter->set_in_and_out(info->frame_in, info->frame_out);
}
// Adjust video filter.
if (Settings.playerGPU()) {
// Special handling for animation keyframes on movit.opacity.
filter->clear("opacity");
#if LIBMLT_VERSION_INT >= ((7<<16)+(21<<8))
filter->anim_set("opacity", 0, 0, 0, mlt_keyframe_smooth_natural);
#else
filter->anim_set("opacity", 0, 0, 0, mlt_keyframe_smooth);
#endif
filter->anim_set("opacity", 1, duration - 1);
} else {
// Special handling for animation keyframes on brightness.
const char *key = filter->get_int("alpha") != 1 ? "alpha" : "level";
filter->clear(key);
filter->anim_set(key, 0, 0);
filter->anim_set(key, 1, duration - 1);
}
filter->set(kShotcutAnimInProperty, duration);
isChanged = true;
} else if (filter) {
// Remove the video filter.
info->producer->detach(*filter);
filterAddedOrRemoved(info->producer);
filter->set(kShotcutAnimInProperty, duration);
isChanged = true;
}
}
// If audio track index is not None.
if (!info->producer->get("audio_index") || info->producer->get_int("audio_index") != -1) {
// Get audio filter.
filter.reset(getFilter("fadeInVolume", info->producer));
if (duration > 0) {
// Add audio filter if needed.
if (!filter) {
Mlt::Filter f(MLT.profile(), "volume");
f.set(kShotcutFilterProperty, "fadeInVolume");
info->producer->attach(f);
filter.reset(new Mlt::Filter(f));
filter->set_in_and_out(info->frame_in, info->frame_out);
}
// Adjust audio filter.
filter->clear("level");
filter->anim_set("level", -60, 0);
filter->anim_set("level", 0, duration - 1);
filter->set(kShotcutAnimInProperty, duration);
isChanged = true;
} else if (filter) {
// Remove the audio filter.
info->producer->detach(*filter);
filterAddedOrRemoved(info->producer);
filter->set(kShotcutAnimInProperty, duration);
isChanged = true;
}
}
if (isChanged) {
// Signal change.
QModelIndex modelIndex = createIndex(clipIndex, 0, trackIndex);
QVector<int> roles;
roles << FadeInRole;
emit dataChanged(modelIndex, modelIndex, roles);
emit modified();
}
}
}
}
void MultitrackModel::fadeOut(int trackIndex, int clipIndex, int duration)
{
int i = m_trackList.at(trackIndex).mlt_index;
QScopedPointer<Mlt::Producer> track(m_tractor->track(i));
if (track) {
Mlt::Playlist playlist(*track);
QScopedPointer<Mlt::ClipInfo> info(playlist.clip_info(clipIndex));
if (info && info->producer && info->producer->is_valid()) {
QScopedPointer<Mlt::Filter> filter;
duration = qBound(0, duration, info->frame_count);
bool isChanged = false;
if (m_trackList[trackIndex].type == VideoTrackType
// If video track index is not None.
&& (!info->producer->get("video_index") || info->producer->get_int("video_index") != -1)) {
// Get video filter.
if (Settings.playerGPU())
filter.reset(getFilter("fadeOutMovit", info->producer));
else
filter.reset(getFilter("fadeOutBrightness", info->producer));
if (duration > 0) {
// Add video filter if needed.
if (!filter) {
if (Settings.playerGPU()) {
Mlt::Filter f(MLT.profile(), "movit.opacity");
f.set(kShotcutFilterProperty, "fadeOutMovit");
f.set("alpha", i == bottomVideoTrackMltIndex() ? 1 : -1);
info->producer->attach(f);
filter.reset(new Mlt::Filter(f));
} else {
Mlt::Filter f(MLT.profile(), "brightness");
f.set(kShotcutFilterProperty, "fadeOutBrightness");
if (i == bottomVideoTrackMltIndex()) {
f.set("alpha", 1);
} else {
f.set("alpha", 0);
f.set("level", 1);
}
info->producer->attach(f);
filter.reset(new Mlt::Filter(f));
}
moveBeforeFirstAudioFilter(info->producer);
filter->set_in_and_out(info->frame_in, info->frame_out);
}
// Adjust video filter.
if (Settings.playerGPU()) {
// Special handling for animation keyframes on movit.opacity.
filter->clear("opacity");
#if LIBMLT_VERSION_INT >= ((7<<16)+(21<<8))
filter->anim_set("opacity", 1, info->frame_count - duration, 0, mlt_keyframe_smooth_natural);
#else
filter->anim_set("opacity", 1, info->frame_count - duration, 0, mlt_keyframe_smooth);
#endif
filter->anim_set("opacity", 0, info->frame_count - 1);
} else {
// Special handling for animation keyframes on brightness.
const char *key = filter->get_int("alpha") != 1 ? "alpha" : "level";
filter->clear(key);
filter->anim_set(key, 1, info->frame_count - duration);
filter->anim_set(key, 0, info->frame_count - 1);
}
filter->set(kShotcutAnimOutProperty, duration);
isChanged = true;
} else if (filter) {
// Remove the video filter.
info->producer->detach(*filter);
filterAddedOrRemoved(info->producer);
filter->set(kShotcutAnimOutProperty, duration);
isChanged = true;
}
}
// If audio track index is not None.
if (!info->producer->get("audio_index") || info->producer->get_int("audio_index") != -1) {
// Get audio filter.
filter.reset(getFilter("fadeOutVolume", info->producer));
if (duration > 0) {
// Add audio filter if needed.
if (!filter) {
Mlt::Filter f(MLT.profile(), "volume");
f.set(kShotcutFilterProperty, "fadeOutVolume");
info->producer->attach(f);
filter.reset(new Mlt::Filter(f));
filter->set_in_and_out(info->frame_in, info->frame_out);
}
// Adjust audio filter.
filter->clear("level");
filter->anim_set("level", 0, info->frame_count - duration);
filter->anim_set("level", -60, info->frame_count - 1);
filter->set(kShotcutAnimOutProperty, duration);
isChanged = true;
} else if (filter) {
// Remove the audio filter.
info->producer->detach(*filter);
filterAddedOrRemoved(info->producer);
filter->set(kShotcutAnimOutProperty, duration);
isChanged = true;
}
}
if (isChanged) {
// Signal change.
QModelIndex modelIndex = createIndex(clipIndex, 0, trackIndex);
QVector<int> roles;
roles << FadeOutRole;
emit dataChanged(modelIndex, modelIndex, roles);
emit modified();
}
}
}
}
bool MultitrackModel::addTransitionValid(int fromTrack, int toTrack, int clipIndex, int position,
bool ripple)
{
bool result = false;
int i = m_trackList.at(toTrack).mlt_index;
QScopedPointer<Mlt::Producer> track(m_tractor->track(i));
if (track) {
Mlt::Playlist playlist(*track);
if (fromTrack == toTrack) {
int targetIndex = playlist.get_clip_index_at(position);
int previousIndex = clipIndex - 1 - (playlist.is_blank(clipIndex - 1) ? 1 : 0);
int nextIndex = clipIndex + 1 + (playlist.is_blank(clipIndex + 1) ? 1 : 0);
int endOfPreviousClip = playlist.clip_start(previousIndex) + playlist.clip_length(
previousIndex) - 1;
int endOfCurrentClip = position + playlist.clip_length(clipIndex) - 1;
int startOfNextClip = playlist.clip_start(nextIndex);
auto isBlankAtPosition = playlist.is_blank_at(position);
auto isTransitionAtPreviousIndex = isTransition(playlist, previousIndex);
auto isBlankAtEndOfCurrentClip = playlist.is_blank_at(endOfCurrentClip);
auto isTransitionAtNextIndex = isTransition(playlist, nextIndex);
if ((targetIndex < clipIndex && (endOfCurrentClip > endOfPreviousClip)
&& (position > playlist.clip_start(previousIndex)) && !isBlankAtPosition
&& !isTransitionAtPreviousIndex)
||
(!ripple && (targetIndex >= clipIndex) && (position < startOfNextClip)
&& !isBlankAtEndOfCurrentClip && !isTransitionAtNextIndex)) {
result = true;
}
}
}
return result;
}
int MultitrackModel::addTransition(int trackIndex, int clipIndex, int position, bool ripple,
bool rippleAllTracks)
{
int i = m_trackList.at(trackIndex).mlt_index;
QScopedPointer<Mlt::Producer> track(m_tractor->track(i));
if (track) {
Mlt::Playlist playlist(*track);
int targetIndex = playlist.get_clip_index_at(position);
int previousIndex = clipIndex - 1 - (playlist.is_blank(clipIndex - 1) ? 1 : 0);
int nextIndex = clipIndex + 1 + (playlist.is_blank(clipIndex + 1) ? 1 : 0);
int endOfPreviousClip = playlist.clip_start(previousIndex) + playlist.clip_length(
previousIndex) - 1;
int endOfCurrentClip = position + playlist.clip_length(clipIndex) - 1;
int startOfNextClip = playlist.clip_start(nextIndex);
if ((targetIndex < clipIndex && endOfCurrentClip > endOfPreviousClip) || // dragged left
(targetIndex >= clipIndex && position < startOfNextClip)) { // dragged right
int duration = qAbs(position - playlist.clip_start(clipIndex));
// Remove a blank duration from the transition duration.
if (playlist.is_blank(clipIndex - 1) && targetIndex < clipIndex)
duration -= playlist.clip_length(clipIndex - 1);
else if (playlist.is_blank(clipIndex + 1) && targetIndex >= clipIndex)
duration -= playlist.clip_length(clipIndex + 1);
// Adjust/insert blanks
moveClipInBlank(playlist, trackIndex, clipIndex, position, ripple, rippleAllTracks, duration);
targetIndex = playlist.get_clip_index_at(position);
// Create mix
beginInsertRows(index(trackIndex), targetIndex + 1, targetIndex + 1);
playlist.mix(targetIndex, duration);
Mlt::Producer producer(playlist.get_clip(targetIndex + 1));
if (producer.is_valid()) {
producer.parent().set(kShotcutTransitionProperty, kShotcutDefaultTransition);
}
endInsertRows();
// Add transitions
Mlt::Transition dissolve(MLT.profile(), Settings.playerGPU() ? "movit.luma_mix" : "luma");
Mlt::Transition crossFade(MLT.profile(), "mix:-1");
if (!Settings.playerGPU()) {
dissolve.set("alpha_over", 1);
dissolve.set("fix_background_alpha", 1);
}
playlist.mix_add(targetIndex + 1, &dissolve);
playlist.mix_add(targetIndex + 1, &crossFade);
// Notify ins and outs changed
QModelIndex modelIndex = createIndex(targetIndex, 0, trackIndex);
QVector<int> roles;
roles << StartRole;
roles << OutPointRole;
roles << DurationRole;
emit dataChanged(modelIndex, modelIndex, roles);
modelIndex = createIndex(targetIndex + 2, 0, trackIndex);
roles.clear();
roles << StartRole;
roles << InPointRole;
roles << DurationRole;
roles << AudioLevelsRole;
emit dataChanged(modelIndex, modelIndex, roles);
emit modified();
return targetIndex + 1;
}
}
return -1;
}
void MultitrackModel::clearMixReferences(int trackIndex, int clipIndex)
{
int i = m_trackList.at(trackIndex).mlt_index;
QScopedPointer<Mlt::Producer> track(m_tractor->track(i));
if (track) {
Mlt::Playlist playlist(*track);
QScopedPointer<Mlt::Producer> producer(playlist.get_clip(clipIndex - 1));
if (producer && producer->is_valid()) {
// Clear these since they are no longer valid.
producer->set("mix_in", NULL, 0);
producer->set("mix_out", NULL, 0);
producer.reset(playlist.get_clip(clipIndex));
if (producer && producer->is_valid()) {
producer->parent().set("mlt_mix", NULL, 0);
producer->set("mix_in", NULL, 0);
producer->set("mix_out", NULL, 0);
}
producer.reset(playlist.get_clip(clipIndex + 1));
if (producer && producer->is_valid()) {
producer->set("mix_in", NULL, 0);
producer->set("mix_out", NULL, 0);
}
}
}
}
void MultitrackModel::removeTransition(int trackIndex, int clipIndex)
{
int i = m_trackList.at(trackIndex).mlt_index;
QScopedPointer<Mlt::Producer> track(m_tractor->track(i));
if (track) {
Mlt::Playlist playlist(*track);
clearMixReferences(trackIndex, clipIndex);
emit removing(playlist.get_clip(clipIndex));
beginRemoveRows(index(trackIndex), clipIndex, clipIndex);
playlist.remove(clipIndex);
endRemoveRows();
--clipIndex;
QModelIndex modelIndex = createIndex(clipIndex, 0, trackIndex);
QVector<int> roles;
roles << OutPointRole;
roles << DurationRole;
emit dataChanged(modelIndex, modelIndex, roles);
modelIndex = createIndex(clipIndex + 1, 0, trackIndex);
roles << InPointRole;
roles << DurationRole;
emit dataChanged(modelIndex, modelIndex, roles);
emit modified();
}
}
void MultitrackModel::removeTransitionByTrimIn(int trackIndex, int clipIndex, int delta)
{
QModelIndex modelIndex = index(clipIndex, 0, index(trackIndex));
clearMixReferences(trackIndex, clipIndex);
int duration = -data(modelIndex, MultitrackModel::DurationRole).toInt();
liftClip(trackIndex, clipIndex);
trimClipOut(trackIndex, clipIndex - 1, duration, false, false);
notifyClipOut(trackIndex, clipIndex - 1);
if (delta) {
trimClipIn(trackIndex, clipIndex, delta, false, false);
notifyClipIn(trackIndex, clipIndex);
}
}
void MultitrackModel::removeTransitionByTrimOut(int trackIndex, int clipIndex, int delta)
{
QModelIndex modelIndex = index(clipIndex + 1, 0, index(trackIndex));
clearMixReferences(trackIndex, clipIndex);
int duration = -data(modelIndex, MultitrackModel::DurationRole).toInt();
liftClip(trackIndex, clipIndex + 1);
trimClipIn(trackIndex, clipIndex + 2, duration, false, false);
notifyClipIn(trackIndex, clipIndex + 1);
if (delta) {
trimClipOut(trackIndex, clipIndex, delta, false, false);
notifyClipOut(trackIndex, clipIndex);
}
}
bool MultitrackModel::trimTransitionInValid(int trackIndex, int clipIndex, int delta)
{
if (m_isMakingTransition) return false;
bool result = false;
int i = m_trackList.at(trackIndex).mlt_index;
QScopedPointer<Mlt::Producer> track(m_tractor->track(i));
if (track) {
Mlt::Playlist playlist(*track);
if (clipIndex + 2 < playlist.count()) {
Mlt::ClipInfo info;
// Check if there is already a transition and its new length valid.
if (isTransition(playlist, clipIndex + 1) && playlist.clip_length(clipIndex + 1) + delta > 0) {
// Check clip A out point.
playlist.clip_info(clipIndex, &info);
info.frame_out -= delta;
if (info.frame_out > info.frame_in && info.frame_out < info.length) {
// Check clip B in point.
playlist.clip_info(clipIndex + 2, &info);
info.frame_in -= playlist.clip_length(clipIndex + 1) + delta;
if (info.frame_in >= 0 && info.frame_in <= info.frame_out)
result = true;
}
}
}
}
return result;
}
void MultitrackModel::trimTransitionIn(int trackIndex, int clipIndex, int delta, bool slip)
{
// LOG_DEBUG() << "clipIndex" << clipIndex << "delta" << delta;
int i = m_trackList.at(trackIndex).mlt_index;
QScopedPointer<Mlt::Producer> track(m_tractor->track(i));
if (track) {
Mlt::Playlist playlist(*track);
// Adjust the playlist "mix" entry.
QScopedPointer<Mlt::Producer> producer(playlist.get_clip(clipIndex + 1));
Mlt::Tractor tractor(producer->parent());
if (!tractor.is_valid())
return;
QScopedPointer<Mlt::Producer> track_a(tractor.track(0));
QScopedPointer<Mlt::Producer> track_b(tractor.track(1));
int out = playlist.clip_length(clipIndex + 1) + delta - 1;
playlist.block();
track_a->set_in_and_out(track_a->get_in() - delta, track_a->get_out());
track_b->set_in_and_out(track_b->get_in() - delta, track_b->get_out());
playlist.unblock();
QScopedPointer<Mlt::Multitrack> multitrack(tractor.multitrack());
multitrack->set_in_and_out(0, out);
tractor.set_in_and_out(0, out);
producer->set("length", producer->frames_to_time(out + 1, mlt_time_clock));
producer->set_in_and_out(0, out);
// Adjust the transitions.
QScopedPointer<Mlt::Service> service(tractor.producer());
while (service && service->is_valid()) {
if (service->type() == mlt_service_transition_type) {
Mlt::Transition transition(*service);
transition.set_in_and_out(0, out);
}
service.reset(service->producer());
}
// Adjust clip entry being trimmed.
Mlt::ClipInfo info;
playlist.clip_info(clipIndex, &info);
playlist.resize_clip(clipIndex, info.frame_in - (slip ? delta : 0), info.frame_out - delta);
if (slip)
MLT.adjustClipFilters(*info.producer, info.frame_in, info.frame_out, -delta, 0, 0);
// Adjust filters.
playlist.clip_info(clipIndex + 2, &info);
MLT.adjustClipFilters(*info.producer, info.frame_in, info.frame_out, -(out + 1), 0, -delta);
QVector<int> roles;
roles << InPointRole;
roles << OutPointRole;
roles << DurationRole;
emit dataChanged(createIndex(clipIndex, 0, trackIndex),
createIndex(clipIndex + 1, 0, trackIndex), roles);
emit modified();
}
}
bool MultitrackModel::trimTransitionOutValid(int trackIndex, int clipIndex, int delta)
{
if (m_isMakingTransition) return false;
bool result = false;
int i = m_trackList.at(trackIndex).mlt_index;
QScopedPointer<Mlt::Producer> track(m_tractor->track(i));
if (track) {
Mlt::Playlist playlist(*track);
if (clipIndex > 1) {
Mlt::ClipInfo info;
// Check if there is already a transition.
if (isTransition(playlist, clipIndex - 1)) {
// Check clip A out point.
playlist.clip_info(clipIndex - 2, &info);
info.frame_out += playlist.clip_length(clipIndex - 1) + delta;
if (info.frame_out > info.frame_in && info.frame_out < info.length) {
// Check clip B in point.
playlist.clip_info(clipIndex, &info);
info.frame_in += delta;
if (info.frame_in >= 0 && info.frame_in <= info.frame_out)
result = true;
}
}
}
}
return result;
}
void MultitrackModel::trimTransitionOut(int trackIndex, int clipIndex, int delta, bool slip)
{
// LOG_DEBUG() << "clipIndex" << clipIndex << "delta" << delta;
int i = m_trackList.at(trackIndex).mlt_index;
QScopedPointer<Mlt::Producer> track(m_tractor->track(i));
if (track) {
Mlt::Playlist playlist(*track);
// Adjust the playlist "mix" entry.
QScopedPointer<Mlt::Producer> producer(playlist.get_clip(clipIndex - 1));
Mlt::Tractor tractor(producer->parent());
if (!tractor.is_valid())
return;
QScopedPointer<Mlt::Producer> track_a(tractor.track(0));
QScopedPointer<Mlt::Producer> track_b(tractor.track(1));
int out = playlist.clip_length(clipIndex - 1) + delta - 1;
playlist.block();
track_a->set_in_and_out(track_a->get_in(), track_a->get_out() + delta);
track_b->set_in_and_out(track_b->get_in(), track_b->get_out() + delta);
playlist.unblock();
QScopedPointer<Mlt::Multitrack> multitrack(tractor.multitrack());
multitrack->set_in_and_out(0, out);
tractor.set_in_and_out(0, out);
producer->set("length", producer->frames_to_time(out + 1, mlt_time_clock));
producer->set_in_and_out(0, out);
// Adjust the transitions.
QScopedPointer<Mlt::Service> service(tractor.producer());
while (service && service->is_valid()) {
if (service->type() == mlt_service_transition_type) {
Mlt::Transition transition(*service);
transition.set_in_and_out(0, out);
}
service.reset(service->producer());
}
// Adjust clip entry being trimmed.
Mlt::ClipInfo info;
playlist.clip_info(clipIndex, &info);
playlist.resize_clip(clipIndex, info.frame_in + delta, info.frame_out + (slip ? delta : 0));
if (slip)
MLT.adjustClipFilters(*info.producer, info.frame_in, info.frame_out, 0, -delta, 0);
// Adjust filters.
playlist.clip_info(clipIndex - 2, &info);
MLT.adjustClipFilters(*info.producer, info.frame_in, info.frame_out, 0, -(out + 1), 0);
QVector<int> roles;
roles << OutPointRole;
roles << DurationRole;
emit dataChanged(createIndex(clipIndex - 1, 0, trackIndex),
createIndex(clipIndex - 1, 0, trackIndex), roles);
roles.clear();
roles << InPointRole;
roles << OutPointRole;
roles << DurationRole;
emit dataChanged(createIndex(clipIndex, 0, trackIndex),
createIndex(clipIndex, 0, trackIndex), roles);
emit modified();
}
}
bool MultitrackModel::addTransitionByTrimInValid(int trackIndex, int clipIndex, int delta)
{
Q_UNUSED(delta)
bool result = false;
int i = m_trackList.at(trackIndex).mlt_index;
QScopedPointer<Mlt::Producer> track(m_tractor->track(i));
if (track) {
Mlt::Playlist playlist(*track);
if (clipIndex > 0) {
// Check if preceding clip is not blank, not already a transition,
// and there is enough frames before in point of current clip.
if (!m_isMakingTransition && delta < 0 && !playlist.is_blank(clipIndex - 1)
&& !isTransition(playlist, clipIndex - 1)) {
Mlt::ClipInfo info;
playlist.clip_info(clipIndex, &info);
if (info.frame_in >= -delta)
result = true;
} else if (m_isMakingTransition && isTransition(playlist, clipIndex - 1)) {
// Invalid if transition length will be 0 or less.
auto newTransitionDuration = playlist.clip_length(clipIndex - 1) - delta;
result = newTransitionDuration > 0;
if (result && clipIndex > 1) {
QScopedPointer<Mlt::ClipInfo> info(playlist.clip_info(clipIndex));
// Invalid if left clip length will be 0 or less.
result = playlist.clip_length(clipIndex - 2) + delta > 0 &&
// Invalid if current clip in point will be less than 0.
info && info->frame_in - newTransitionDuration >= 0;
}
} else {
result = m_isMakingTransition;
}
}
}
return result;
}
int MultitrackModel::addTransitionByTrimIn(int trackIndex, int clipIndex, int delta)
{
int i = m_trackList.at(trackIndex).mlt_index;
QScopedPointer<Mlt::Producer> track(m_tractor->track(i));
if (track) {
Mlt::Playlist playlist(*track);
// Create transition if it does not yet exist.
if (!isTransition(playlist, clipIndex - 1)) {
// Adjust filters.
Mlt::ClipInfo info;
playlist.clip_info(clipIndex, &info);
MLT.adjustClipFilters(*info.producer, info.frame_in, info.frame_out, delta, 0, 0);
// Insert the mix clip.
beginInsertRows(index(trackIndex), clipIndex, clipIndex);
playlist.mix_out(clipIndex - 1, -delta);
QScopedPointer<Mlt::Producer> producer(playlist.get_clip(clipIndex));
producer->parent().set(kShotcutTransitionProperty, kShotcutDefaultTransition);
endInsertRows();
// Add transitions.
Mlt::Transition dissolve(MLT.profile(), Settings.playerGPU() ? "movit.luma_mix" : "luma");
Mlt::Transition crossFade(MLT.profile(), "mix:-1");
if (!Settings.playerGPU()) {
dissolve.set("alpha_over", 1);
dissolve.set("fix_background_alpha", 1);
}
playlist.mix_add(clipIndex, &dissolve);
playlist.mix_add(clipIndex, &crossFade);
// Notify clip A changed.
QModelIndex modelIndex = createIndex(clipIndex - 1, 0, trackIndex);
QVector<int> roles;
roles << OutPointRole;
roles << DurationRole;
emit dataChanged(modelIndex, modelIndex, roles);
emit modified();
m_isMakingTransition = true;
clipIndex += 1;
} else if (m_isMakingTransition) {
// Adjust a transition addition already in progress.
// m_isMakingTransition will be set false when mouse button released via notifyClipOut().
trimTransitionIn(trackIndex, clipIndex - 2, -delta);
}
}
return clipIndex;
}
bool MultitrackModel::addTransitionByTrimOutValid(int trackIndex, int clipIndex, int delta)
{
Q_UNUSED(delta)
bool result = false;
int i = m_trackList.at(trackIndex).mlt_index;
QScopedPointer<Mlt::Producer> track(m_tractor->track(i));
if (track) {
Mlt::Playlist playlist(*track);
if (clipIndex + 1 < playlist.count()) {
// Check if following clip is not blank, not already a transition,
// and there is enough frames after out point of current clip.
if (!m_isMakingTransition && delta < 0 && !playlist.is_blank(clipIndex + 1)
&& !isTransition(playlist, clipIndex + 1)) {
Mlt::ClipInfo info;
playlist.clip_info(clipIndex, &info);
// LOG_DEBUG() << "(info.length" << info.length << " - info.frame_out" << info.frame_out << ") =" << (info.length - info.frame_out) << " >= -delta" << -delta;
if ((info.length - info.frame_out) >= -delta)
result = true;
} else if (m_isMakingTransition && isTransition(playlist, clipIndex + 1)) {
// Invalid if transition length will be 0 or less.
auto newTransitionDuration = playlist.clip_length(clipIndex + 1) - delta;
// LOG_DEBUG() << "playlist.clip_length(clipIndex + 1)" << playlist.clip_length(clipIndex + 1) << "- delta" << delta << "=" << (playlist.clip_length(clipIndex + 1) - delta);
result = newTransitionDuration > 0;
if (result && clipIndex + 2 < playlist.count()) {
QScopedPointer<Mlt::ClipInfo> info(playlist.clip_info(clipIndex));
// Invalid if right clip length will be 0 or less.
result = playlist.clip_length(clipIndex + 2) + delta > 0 &&
// Invalid if current clip out point would exceed its duration.
info && info->frame_out + newTransitionDuration < info->length;
}
} else {
result = m_isMakingTransition;
}
}
}
return result;
}
void MultitrackModel::addTransitionByTrimOut(int trackIndex, int clipIndex, int delta)
{
int i = m_trackList.at(trackIndex).mlt_index;
QScopedPointer<Mlt::Producer> track(m_tractor->track(i));
if (track) {
Mlt::Playlist playlist(*track);
// Create transition if it does not yet exist.
if (!isTransition(playlist, clipIndex + 1)) {
// Adjust filters.
Mlt::ClipInfo info;
playlist.clip_info(clipIndex, &info);
MLT.adjustClipFilters(*info.producer, info.frame_in, info.frame_out, 0, delta, 0);
// Insert the mix clip.
beginInsertRows(index(trackIndex), clipIndex + 1, clipIndex + 1);
playlist.mix_in(clipIndex, -delta);
QScopedPointer<Mlt::Producer> producer(playlist.get_clip(clipIndex + 1));
producer->parent().set(kShotcutTransitionProperty, kShotcutDefaultTransition);
endInsertRows();
// Add transitions.
Mlt::Transition dissolve(MLT.profile(), Settings.playerGPU() ? "movit.luma_mix" : "luma");
Mlt::Transition crossFade(MLT.profile(), "mix:-1");
if (!Settings.playerGPU()) {
dissolve.set("alpha_over", 1);
dissolve.set("fix_background_alpha", 1);
}
playlist.mix_add(clipIndex + 1, &dissolve);
playlist.mix_add(clipIndex + 1, &crossFade);
// Notify clip B changed.
QModelIndex modelIndex = createIndex(clipIndex + 2, 0, trackIndex);
QVector<int> roles;
roles << InPointRole;
roles << DurationRole;
emit dataChanged(modelIndex, modelIndex, roles);
emit modified();
m_isMakingTransition = true;
} else if (m_isMakingTransition) {
// Adjust a transition addition already in progress.
// m_isMakingTransition will be set false when mouse button released via notifyClipIn().
delta = playlist.clip_start(clipIndex + 1) - (playlist.clip_start(clipIndex) + playlist.clip_length(
clipIndex) + delta);
trimTransitionOut(trackIndex, clipIndex + 2, delta);
}
}
}
bool MultitrackModel::removeTransitionByTrimInValid(int trackIndex, int clipIndex, int delta)
{
bool result = false;
int i = m_trackList.at(trackIndex).mlt_index;
QScopedPointer<Mlt::Producer> track(m_tractor->track(i));
if (track) {
Mlt::Playlist playlist(*track);
if (clipIndex > 1) {
// Check if there is a transition and its new length is 0 or less.
if (isTransition(playlist, clipIndex - 1)
&& playlist.clip_length(clipIndex - 1) - qAbs(delta) <= 0
&& ((delta < 0 && !m_isMakingTransition) || (delta > 0 && m_isMakingTransition))) {
result = true;
m_isMakingTransition = false;
}
}
}
return result;
}
bool MultitrackModel::removeTransitionByTrimOutValid(int trackIndex, int clipIndex, int delta)
{
bool result = false;
int i = m_trackList.at(trackIndex).mlt_index;
QScopedPointer<Mlt::Producer> track(m_tractor->track(i));
if (track) {
Mlt::Playlist playlist(*track);
if (clipIndex + 2 < playlist.count()) {
// Check if there is a transition and its new length is 0 or less.
// LOG_DEBUG() << "transition length" << playlist.clip_length(clipIndex + 1) << "delta" << delta << playlist.clip_length(clipIndex + 1) - qAbs(delta);
if (isTransition(playlist, clipIndex + 1)
&& playlist.clip_length(clipIndex + 1) - qAbs(delta) <= 0
&& ((delta < 0 && !m_isMakingTransition) || (delta > 0 && m_isMakingTransition))) {
result = true;
m_isMakingTransition = false;
}
}
}
return result;
}
void MultitrackModel::filterAddedOrRemoved(Mlt::Producer *producer)
{
if (!m_tractor || !producer || !producer->is_valid())
return;
mlt_service service = producer->get_service();
// Check if it was on the multitrack tractor.
if (service == m_tractor->get_service())
emit filteredChanged();
else if (producer->get(kMultitrackItemProperty)) {
// Check if it was a clip.
QString s = QString::fromLatin1(producer->get(kMultitrackItemProperty));
auto parts = s.split(':');
if (parts.length() == 2) {
QModelIndex modelIndex = createIndex(parts[0].toInt(), 0, parts[1].toInt());
QVector<int> roles;
roles << FadeInRole;
roles << FadeOutRole;
emit dataChanged(modelIndex, modelIndex, roles);
}
} else for (int i = 0; i < m_trackList.size(); i++) {
// Check if it was on one of the tracks.
QScopedPointer<Mlt::Producer> track(m_tractor->track(m_trackList[i].mlt_index));
if (service == track.data()->get_service()) {
QModelIndex modelIndex = index(i, 0);
QVector<int> roles;
roles << IsFilteredRole;
emit dataChanged(modelIndex, modelIndex, roles);
break;
}
}
}
void MultitrackModel::onFilterChanged(Mlt::Service *filter)
{
if (filter && filter->is_valid()) {
Mlt::Service service(mlt_service(filter->get_data("service")));
if (service.is_valid() && service.get(kMultitrackItemProperty)) {
QString s = QString::fromLatin1(service.get(kMultitrackItemProperty));
auto parts = s.split(':');
if (parts.length() == 2) {
QModelIndex modelIndex = createIndex(parts[0].toInt(), 0, parts[1].toInt());
QVector<int> roles;
const char *name = filter->get(kShotcutFilterProperty);
if (!qstrcmp("fadeInMovit", name) ||
!qstrcmp("fadeInBrightness", name) ||
!qstrcmp("fadeInVolume", name))
roles << FadeInRole;
if (!qstrcmp("fadeOutMovit", name) ||
!qstrcmp("fadeOutBrightness", name) ||
!qstrcmp("fadeOutVolume", name))
roles << FadeOutRole;
if (roles.length())
emit dataChanged(modelIndex, modelIndex, roles);
}
}
}
}
void MultitrackModel::moveClipToEnd(Mlt::Playlist &playlist, int trackIndex, int clipIndex,
int position, bool ripple, bool rippleAllTracks)
{
int n = playlist.count();
int length = position - playlist.clip_start(n - 1) - playlist.clip_length(n - 1);
int clipPlaytime = playlist.clip_length(clipIndex);
int clipStart = playlist.clip_start(clipIndex);
if (!ripple) {
if (clipIndex > 0 && playlist.is_blank(clipIndex - 1)) {
// If there was a blank on the left adjust it.
int duration = playlist.clip_length(clipIndex - 1) + playlist.clip_length(clipIndex);
// LOG_DEBUG() << "adjust blank on left to" << duration;
playlist.resize_clip(clipIndex - 1, 0, duration - 1);
QModelIndex index = createIndex(clipIndex - 1, 0, trackIndex);
QVector<int> roles;
roles << DurationRole;
emit dataChanged(index, index, roles);
} else if ((clipIndex + 1) < n && playlist.is_blank(clipIndex + 1)) {
// If there was a blank on the right adjust it.
int duration = playlist.clip_length(clipIndex + 1) + playlist.clip_length(clipIndex);
// LOG_DEBUG() << "adjust blank on right to" << duration;
playlist.resize_clip(clipIndex + 1, 0, duration - 1);
QModelIndex index = createIndex(clipIndex + 1, 0, trackIndex);
QVector<int> roles;
roles << DurationRole;
emit dataChanged(index, index, roles);
} else {
// Add new blank
beginInsertRows(index(trackIndex), clipIndex, clipIndex);
playlist.insert_blank(clipIndex, playlist.clip_length(clipIndex) - 1);
endInsertRows();
++clipIndex;
++n;
}
}
// Add blank to end if needed.
if (length > 0) {
beginInsertRows(index(trackIndex), n, n);
playlist.blank(length - 1);
endInsertRows();
}
// Finally, move clip into place.
QModelIndex parentIndex = index(trackIndex);
if (playlist.count() < clipIndex || playlist.count() > clipIndex + 1) {
beginMoveRows(parentIndex, clipIndex, clipIndex, parentIndex, playlist.count());
playlist.move(clipIndex, playlist.count());
endMoveRows();
consolidateBlanks(playlist, trackIndex);
}
// Ripple all unlocked tracks.
if (clipPlaytime > 0 && ripple && rippleAllTracks)
for (int j = 0; j < m_trackList.count(); ++j) {
if (j == trackIndex)
continue;
int mltIndex = m_trackList.at(j).mlt_index;
QScopedPointer<Mlt::Producer> otherTrack(m_tractor->track(mltIndex));
if (otherTrack) {
if (otherTrack->get_int(kTrackLockProperty))
continue;
removeRegion(j, clipStart, clipPlaytime);
}
}
}
void MultitrackModel::moveClipInBlank(Mlt::Playlist &playlist, int trackIndex, int clipIndex,
int position, bool ripple, bool rippleAllTracks, int duration)
{
int clipPlaytime = duration ? duration : playlist.clip_length(clipIndex);
int clipStart = playlist.clip_start(clipIndex);
int delta = position - clipStart;
if (clipIndex > 0 && playlist.is_blank(clipIndex - 1)) {
// Adjust blank on left.
int duration = playlist.clip_length(clipIndex - 1) + delta;
if (duration > 0) {
// LOG_DEBUG() << "adjust blank on left" << (clipIndex - 1) << "to" << duration;
playlist.resize_clip(clipIndex - 1, 0, duration - 1);
QModelIndex index = createIndex(clipIndex - 1, 0, trackIndex);
QVector<int> roles;
roles << DurationRole;
emit dataChanged(index, index, roles);
} else {
// LOG_DEBUG() << "remove blank on left";
int i = clipIndex - 1;
beginRemoveRows(index(trackIndex), i, i);
playlist.remove(i);
endRemoveRows();
consolidateBlanks(playlist, trackIndex);
--clipIndex;
}
} else if (delta > 0) {
// LOG_DEBUG() << "add blank on left with duration" << delta;
// Add blank to left.
int i = qMax(clipIndex, 0);
beginInsertRows(index(trackIndex), i, i);
playlist.insert_blank(i, delta - 1);
endInsertRows();
++clipIndex;
}
if (!ripple && (clipIndex + 1) < playlist.count() && playlist.is_blank(clipIndex + 1)) {
// Adjust blank to right.
int duration = playlist.clip_length(clipIndex + 1) - delta;
if (duration > 0) {
// LOG_DEBUG() << "adjust blank on right" << (clipIndex + 1) << "to" << duration;
playlist.resize_clip(clipIndex + 1, 0, duration - 1);
QModelIndex index = createIndex(clipIndex + 1, 0, trackIndex);
QVector<int> roles;
roles << DurationRole;
emit dataChanged(index, index, roles);
} else {
// LOG_DEBUG() << "remove blank on right";
int i = clipIndex + 1;
beginRemoveRows(index(trackIndex), i, i);
playlist.remove(i);
endRemoveRows();
consolidateBlanks(playlist, trackIndex);
}
} else if (!ripple && delta < 0 && (clipIndex + 1) < playlist.count()) {
// Add blank to right.
// LOG_DEBUG() << "add blank on right with duration" << -delta;
beginInsertRows(index(trackIndex), clipIndex + 1, clipIndex + 1);
playlist.insert_blank(clipIndex + 1, (-delta - 1));
endInsertRows();
}
// Ripple all unlocked tracks.
if (clipPlaytime > 0 && ripple && rippleAllTracks) {
QList<int> otherTracksToRipple;
for (int i = 0; i < m_trackList.count(); ++i) {
if (i == trackIndex)
continue;
int mltIndex = m_trackList.at(i).mlt_index;
QScopedPointer<Mlt::Producer> otherTrack(m_tractor->track(mltIndex));
if (otherTrack && otherTrack->get_int(kTrackLockProperty))
continue;
otherTracksToRipple << i;
}
if (position < clipStart) {
foreach (int idx, otherTracksToRipple)
removeRegion(idx, position, clipStart - position);
} else {
insertOrAdjustBlankAt(otherTracksToRipple, clipStart, position - clipStart);
consolidateBlanks(playlist, trackIndex);
}
}
}
void MultitrackModel::consolidateBlanks(Mlt::Playlist &playlist, int trackIndex)
{
for (int i = 1; i < playlist.count(); i++) {
if (playlist.is_blank(i - 1) && playlist.is_blank(i)) {
int out = playlist.clip_length(i - 1) + playlist.clip_length(i) - 1;
playlist.resize_clip(i - 1, 0, out);
QModelIndex idx = createIndex(i - 1, 0, trackIndex);
QVector<int> roles;
roles << DurationRole;
emit dataChanged(idx, idx, roles);
beginRemoveRows(index(trackIndex), i, i);
playlist.remove(i--);
endRemoveRows();
}
}
if (playlist.count() > 0) {
int i = playlist.count() - 1;
if (playlist.is_blank(i)) {
beginRemoveRows(index(trackIndex), i, i);
playlist.remove(i);
endRemoveRows();
}
}
if (playlist.count() == 0) {
beginInsertRows(index(trackIndex), 0, 0);
playlist.blank(0);
endInsertRows();
}
}
void MultitrackModel::consolidateBlanksAllTracks()
{
if (!m_tractor) return;
int i = 0;
foreach (Track t, m_trackList) {
std::unique_ptr<Mlt::Producer> track(m_tractor->track(t.mlt_index));
if (track && track->is_valid()) {
Mlt::Playlist playlist(*track);
consolidateBlanks(playlist, i);
}
++i;
}
}
void MultitrackModel::audioLevelsReady(const QPersistentModelIndex &index)
{
QVector<int> roles;
roles << AudioLevelsRole;
emit dataChanged(index, index, roles);
}
bool MultitrackModel::createIfNeeded()
{
if (!m_tractor) {
m_tractor = new Mlt::Tractor(MLT.profile());
MLT.profile().set_explicit(true);
m_tractor->set(kShotcutXmlProperty, 1);
retainPlaylist();
addBackgroundTrack();
addVideoTrack();
emit created();
} else if (!m_trackList.count()) {
addVideoTrack();
}
return true;
}
void MultitrackModel::addBackgroundTrack()
{
Mlt::Playlist playlist(MLT.profile());
playlist.set("id", kBackgroundTrackId);
Mlt::Producer producer(MLT.profile(), "color:0");
producer.set("mlt_image_format", "rgba");
producer.set("length", 1);
producer.set("id", "black");
// Allow mixing against frames produced by this producer.
producer.set("set.test_audio", 0);
playlist.append(producer);
m_tractor->set_track(playlist, m_tractor->count());
}
void MultitrackModel::adjustBackgroundDuration()
{
if (!m_tractor) return;
int duration = getDuration();
std::unique_ptr<Mlt::Producer> track(m_tractor->track(0));
if (track && track->is_valid()) {
Mlt::Playlist playlist(*track);
std::unique_ptr<Mlt::Producer> clip(playlist.get_clip(0));
if (clip && clip->is_valid()) {
if (duration != clip->parent().get_length()) {
clip->parent().set("length", clip->parent().frames_to_time(duration, mlt_time_clock));
clip->parent().set_in_and_out(0, duration - 1);
clip->set("length", clip->parent().frames_to_time(duration, mlt_time_clock));
clip->set_in_and_out(0, duration - 1);
playlist.resize_clip(0, 0, duration - 1);
emit durationChanged();
}
}
}
}
void MultitrackModel::adjustServiceFilterDurations(Mlt::Service &service, int duration)
{
// Use kFilterOutProperty to track duration changes
if (service.get(kFilterOutProperty)) {
int oldOut = service.get_int(kFilterOutProperty);
int n = service.filter_count();
for (int i = 0; i < n; i++) {
QScopedPointer<Mlt::Filter> filter(service.filter(i));
if (filter && filter->is_valid() && !filter->get_int("_loader")
&& !filter->get_int(kShotcutHiddenProperty)) {
int in = filter->get_in();
int out = filter->get_out();
// Only change out if it is pinned (same as old track duration)
if (out == oldOut || in < 0) {
out = duration - 1;
filter->set_in_and_out(qMax(in, 0), out);
}
}
}
}
service.set(kFilterOutProperty, duration - 1);
}
bool MultitrackModel::warnIfInvalid(Mlt::Service &service)
{
if (!service.is_valid()) {
const char *plugin = Settings.playerGPU() ? "Movit overlay" : "frei0r cairoblend";
const char *plugins = Settings.playerGPU() ? "Movit" : "frei0r";
LongUiTask::cancel();
QMessageBox::critical(&MAIN, qApp->applicationName(),
tr("Error: Shotcut could not find the %1 plugin on your system.\n\n"
"Please install the %2 plugins.").arg(plugin).arg(plugins));
return true;
}
return false;
}
Mlt::Transition *MultitrackModel::getVideoBlendTransition(int trackIndex) const
{
auto transition = getTransition("frei0r.cairoblend", trackIndex);
if (!transition)
transition = getTransition("movit.overlay", trackIndex);
if (!transition)
transition = getTransition("qtblend", trackIndex);
return transition;
}
int MultitrackModel::bottomVideoTrackMltIndex() const
{
return mltIndexForTrack(bottomVideoTrackIndex());
}
bool MultitrackModel::hasEmptyTrack(TrackType trackType) const
{
bool isEmpty = false;
for (auto a : m_trackList) {
if (a.type == trackType) {
QScopedPointer<Mlt::Producer> producer(m_tractor->track(a.mlt_index));
if (producer) {
Mlt::Playlist track(*producer);
if (track.count() == 1 && track.is_blank(0)) {
isEmpty = true;
break;
}
}
}
}
return isEmpty;
}
void MultitrackModel::refreshVideoBlendTransitions()
{
int a_track = bottomVideoTrackMltIndex();
// For each video track
for (auto &t : m_trackList) {
if (t.type == VideoTrackType) {
QScopedPointer<Mlt::Transition> transition(getVideoBlendTransition(t.mlt_index));
if (transition && transition->is_valid()) {
// Normalize its video blending transition
if (transition->get_a_track() != 0) {
transition->set("a_track", a_track);
}
if (t.number) {
transition->clear("disable");
} else {
transition->set("disable", 1);
}
}
}
}
}
int MultitrackModel::bottomVideoTrackIndex() const
{
int track = -1;
for (int i = 0; i < m_trackList.size(); ++i) {
if (m_trackList[i].type == VideoTrackType) {
track = i;
}
}
return track;
}
int MultitrackModel::mltIndexForTrack(int trackIndex) const
{
int i = -1;
if (trackIndex >= 0 && trackIndex < m_trackList.size()) {
i = m_trackList[trackIndex].mlt_index;
}
return i;
}
bool MultitrackModel::checkForEmptyTracks(int trackIndex)
{
auto trackType = m_trackList.at(trackIndex).type;
if (!hasEmptyTrack(trackType)) {
emit noMoreEmptyTracks(AudioTrackType == trackType);
return true;
}
return false;
}
void MultitrackModel::adjustTrackFilters()
{
if (!m_tractor) return;
int duration = getDuration();
// Adjust filters on the tractor.
adjustServiceFilterDurations(*m_tractor, duration);
// Adjust filters on the tracks.
foreach (Track t, m_trackList) {
QScopedPointer<Mlt::Producer> track(m_tractor->track(t.mlt_index));
if (track && track->is_valid())
adjustServiceFilterDurations(*track, duration);
}
}
std::unique_ptr<Mlt::ClipInfo> MultitrackModel::findClipByUuid(const QUuid &uuid, int &trackIndex,
int &clipIndex)
{
if (uuid.isNull()) {
LOG_ERROR() << "Request to find clip without UUID";
#ifndef NDEBUG
Q_ASSERT(!uuid.isNull());
#endif
return nullptr;
}
for (trackIndex = 0; trackIndex < trackList().size(); trackIndex++) {
int i = trackList().at(trackIndex).mlt_index;
QScopedPointer<Mlt::Producer> track(tractor()->track(i));
if (track) {
Mlt::Playlist playlist(*track);
for (clipIndex = 0; clipIndex < playlist.count(); clipIndex++) {
Mlt::ClipInfo *info;
if ((info = playlist.clip_info(clipIndex))) {
if (MLT.uuid(*info->producer) == uuid || MLT.uuid(*info->cut) == uuid)
return std::unique_ptr<Mlt::ClipInfo>(info);
else
delete info;
}
}
}
}
return nullptr;
}
std::unique_ptr<Mlt::ClipInfo> MultitrackModel::getClipInfo(int trackIndex, int clipIndex)
{
Mlt::ClipInfo *result = nullptr;
if (clipIndex >= 0 && trackIndex >= 0 && trackIndex < trackList().size()) {
int i = trackList().at(trackIndex).mlt_index;
QScopedPointer<Mlt::Producer> track(tractor()->track(i));
if (track) {
Mlt::Playlist playlist(*track);
result = playlist.clip_info(clipIndex);
}
}
return std::unique_ptr<Mlt::ClipInfo>(result);
}
QString MultitrackModel::getTrackName(int trackIndex)
{
QString name;
if (trackIndex < m_trackList.size()) {
QScopedPointer<Mlt::Producer> track(m_tractor->track(m_trackList.at(trackIndex).mlt_index));
if (track)
name = track->get(kTrackNameProperty);
}
return name;
}
int MultitrackModel::addAudioTrack()
{
if (!m_tractor) {
m_tractor = new Mlt::Tractor(MLT.profile());
MLT.profile().set_explicit(true);
m_tractor->set(kShotcutXmlProperty, 1);
retainPlaylist();
addBackgroundTrack();
addAudioTrack();
emit created();
emit modified();
return 0;
}
// Get the new track index.
int i = m_tractor->count();
// Create the MLT track.
Mlt::Playlist playlist(MLT.profile());
playlist.set(kAudioTrackProperty, 1);
playlist.set("hide", 1);
playlist.blank(0);
m_tractor->set_track(playlist, i);
MLT.updateAvformatCaching(m_tractor->count());
// Add the mix transition.
Mlt::Transition mix(MLT.profile(), "mix");
mix.set("always_active", 1);
mix.set("sum", 1);
m_tractor->plant_transition(mix, 0, i);
// Get the new, logical audio-only index.
int a = 0;
foreach (Track t, m_trackList) {
if (t.type == AudioTrackType)
++a;
}
// Add the shotcut logical audio track.
Track t;
t.mlt_index = i;
t.type = AudioTrackType;
t.number = a++;
QString trackName = QStringLiteral("A%1").arg(a);
playlist.set(kTrackNameProperty, trackName.toUtf8().constData());
beginInsertRows(QModelIndex(), m_trackList.count(), m_trackList.count());
m_trackList.append(t);
endInsertRows();
emit modified();
return m_trackList.count() - 1;
}
int MultitrackModel::addVideoTrack()
{
if (!m_tractor) {
createIfNeeded();
return 0;
}
// Get the new track index.
int i = m_tractor->count();
// Create the MLT track.
Mlt::Playlist playlist(MLT.profile());
playlist.set(kVideoTrackProperty, 1);
playlist.blank(0);
m_tractor->set_track(playlist, i);
MLT.updateAvformatCaching(m_tractor->count());
// Add the mix transition.
Mlt::Transition mix(MLT.profile(), "mix");
mix.set("always_active", 1);
mix.set("sum", 1);
m_tractor->plant_transition(mix, 0, i);
// Add the composite transition.
Mlt::Transition composite(MLT.profile(),
Settings.playerGPU() ? "movit.overlay" : "frei0r.cairoblend");
if (!composite.is_valid() && !Settings.playerGPU()) {
composite = Mlt::Transition(MLT.profile(), "qtblend");
} else if (composite.is_valid() && !Settings.playerGPU()) {
composite.set("threads", 0);
}
if (warnIfInvalid(composite)) {
return -1;
}
composite.set("disable", 1);
foreach (Track t, m_trackList) {
if (t.type == VideoTrackType) {
composite.set("disable", 0);
break;
}
}
// Get the new, logical video-only index.
int v = 0;
int last_mlt_index = 0;
foreach (Track t, m_trackList) {
if (t.type == VideoTrackType) {
++v;
last_mlt_index = t.mlt_index;
}
}
m_tractor->plant_transition(composite, last_mlt_index, i);
// Add the shotcut logical video track.
Track t;
t.mlt_index = i;
t.type = VideoTrackType;
t.number = v++;
QString trackName = QStringLiteral("V%1").arg(v);
playlist.set(kTrackNameProperty, trackName.toUtf8().constData());
beginInsertRows(QModelIndex(), 0, 0);
m_trackList.prepend(t);
endInsertRows();
emit modified();
return 0;
}
void MultitrackModel::removeTrack(int trackIndex)
{
if (trackIndex >= 0 && trackIndex < m_trackList.size()) {
const Track &track = m_trackList.value(trackIndex);
QScopedPointer<Mlt::Field> field(m_tractor->field());
QScopedPointer<Mlt::Transition> transition(getVideoBlendTransition(track.mlt_index));
// Get the playlist, loop over its clips, and emit removing
QScopedPointer<Mlt::Producer> producer(m_tractor->track(track.mlt_index));
if (producer) {
Mlt::Playlist playlist(*producer);
for (int i = 0; i < playlist.count(); ++i) {
if (!playlist.is_blank(i))
emit removing(playlist.get_clip(i));
}
}
// Remove transitions.
if (transition && transition->is_valid())
field->disconnect_service(*transition);
transition.reset(getTransition("mix", track.mlt_index));
if (transition && transition->is_valid())
field->disconnect_service(*transition);
// foreach (Track t, m_trackList) LOG_DEBUG() << (t.type == VideoTrackType?"Video":"Audio") << "track number" << t.number << "mlt_index" << t.mlt_index;
// LOG_DEBUG() << trackIndex << "mlt_index" << track.mlt_index;
// Remove track.
beginRemoveRows(QModelIndex(), trackIndex, trackIndex);
m_tractor->remove_track(track.mlt_index);
m_trackList.removeAt(trackIndex);
// foreach (Track t, m_trackList) LOG_DEBUG() << (t.type == VideoTrackType?"Video":"Audio") << "track number" << t.number << "mlt_index" << t.mlt_index;
// Renumber other tracks.
int row = 0;
foreach (Track t, m_trackList) {
if (t.mlt_index > track.mlt_index)
--m_trackList[row].mlt_index;
if (t.type == track.type && t.number > track.number) {
--m_trackList[row].number;
QModelIndex modelIndex = index(row, 0);
// Disable compositing on the bottom video track.
if (m_trackList[row].number == 0 && t.type == VideoTrackType) {
QScopedPointer<Mlt::Transition> transition(getVideoBlendTransition(1));
if (transition && transition->is_valid())
transition->set("disable", 1);
emit dataChanged(modelIndex, modelIndex, QVector<int>() << IsBottomVideoRole << IsCompositeRole);
}
// Rename default track names.
QScopedPointer<Mlt::Producer> mltTrack(m_tractor->track(m_trackList[row].mlt_index));
QString trackNameTemplate = (t.type == VideoTrackType) ? QStringLiteral("V%1") :
QStringLiteral("A%1");
QString trackName = trackNameTemplate.arg(t.number + 1);
if (mltTrack && mltTrack->get(kTrackNameProperty) == trackName) {
trackName = trackNameTemplate.arg(m_trackList[row].number + 1);
mltTrack->set(kTrackNameProperty, trackName.toUtf8().constData());
emit dataChanged(modelIndex, modelIndex, QVector<int>() << NameRole);
}
}
++row;
}
endRemoveRows();
MLT.updateAvformatCaching(m_tractor->count());
// foreach (Track t, m_trackList) LOG_DEBUG() << (t.type == VideoTrackType?"Video":"Audio") << "track number" << t.number << "mlt_index" << t.mlt_index;
}
emit modified();
}
void MultitrackModel::retainPlaylist()
{
if (!MAIN.playlist())
MAIN.playlistDock()->model()->createIfNeeded();
Mlt::Playlist playlist(*MAIN.playlist());
playlist.set("id", kPlaylistTrackId);
QString retain = QStringLiteral("xml_retain %1").arg(kPlaylistTrackId);
m_tractor->set(retain.toUtf8().constData(), playlist.get_service(), 0);
}
void MultitrackModel::loadPlaylist()
{
Mlt::Properties retainList((mlt_properties) m_tractor->get_data("xml_retain"));
if (retainList.is_valid()) {
Mlt::Playlist playlist((mlt_playlist) retainList.get_data(kPlaylistTrackId));
if (playlist.is_valid() && playlist.type() == mlt_service_playlist_type) {
MAIN.playlistDock()->model()->setPlaylist(playlist);
} else {
Mlt::Playlist legacyPlaylist((mlt_playlist) retainList.get_data(kLegacyPlaylistTrackId));
if (legacyPlaylist.is_valid() && legacyPlaylist.type() == mlt_service_playlist_type)
MAIN.playlistDock()->model()->setPlaylist(legacyPlaylist);
}
}
retainPlaylist();
}
void MultitrackModel::removeRegion(int trackIndex, int position, int length)
{
int i = m_trackList.at(trackIndex).mlt_index;
QScopedPointer<Mlt::Producer> track(m_tractor->track(i));
if (track) {
Mlt::Playlist playlist(*track);
int clipIndex = playlist.get_clip_index_at(position);
if (clipIndex >= 0 && clipIndex < playlist.count()) {
int clipStart = playlist.clip_start(clipIndex);
int playtime = playlist.get_playtime();
playlist.block(playlist.get_playlist());
if (position + length > playtime)
length -= (position + length - playtime);
if (clipStart < position) {
splitClip(trackIndex, clipIndex, position);
++clipIndex;
}
while (length > 0) {
if (playlist.clip_length(clipIndex) > length) {
splitClip(trackIndex, clipIndex, position + length);
}
length -= playlist.clip_length(clipIndex);
if (clipIndex < playlist.count()) {
// Shotcut does not like the behavior of remove() on a
// transition (MLT mix clip). So, we null mlt_mix to prevent it.
clearMixReferences(trackIndex, clipIndex);
emit removing(playlist.get_clip(clipIndex));
beginRemoveRows(index(trackIndex), clipIndex, clipIndex);
playlist.remove(clipIndex);
endRemoveRows();
}
}
playlist.unblock(playlist.get_playlist());
consolidateBlanks(playlist, trackIndex);
}
}
}
bool MultitrackModel::isTransition(Mlt::Playlist &playlist, int clipIndex) const
{
QScopedPointer<Mlt::Producer> producer(playlist.get_clip(clipIndex));
if (producer && producer->is_valid() && producer->parent().is_valid()
&& producer->parent().get(kShotcutTransitionProperty))
return true;
return false;
}
void MultitrackModel::insertTrack(int trackIndex, TrackType type)
{
if (!m_tractor || trackIndex <= 0) {
addVideoTrack();
return;
}
// Get the new track index.
Track ¤tTrack = m_trackList[qBound(0, trackIndex, m_trackList.count() - 1)];
int currentTrackNumber = currentTrack.number;
int new_mlt_index = currentTrack.mlt_index;
QScopedPointer<Mlt::Transition> lowerVideoTransition;
const char *videoTransitionName = Settings.playerGPU() ? "movit.overlay" : "frei0r.cairoblend";
bool isInsertBottomVideoTrack = false;
if (type == VideoTrackType) {
++new_mlt_index;
lowerVideoTransition.reset(getVideoBlendTransition(currentTrack.mlt_index));
// Handle special case of insert bottom video track.
if ((trackIndex > 0 && currentTrack.type == AudioTrackType) || trackIndex >= m_trackList.count()) {
Track &upperTrack = m_trackList[qBound(0, trackIndex - 1, m_trackList.count() - 1)];
if (upperTrack.type == VideoTrackType) {
new_mlt_index = 1;
lowerVideoTransition.reset(getVideoBlendTransition(upperTrack.mlt_index));
isInsertBottomVideoTrack = true;
}
}
}
// When requesting a new top track.
if (trackIndex >= m_trackList.count()) {
if (type == AudioTrackType) {
addAudioTrack();
return;
} else if (type == VideoTrackType) {
new_mlt_index = currentTrack.mlt_index;
}
}
// foreach (Track t, m_trackList) LOG_DEBUG() << (t.type == VideoTrackType?"Video":"Audio") << "track number" << t.number << "mlt_index" << t.mlt_index;
// LOG_DEBUG() << "trackIndex" << trackIndex << "mlt_index" << i;
// Compute new track numbers.
int videoTrackCount = 0;
int last_mlt_index = 0;
int row = 0;
foreach (Track t, m_trackList) {
if (t.type == type) {
if ((t.type == VideoTrackType && (t.number > currentTrackNumber || isInsertBottomVideoTrack)) ||
(t.type == AudioTrackType && t.number >= currentTrackNumber)) {
// Rename default track names.
QScopedPointer<Mlt::Producer> mltTrack(m_tractor->track(t.mlt_index));
QString trackNameTemplate = (t.type == VideoTrackType) ? QStringLiteral("V%1") :
QStringLiteral("A%1");
QString trackName = trackNameTemplate.arg(++t.number);
if (mltTrack && mltTrack->get(kTrackNameProperty) == trackName) {
trackName = trackNameTemplate.arg(t.number + 1);
mltTrack->set(kTrackNameProperty, trackName.toUtf8().constData());
QModelIndex modelIndex = index(row, 0);
emit dataChanged(modelIndex, modelIndex, QVector<int>() << NameRole);
}
++m_trackList[row].number;
}
}
// Increment the mlt_index for tracks that are moving.
if (t.mlt_index >= new_mlt_index)
++m_trackList[row].mlt_index;
// Count the number of video tracks and get the mlt_index of the last video track.
if (t.type == VideoTrackType) {
++videoTrackCount;
last_mlt_index = t.mlt_index;
}
++row;
}
// foreach (Track t, m_trackList) LOG_DEBUG() << (t.type == VideoTrackType?"Video":"Audio") << "track number" << t.number << "mlt_index" << t.mlt_index;
// Create the MLT track.
Mlt::Playlist playlist(MLT.profile());
if (type == VideoTrackType) {
playlist.set(kVideoTrackProperty, 1);
} else if (type == AudioTrackType) {
playlist.set(kAudioTrackProperty, 1);
playlist.set("hide", 1);
}
playlist.blank(0);
m_tractor->insert_track(playlist, new_mlt_index);
MLT.updateAvformatCaching(m_tractor->count());
// Add the mix transition.
Mlt::Transition mix(MLT.profile(), "mix");
mix.set("always_active", 1);
mix.set("sum", 1);
m_tractor->plant_transition(mix, 0, new_mlt_index);
if (type == VideoTrackType) {
// Add the composite transition.
Mlt::Transition composite(MLT.profile(), videoTransitionName);
if (!composite.is_valid() && !Settings.playerGPU()) {
composite = Mlt::Transition(MLT.profile(), "qtblend");
} else if (composite.is_valid() && !Settings.playerGPU()) {
composite.set("threads", 0);
}
if (warnIfInvalid(composite)) {
return;
}
if (lowerVideoTransition && lowerVideoTransition->is_valid()) {
QScopedPointer<Mlt::Service> consumer(lowerVideoTransition->consumer());
if (consumer->is_valid()) {
// Insert the new transition.
if (new_mlt_index == 1) {
// Special case of insert new bottom video track
LOG_DEBUG() << "inserting transition" << 0 << new_mlt_index;
QScopedPointer<Mlt::Service> lowerProducer(lowerVideoTransition->producer());
if (lowerProducer->is_valid()) {
composite.connect(*lowerProducer, 0, new_mlt_index);
Mlt::Transition t((mlt_transition) lowerProducer->get_service());
lowerVideoTransition->connect(composite, new_mlt_index, t.get_int("b_track"));
}
} else {
LOG_DEBUG() << "inserting transition" << last_mlt_index << new_mlt_index;
composite.connect(*lowerVideoTransition, last_mlt_index, new_mlt_index);
Mlt::Transition t((mlt_transition) consumer->get_service());
t.connect(composite, t.get_int("a_track"), t.get_int("b_track"));
}
} else {
// Append the new transition.
LOG_DEBUG() << "appending transition";
m_tractor->plant_transition(composite, last_mlt_index, new_mlt_index);
}
} else {
// Append the new transition.
LOG_DEBUG() << "appending transition";
m_tractor->plant_transition(composite, last_mlt_index, new_mlt_index);
}
}
// Add the shotcut logical video track.
Track t;
t.mlt_index = new_mlt_index;
t.type = type;
t.number = 0;
QString trackName;
if (t.type == VideoTrackType) {
t.number = videoTrackCount - trackIndex;
trackName = QStringLiteral("V%1");
} else if (t.type == AudioTrackType) {
t.number = trackIndex - videoTrackCount;
trackName = QStringLiteral("A%1");
}
trackName = trackName.arg(t.number + 1);
playlist.set(kTrackNameProperty, trackName.toUtf8().constData());
beginInsertRows(QModelIndex(), trackIndex, trackIndex);
m_trackList.insert(trackIndex, t);
refreshVideoBlendTransitions();
endInsertRows();
emit modified();
// foreach (Track t, m_trackList) LOG_DEBUG() << (t.type == VideoTrackType?"Video":"Audio") << "track number" << t.number << "mlt_index" << t.mlt_index;
}
void MultitrackModel::moveTrack(int fromTrackIndex, int toTrackIndex)
{
LOG_DEBUG() << "From: " << fromTrackIndex << "To: " << toTrackIndex;
MLT.pause();
if (fromTrackIndex >= m_trackList.count() || fromTrackIndex < 0
|| toTrackIndex >= m_trackList.count() || toTrackIndex < 0) {
LOG_DEBUG() << "Invalid track index" << fromTrackIndex << toTrackIndex;
return;
}
if (fromTrackIndex == toTrackIndex) {
LOG_DEBUG() << "Do not move track to itself" << fromTrackIndex;
return;
}
int fromMltIndex = m_trackList.at(fromTrackIndex).mlt_index;
int toMltIndex = m_trackList.at(toTrackIndex).mlt_index;
// Take a copy of the track
QScopedPointer<Mlt::Producer> producer(m_tractor->track(fromMltIndex));
// Take a copy of all the transitions
// Save the transitions in order of their new track index
QMap<int, Mlt::Transition> videoTransitions;
QMap<int, Mlt::Transition> audioTransitions;
QScopedPointer<Mlt::Service> service(m_tractor->producer());
while (service && service->is_valid()) {
if (service->type() == mlt_service_transition_type) {
Mlt::Transition t((mlt_transition) service->get_service());
int newBTrack = t.get_b_track();
if (newBTrack == fromMltIndex) {
newBTrack = toMltIndex;
} else {
if (newBTrack > fromMltIndex) {
newBTrack--;
}
if (newBTrack >= toMltIndex) {
newBTrack++;
}
}
if (service->get("mlt_service") != QStringLiteral("mix") ) {
videoTransitions[newBTrack] = *service;
} else {
audioTransitions[newBTrack] = *service;
}
}
service.reset(service->producer());
}
if (toTrackIndex > fromTrackIndex) {
beginMoveRows(QModelIndex(), fromTrackIndex, fromTrackIndex, QModelIndex(), toTrackIndex + 1);
} else {
beginMoveRows(QModelIndex(), fromTrackIndex, fromTrackIndex, QModelIndex(), toTrackIndex);
}
// Clear all default track names (will regenerate in refreshTrackList)
foreach (const Track &t, m_trackList) {
QScopedPointer<Mlt::Producer> mltTrack(m_tractor->track(t.mlt_index));
QString trackNameTemplate = (t.type == VideoTrackType) ? QStringLiteral("V%1") :
QStringLiteral("A%1");
QString trackName = trackNameTemplate.arg(t.number + 1);
if (mltTrack && mltTrack->get(kTrackNameProperty) == trackName) {
mltTrack->Mlt::Properties::clear(kTrackNameProperty);
}
}
// Remove all the transitions
// (remove_track() and insert_track() would mess them up)
service.reset(m_tractor->producer());
QScopedPointer<Mlt::Field> field(m_tractor->field());
while (service && service->is_valid()) {
Mlt::Service s(service->get_service());
service.reset(service->producer());
if (s.type() == mlt_service_transition_type) {
field->disconnect_service(s);
s.disconnect_all_producers();
}
}
// Remove the track and add it in the new position
m_tractor->remove_track(fromMltIndex);
m_tractor->insert_track(*producer, toMltIndex);
// Add the transitions back in the new positions
for (auto i = audioTransitions.keyBegin(); i != audioTransitions.keyEnd(); i++) {
int bTrack = *i;
int aTrack = 0;
if (audioTransitions[bTrack].is_valid()) {
Mlt::Transition aTransition (MLT.profile(), audioTransitions[bTrack].get("mlt_service"));
aTransition.inherit(audioTransitions[bTrack]);
m_tractor->plant_transition(aTransition, aTrack, bTrack);
}
if (videoTransitions[bTrack].is_valid()) {
Mlt::Transition vTransition (MLT.profile(), videoTransitions[bTrack].get("mlt_service"));
vTransition.set("1", videoTransitions[bTrack].get("1"));
if (bTrack == 1) {
vTransition.set("disable", 1);
} else {
// video transitions mix with track 1
// (except track 1 which mixes with track 0)
aTrack = 1;
vTransition.set("disable", 0);
QString mode = vTransition.get("1");
if (mode.isEmpty()) {
vTransition.set("1", "normal");
}
}
m_tractor->plant_transition(vTransition, aTrack, bTrack);
}
}
m_trackList.clear();
refreshTrackList();
endMoveRows();
emit dataChanged(index(0), index(m_trackList.size() - 1),
QVector<int>() << IsTopVideoRole << IsBottomVideoRole << IsTopAudioRole << IsBottomAudioRole <<
IsCompositeRole << NameRole);
emit modified();
}
void MultitrackModel::insertOrAdjustBlankAt(QList<int> tracks, int position, int length)
{
foreach (int trackIndex, tracks) {
int mltIndex = m_trackList.at(trackIndex).mlt_index;
QScopedPointer<Mlt::Producer> otherTrack(m_tractor->track(mltIndex));
if (otherTrack) {
Mlt::Playlist trackPlaylist(*otherTrack);
// Check if frame before position is blank
int idx = trackPlaylist.get_clip_index_at(position - 1);
if (trackPlaylist.is_blank(idx)) {
trackPlaylist.resize_clip(idx, 0, trackPlaylist.clip_length(idx) + length - 1);
QModelIndex modelIndex = createIndex(idx, 0, trackIndex);
emit dataChanged(modelIndex, modelIndex, QVector<int>() << DurationRole);
continue;
}
// Check if frame as position is blank
idx = trackPlaylist.get_clip_index_at(position);
if (trackPlaylist.is_blank(idx)) {
trackPlaylist.resize_clip(idx, 0, trackPlaylist.clip_length(idx) + length - 1);
QModelIndex modelIndex = createIndex(idx, 0, trackIndex);
emit dataChanged(modelIndex, modelIndex, QVector<int>() << DurationRole);
} else if (length > 0) {
int insertBlankAtIdx = idx;
if (trackPlaylist.clip_start(idx) < position) {
splitClip(trackIndex, idx, position);
insertBlankAtIdx = idx + 1;
}
beginInsertRows(index(trackIndex), insertBlankAtIdx, insertBlankAtIdx);
trackPlaylist.insert_blank(insertBlankAtIdx, length - 1);
endInsertRows();
} else {
Q_ASSERT(!"unsupported");
}
}
}
}
bool MultitrackModel::mergeClipWithNext(int trackIndex, int clipIndex, bool dryrun)
{
int i = m_trackList.at(trackIndex).mlt_index;
QScopedPointer<Mlt::Producer> track(m_tractor->track(i));
if (!track)
return false;
Mlt::Playlist playlist(*track);
if (clipIndex >= playlist.count() + 1)
return false;
Mlt::ClipInfo clip1;
Mlt::ClipInfo clip2;
playlist.clip_info(clipIndex, &clip1);
playlist.clip_info(clipIndex + 1, &clip2);
if (QString::fromUtf8(clip1.resource) != QString::fromUtf8(clip2.resource))
return false;
if (clip1.frame_out + 1 != clip2.frame_in)
return false;
if (dryrun)
return true;
// Consolidate filters
QStringList filters {"fadeInVolume", "fadeOutVolume", "fadeInBrightness", "fadeOutBrightness", "fadeInMovit", "fadeOutMovit"};
for (const auto &s : filters) {
QScopedPointer<Mlt::Filter> filter(getFilter(s, clip1.producer));
if (filter && filter->is_valid()) {
filter.reset(getFilter(s, clip2.producer));
if (filter && filter->is_valid()) {
clip2.producer->detach(*filter);
}
}
}
Mlt::Controller::copyFilters(*clip2.producer, *clip1.producer);
QModelIndex modelIndex = createIndex(clipIndex, 0, trackIndex);
QVector<int> roles;
roles << FadeInRole;
roles << FadeOutRole;
emit dataChanged(modelIndex, modelIndex, roles);
liftClip(trackIndex, clipIndex + 1);
trimClipOut(trackIndex, clipIndex, -clip2.frame_count, false, false);
emit modified();
return true;
}
bool MultitrackModel::isFiltered(Mlt::Producer *producer) const
{
if (!producer)
producer = m_tractor;
if (producer && producer->is_valid()) {
int count = producer->filter_count();
for (int i = 0; i < count; i++) {
QScopedPointer<Mlt::Filter> filter(producer->filter(i));
if (filter && filter->is_valid() && !filter->get_int("_loader")
&& !filter->get_int(kShotcutHiddenProperty))
return true;
}
}
return false;
}
int MultitrackModel::getDuration()
{
int n = 0;
if (m_tractor) {
foreach (Track t, m_trackList) {
QScopedPointer<Mlt::Producer> track(m_tractor->track(t.mlt_index));
if (track && track->is_valid())
n = qMax(n, track->get_length());
}
}
return n;
}
void MultitrackModel::load()
{
if (m_tractor) {
emit aboutToClose();
AudioLevelsTask::closeAll();
beginResetModel();
delete m_tractor;
m_tractor = nullptr;
m_trackList.clear();
endResetModel();
}
// In some versions of MLT, the resource property is the XML filename,
// but the Mlt::Tractor(Service&) constructor will fail unless it detects
// the type as tractor, and mlt_service_identify() needs the resource
// property to say "<tractor>" to identify it as playlist type.
MLT.producer()->set("mlt_type", "mlt_producer");
MLT.producer()->set("resource", "<tractor>");
MLT.profile().set_explicit(true);
m_tractor = new Mlt::Tractor(*MLT.producer());
if (!m_tractor->is_valid()) {
delete m_tractor;
m_tractor = 0;
return;
}
loadPlaylist();
addBlackTrackIfNeeded();
MLT.updateAvformatCaching(m_tractor->count());
refreshTrackList();
convertOldDoc();
consolidateBlanksAllTracks();
adjustBackgroundDuration();
adjustTrackFilters();
if (m_trackList.count() > 0) {
beginInsertRows(QModelIndex(), 0, m_trackList.count() - 1);
endInsertRows();
getAudioLevels();
}
emit created();
emit filteredChanged();
emit scaleFactorChanged();
}
void MultitrackModel::reload(bool asynchronous)
{
if (m_tractor) {
if (asynchronous) {
emit reloadRequested();
} else {
AudioLevelsTask::closeAll();
beginResetModel();
endResetModel();
getAudioLevels();
emit filteredChanged();
}
}
}
void MultitrackModel::replace(int trackIndex, int clipIndex, Mlt::Producer &clip, bool copyFilters)
{
int i = m_trackList.at(trackIndex).mlt_index;
QScopedPointer<Mlt::Producer> track(m_tractor->track(i));
if (track->is_valid()) {
// LOG_DEBUG() << __FUNCTION__ << "replace" << position << MLT.XML(&clip);
Mlt::Playlist playlist(*track.data());
int in = clip.get_in();
int out = clip.get_out();
Mlt::Producer oldClip(playlist.get_clip(clipIndex));
Q_ASSERT(oldClip.is_valid());
int clipPlaytime = oldClip.get_playtime();
int transitionIn = oldClip.parent().get(kFilterInProperty) ? oldClip.get_in() -
oldClip.parent().get_int(kFilterInProperty) : 0;
int transitionOut = oldClip.parent().get(kFilterOutProperty) ? oldClip.parent().get_int(
kFilterOutProperty) - oldClip.get_out() : 0;
in += transitionIn;
out -= transitionOut;
if (clip.get_in() > 0 || clip.get_out() == clip.get_playtime() - 1)
out = in + clipPlaytime - 1;
else
in = out - clipPlaytime + 1;
clip.set_in_and_out(in, out);
if (copyFilters) {
auto parent = oldClip.parent();
parent.set(kFilterInProperty, oldClip.get_in());
parent.set(kFilterOutProperty, oldClip.get_out());
Mlt::Controller::copyFilters(parent, clip);
Mlt::Controller::adjustFilters(clip);
}
emit removing(playlist.get_clip(clipIndex));
beginRemoveRows(index(trackIndex), clipIndex, clipIndex);
playlist.remove(clipIndex);
endRemoveRows();
beginInsertRows(index(trackIndex), clipIndex, clipIndex);
playlist.insert_blank(clipIndex, clipPlaytime - 1);
endInsertRows();
overwrite(trackIndex, clip, playlist.clip_start(clipIndex), false);
// Handle transition on the left
if (transitionIn && isTransition(playlist, clipIndex - 1)) {
Mlt::Producer producer(playlist.get_clip(clipIndex - 1));
if (producer.is_valid()) {
Mlt::Tractor tractor(MLT_TRACTOR(producer.get_parent()));
Q_ASSERT(tractor.is_valid());
QScopedPointer<Mlt::Producer> track(tractor.track(1));
if (!qstrcmp(track->parent().get(kShotcutHashProperty),
oldClip.parent().get(kShotcutHashProperty))) {
QScopedPointer<Mlt::Producer> cut(clip.cut(in - transitionIn, in - 1));
tractor.set_track(*cut.data(), 1);
}
}
}
// Handle transition on the right
if (transitionOut && isTransition(playlist, clipIndex + 1)) {
Mlt::Producer producer(playlist.get_clip(clipIndex + 1));
if (producer.is_valid()) {
Mlt::Tractor tractor(MLT_TRACTOR(producer.get_parent()));
Q_ASSERT(tractor.is_valid());
QScopedPointer<Mlt::Producer> track(tractor.track(0));
if (!qstrcmp(track->parent().get(kShotcutHashProperty),
oldClip.parent().get(kShotcutHashProperty))) {
QScopedPointer<Mlt::Producer> cut(clip.cut(out + 1, out + transitionOut));
tractor.set_track(*cut.data(), 0);
}
}
}
}
}
void MultitrackModel::close()
{
if (!m_tractor) return;
emit aboutToClose();
AudioLevelsTask::closeAll();
beginResetModel();
delete m_tractor;
m_tractor = nullptr;
m_trackList.clear();
endResetModel();
emit closed();
emit filteredChanged();
}
int MultitrackModel::clipIndex(int trackIndex, int position)
{
int i = m_trackList.at(trackIndex).mlt_index;
QScopedPointer<Mlt::Producer> track(m_tractor->track(i));
if (track) {
Mlt::Playlist playlist(*track);
return playlist.get_clip_index_at(position);
}
return -1; // error
}
void MultitrackModel::refreshTrackList()
{
int n = m_tractor->count();
int a = 0;
int v = 0;
bool isKdenlive = false;
// Add video tracks in reverse order.
for (int i = 0; i < n; ++i) {
QScopedPointer<Mlt::Producer> track(m_tractor->track(i));
if (!track)
continue;
QString trackId = track->get("id");
if (trackId == "black_track")
isKdenlive = true;
else if (trackId == kBackgroundTrackId)
continue;
else if (!track->get(kShotcutPlaylistProperty) && !track->get(kAudioTrackProperty)) {
int hide = track->get_int("hide");
// hide: 0 = a/v, 2 = muted video track
if (track->get(kVideoTrackProperty) || hide == 0 || hide == 2) {
Track t;
t.mlt_index = i;
t.type = VideoTrackType;
t.number = v++;
QString trackName = track->get(kTrackNameProperty);
if (trackName.isEmpty())
trackName = QStringLiteral("V%1").arg(v);
track->set(kTrackNameProperty, trackName.toUtf8().constData());
m_trackList.prepend(t);
// Always disable compositing on V1.
if (v == 1) {
QScopedPointer<Mlt::Transition> transition(getVideoBlendTransition(1));
if (transition && transition->is_valid())
transition->set("disable", 1);
}
}
}
}
// Add audio tracks.
for (int i = 0; i < n; ++i) {
QScopedPointer<Mlt::Producer> track(m_tractor->track(i));
if (!track)
continue;
QString trackId = track->get("id");
if (trackId == "black_track")
isKdenlive = true;
else if (isKdenlive && trackId == "playlist1")
// In Kdenlive, playlist1 is a special audio mixdown track.
continue;
else if (trackId == kPlaylistTrackId || trackId == kLegacyPlaylistTrackId)
continue;
else if (!track->get(kShotcutPlaylistProperty) && !track->get(kVideoTrackProperty)) {
int hide = track->get_int("hide");
// hide: 1 = audio only track, 3 = muted audio-only track
if (track->get(kAudioTrackProperty) || hide == 1 || hide == 3) {
Track t;
t.mlt_index = i;
t.type = AudioTrackType;
t.number = a++;
QString trackName = track->get(kTrackNameProperty);
if (trackName.isEmpty())
trackName = QStringLiteral("A%1").arg(a);
track->set(kTrackNameProperty, trackName.toUtf8().constData());
m_trackList.append(t);
// LOG_DEBUG() << __FUNCTION__ << QString(track->get("id")) << i;
}
}
}
}
void MultitrackModel::getAudioLevels()
{
for (int trackIx = 0; trackIx < m_trackList.size(); trackIx++) {
int i = m_trackList.at(trackIx).mlt_index;
QScopedPointer<Mlt::Producer> track(m_tractor->track(i));
Mlt::Playlist playlist(*track);
for (int clipIx = 0; clipIx < playlist.count(); clipIx++) {
QScopedPointer<Mlt::Producer> clip(playlist.get_clip(clipIx));
if (clip && clip->is_valid() && !clip->is_blank() && clip->get_int("audio_index") > -1) {
QModelIndex index = createIndex(clipIx, 0, trackIx);
AudioLevelsTask::start(clip->parent(), this, index);
}
}
}
}
void MultitrackModel::addBlackTrackIfNeeded()
{
return;
// Make sure the first track is black silence and add it if needed
bool found = false;
int n = m_tractor->count();
QScopedPointer<Mlt::Producer> track(m_tractor->track(0));
if (track) {
Mlt::Playlist playlist(*track);
QScopedPointer<Mlt::Producer> clip(playlist.get_clip(0));
if (clip && QString(clip->get("id")) == "black")
found = true;
}
if (!found) {
// Move all existing tracks down by 1.
for (int i = n; i > 0; i++) {
std::unique_ptr<Mlt::Producer> producer(m_tractor->track(n - 1));
if (producer && producer->is_valid())
m_tractor->set_track(*producer, n);
}
Mlt::Producer producer(MLT.profile(), "color:0");
producer.set("mlt_image_format", "rgba");
m_tractor->set_track(producer, 0);
}
}
void MultitrackModel::convertOldDoc()
{
QScopedPointer<Mlt::Field> field(m_tractor->field());
// Convert composite to frei0r.cairoblend.
int n = m_tractor->count();
for (int i = 1; i < n; ++i) {
QScopedPointer<Mlt::Transition> transition(getTransition("composite", i));
if (transition) {
Mlt::Transition composite(MLT.profile(), "frei0r.cairoblend");
composite.set("disable", transition->get_int("disable"));
field->disconnect_service(*transition);
m_tractor->plant_transition(composite, transition->get_int("a_track"), i);
}
}
// Remove movit.rect filters.
QScopedPointer<Mlt::Service> service(m_tractor->producer());
while (service && service->is_valid()) {
if (service->type() == mlt_service_filter_type) {
Mlt::Filter f((mlt_filter) service->get_service());
if (QString::fromLatin1(f.get("mlt_service")) == "movit.rect") {
field->disconnect_service(f);
}
}
service.reset(service->producer());
}
// Change a_track of composite transitions to bottom video track.
int a_track = bottomVideoTrackMltIndex();
foreach (Track t, m_trackList) {
if (t.type == VideoTrackType) {
QScopedPointer<Mlt::Transition> transition(getVideoBlendTransition(t.mlt_index));
if (transition && transition->is_valid() && transition->get_a_track() != 0)
transition->set("a_track", a_track);
}
}
// Ensure the background track clears the test_audio flag on frames.
QScopedPointer<Mlt::Producer> track(m_tractor->track(0));
if (track) {
Mlt::Playlist playlist(*track);
QScopedPointer<Mlt::ClipInfo> info(playlist.clip_info(0));
if (info && info->producer->is_valid() && QString(info->producer->get("id")) == "black")
info->producer->set("set.test_audio", 0);
}
}
Mlt::Transition *MultitrackModel::getTransition(const QString &name, int trackIndex) const
{
QScopedPointer<Mlt::Service> service(m_tractor->producer());
while (service && service->is_valid()) {
if (service->type() == mlt_service_transition_type) {
Mlt::Transition t((mlt_transition) service->get_service());
if (name == t.get("mlt_service") && t.get_b_track() == trackIndex)
return new Mlt::Transition(t);
}
service.reset(service->producer());
}
return nullptr;
}
Mlt::Filter *MultitrackModel::getFilter(const QString &name, int trackIndex) const
{
QScopedPointer<Mlt::Service> service(m_tractor->producer());
while (service && service->is_valid()) {
if (service->type() == mlt_service_filter_type) {
Mlt::Filter f((mlt_filter) service->get_service());
if (name == f.get("mlt_service") && f.get_track() == trackIndex)
return new Mlt::Filter(f);
}
service.reset(service->producer());
}
return 0;
}
Mlt::Filter *MultitrackModel::getFilter(const QString &name, Mlt::Service *service) const
{
return MLT.getFilter(name, service);
}
void MultitrackModel::removeBlankPlaceholder(Mlt::Playlist &playlist, int trackIndex)
{
if (playlist.count() == 1 && playlist.is_blank(0)) {
QScopedPointer<Mlt::ClipInfo> info(playlist.clip_info(0));
if (info->frame_count == 1) {
qDebug() << "REMOVE PLACEHOLDER";
beginRemoveRows(index(trackIndex), 0, 0);
playlist.remove(0);
endRemoveRows();
checkForEmptyTracks(trackIndex);
}
}
}
| 152,928
|
C++
|
.cpp
| 3,453
| 33.104257
| 188
| 0.568631
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,192
|
subtitlesselectionmodel.cpp
|
mltframework_shotcut/src/models/subtitlesselectionmodel.cpp
|
/*
* Copyright (c) 2024 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "subtitlesselectionmodel.h"
#include "models/subtitlesmodel.h"
SubtitlesSelectionModel::SubtitlesSelectionModel(QAbstractItemModel *model)
: QItemSelectionModel(model)
, m_selectedTrackIndex(-1)
{
connect(this, &QItemSelectionModel::selectionChanged, this, [&](const QItemSelection & selected,
const QItemSelection & deselected) {
QVariantList result;
foreach (auto modelIndex, selectedRows()) {
result << modelIndex.row();
}
m_selectedItems = result;
if (selectedRows().size() == 1) {
m_lastSingleSelection = selectedRows()[0].row();
}
emit selectedItemsChanged();
});
}
QModelIndex SubtitlesSelectionModel::selectedTrackModelIndex()
{
SubtitlesModel *smodel = dynamic_cast<SubtitlesModel *>(model());
return smodel->trackModelIndex(m_selectedTrackIndex);
}
int SubtitlesSelectionModel::selectedTrack()
{
return m_selectedTrackIndex;
}
void SubtitlesSelectionModel::setSelectedTrack(int trackIndex)
{
if (m_selectedTrackIndex != trackIndex) {
m_selectedTrackIndex = trackIndex;
clearSelection();
m_lastSingleSelection = -1;
emit selectedTrackModelIndexChanged(selectedTrackModelIndex());
}
}
QVariantList SubtitlesSelectionModel::selectedItems()
{
return m_selectedItems;
}
bool SubtitlesSelectionModel::isItemSelected(int itemIndex)
{
if (m_selectedItems.contains(QVariant(itemIndex))) {
return true;
}
return false;
}
void SubtitlesSelectionModel::selectItem(int itemIndex)
{
QModelIndexList selected = selectedIndexes();
if (selected.size() == 1 && selected[0].row() == itemIndex) {
// This item is already selected
return;
}
SubtitlesModel *smodel = dynamic_cast<SubtitlesModel *>(model());
QModelIndex itemModelIndex = smodel->itemModelIndex(m_selectedTrackIndex, itemIndex);
if (itemModelIndex.isValid()) {
select(itemModelIndex, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
setCurrentIndex(itemModelIndex, QItemSelectionModel::NoUpdate);
}
}
void SubtitlesSelectionModel::selectRange(int itemIndex)
{
SubtitlesModel *smodel = dynamic_cast<SubtitlesModel *>(model());
QModelIndex itemModelIndex = smodel->itemModelIndex(m_selectedTrackIndex, itemIndex);
if (!itemModelIndex.isValid()) {
return;
}
qDebug() << m_lastSingleSelection << itemIndex;
if (m_lastSingleSelection == -1) {
select(itemModelIndex, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::SelectCurrent |
QItemSelectionModel::Rows);
} else {
QModelIndex firstItemModelIndex = smodel->itemModelIndex(m_selectedTrackIndex,
m_lastSingleSelection);
QItemSelection newSelection(firstItemModelIndex, itemModelIndex);
select(newSelection, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::SelectCurrent |
QItemSelectionModel::Rows);
}
setCurrentIndex(itemModelIndex, QItemSelectionModel::NoUpdate);
}
| 3,823
|
C++
|
.cpp
| 98
| 33.602041
| 105
| 0.721669
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,193
|
resourcemodel.cpp
|
mltframework_shotcut/src/models/resourcemodel.cpp
|
/*
* Copyright (c) 2023-2024 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "resourcemodel.h"
#include <Logger.h>
#include "util.h"
#include "shotcut_mlt_properties.h"
#include <Mlt.h>
class ProducerFinder : public Mlt::Parser
{
public:
ProducerFinder(ResourceModel *model)
: Mlt::Parser()
, m_model(model)
{}
int on_start_producer(Mlt::Producer *producer)
{
if (!m_isBackgroundTrack && producer->parent().get("resource") != QStringLiteral("<tractor>")) {
if (!m_isTransition)
m_clipIndex++;
if (!producer->is_blank()) {
QString location;
if (m_trackIndex == -1) {
location = QObject::tr("Playlist Clip: %1").arg(m_clipIndex + 1);
} else {
if (m_isTransition) {
location = QObject::tr("Track: %1, Clip: %2 (transition)").arg(m_trackName).arg(m_clipIndex + 1);
} else {
location = QObject::tr("Track: %1, Clip: %2").arg(m_trackName).arg(m_clipIndex + 1);
}
}
m_model->add(producer, location);
}
}
return 0;
}
int on_start_filter(Mlt::Filter *)
{
return 0;
}
int on_end_producer(Mlt::Producer *)
{
return 0;
}
int on_start_playlist(Mlt::Playlist *playlist)
{
if (playlist->get("id") == QStringLiteral("background")) {
m_isBackgroundTrack = true;
} else {
m_trackName = playlist->get(kTrackNameProperty);
}
return 0;
}
int on_end_playlist(Mlt::Playlist *)
{
m_trackName.clear();
m_isBackgroundTrack = false;
return 0;
}
int on_start_tractor(Mlt::Tractor *)
{
if (!m_isTimeline) {
m_isTimeline = true;
} else {
m_isTransition = true;
// Count both clips in a transition as the same index;
m_clipIndex++;
}
return 0;
}
int on_end_tractor(Mlt::Tractor *)
{
m_isTransition = false;
return 0;
}
int on_start_multitrack(Mlt::Multitrack *)
{
return 0;
}
int on_end_multitrack(Mlt::Multitrack *)
{
return 0;
}
int on_start_track()
{
if (!m_isTransition) {
m_trackIndex++;
m_clipIndex = -1;
}
return 0;
}
int on_end_track()
{
return 0;
}
int on_end_filter(Mlt::Filter *)
{
return 0;
}
int on_start_transition(Mlt::Transition *)
{
return 0;
}
int on_end_transition(Mlt::Transition *)
{
return 0;
}
int on_start_chain(Mlt::Chain *)
{
return 0;
}
int on_end_chain(Mlt::Chain *)
{
return 0;
}
int on_start_link(Mlt::Link *)
{
return 0;
}
int on_end_link(Mlt::Link *)
{
return 0;
}
private:
ResourceModel *m_model;
bool m_isTimeline = false;
bool m_isTransition = false;
bool m_isBackgroundTrack = false;
int m_trackIndex = -1;
int m_clipIndex = -1;
QString m_trackName;
};
QString appendLocation(QString ¤tLocations, const QString &location)
{
if (currentLocations.isEmpty()) {
return location;
} else {
return currentLocations + "\n" + location;
}
}
ResourceModel::ResourceModel(QObject *parent)
: QAbstractItemModel(parent)
{
}
ResourceModel::~ResourceModel()
{
}
void ResourceModel::search(Mlt::Producer *producer)
{
if (!producer) {
return;
}
ProducerFinder parser(this);
beginResetModel();
parser.start(*producer);
std::sort(m_producers.begin(), m_producers.end(), [ & ](Mlt::Producer & a, Mlt::Producer & b) {
return Util::GetFilenameFromProducer(&a, true).compare(Util::GetFilenameFromProducer(&b, true),
Qt::CaseInsensitive) < 0;
});
endResetModel();
}
void ResourceModel::add(Mlt::Producer *producer, const QString &location)
{
if (producer->is_blank()) {
// Do not add
} else if (producer->is_cut()) {
Mlt::Producer parent = producer->parent();
QString hash = Util::getHash(parent);
if (!hash.isEmpty()) {
if (!exists(hash)) {
beginInsertRows(QModelIndex(), m_producers.size(), m_producers.size());
m_producers.append(parent);
endInsertRows();
}
m_locations[hash] = appendLocation(m_locations[hash], location);
}
} else {
QString hash = Util::getHash(*producer);
if (!hash.isEmpty()) {
if (!exists(hash)) {
beginInsertRows(QModelIndex(), m_producers.size(), m_producers.size());
m_producers.append(*producer);
endInsertRows();
}
m_locations[hash] = appendLocation(m_locations[hash], location);
}
}
}
QList<Mlt::Producer> ResourceModel::getProducers(const QModelIndexList &indices)
{
QList<Mlt::Producer> producers;
foreach (auto index, indices) {
int row = index.row();
if (row >= 0 && row < m_producers.size()) {
producers << m_producers[row];
}
}
return producers;
}
bool ResourceModel::exists(const QString &hash)
{
for ( int i = 0; i < m_producers.count(); ++i ) {
if (Util::getHash(m_producers[i]) == hash) {
return true;
}
}
return false;
}
int ResourceModel::producerCount()
{
return m_producers.count();
}
Mlt::Producer ResourceModel::producer(int index)
{
if (index >= 0 && index < m_producers.count()) {
return m_producers[index];
}
return Mlt::Producer();
}
int ResourceModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent)
return m_producers.size();
}
int ResourceModel::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent)
return COLUMN_COUNT;
}
QVariant ResourceModel::data(const QModelIndex &index, int role) const
{
QVariant result;
switch (role) {
case Qt::StatusTipRole:
case Qt::FontRole:
case Qt::SizeHintRole:
case Qt::CheckStateRole:
case Qt::BackgroundRole:
case Qt::ForegroundRole:
return result;
}
if (!index.isValid() || index.column() < 0 || index.column() >= COLUMN_COUNT || index.row() < 0
|| index.row() >= m_producers.size()) {
LOG_ERROR() << "Invalid Index: " << index.row() << index.column() << role;
return result;
}
Mlt::Producer *producer = const_cast<Mlt::Producer *>(&m_producers[index.row()] );
switch (role) {
case Qt::DisplayRole:
switch (index.column()) {
case COLUMN_INFO:
break;
case COLUMN_NAME: {
QString path = Util::GetFilenameFromProducer(producer, true);
QFileInfo info(path);
result = info.fileName();
break;
}
case COLUMN_SIZE: {
QString path = Util::GetFilenameFromProducer(producer, true);
QFileInfo info(path);
double size = (double)info.size() / (double)(1024 * 1024);
result = tr("%1MB").arg(QLocale().toString(size, 'f', 2));
break;
}
case COLUMN_VID_DESCRIPTION: {
int width = producer->get_int("meta.media.width");
int height = producer->get_int("meta.media.height");
if (producer->get_int("video_index") >= 0) {
double frame_rate_num = producer->get_double("meta.media.frame_rate_num");
double frame_rate_den = producer->get_double("meta.media.frame_rate_den");
if ( width && height && frame_rate_num && frame_rate_den
&& (frame_rate_num / frame_rate_den) < 1000) {
int index = producer->get_int("video_index");
QString key = QStringLiteral("meta.media.%1.codec.name").arg(index);
QString codec(producer->get(key.toLatin1().constData()));
double frame_rate = frame_rate_num / frame_rate_den;
result = tr("%1 %2x%3 %4fps")
.arg(codec)
.arg(width)
.arg(height)
.arg(QLocale().toString(frame_rate, 'f', 2));
}
}
if (result.isNull() && width > 0 && height > 0 ) {
result = QString(QObject::tr("%1x%2"))
.arg(width)
.arg(height);
}
break;
}
case COLUMN_AUD_DESCRIPTION: {
if (producer->get_int("audio_index") >= 0) {
int index = producer->get_int("audio_index");
QString key = QStringLiteral("meta.media.%1.codec.name").arg(index);
QString codec(producer->get(key.toLatin1().constData()));
if (!codec.isEmpty()) {
key = QStringLiteral("meta.media.%1.codec.channels").arg(index);
int channels(producer->get_int(key.toLatin1().constData()));
key = QStringLiteral("meta.media.%1.codec.sample_rate").arg(index);
QString sampleRate(producer->get(key.toLatin1().constData()));
result = QStringLiteral("%1 %2ch %3KHz")
.arg(codec)
.arg(channels)
.arg(sampleRate.toDouble() / 1000);
}
}
break;
}
default:
LOG_ERROR() << "Invalid DisplayRole Column" << index.row() << index.column() << roleNames()[role] <<
role;
break;
}
break;
case Qt::ToolTipRole:
switch (index.column()) {
case COLUMN_INFO:
result = Util::getConversionAdvice(producer);
break;
case COLUMN_NAME:
case COLUMN_VID_DESCRIPTION:
case COLUMN_AUD_DESCRIPTION:
case COLUMN_SIZE: {
QString filename = Util::GetFilenameFromProducer(producer, true);
QString hash = Util::getHash(*producer);
QString locations = m_locations[hash];
if (locations.isEmpty()) {
result = filename;
} else {
result = filename + "\n" + locations;
}
break;
}
default:
LOG_ERROR() << "Invalid ToolTipRole Column" << index.row() << index.column() << roleNames()[role] <<
role;
break;
}
break;
case Qt::TextAlignmentRole:
switch (index.column()) {
case COLUMN_INFO:
case COLUMN_NAME:
case COLUMN_VID_DESCRIPTION:
case COLUMN_AUD_DESCRIPTION:
result = Qt::AlignLeft;
break;
case COLUMN_SIZE:
result = Qt::AlignRight;
break;
default:
LOG_ERROR() << "Invalid TextAlignmentRole Column" << index.row() << index.column() <<
roleNames()[role] << role;
break;
}
break;
case Qt::DecorationRole:
switch (index.column()) {
case COLUMN_INFO:
if (!Util::getConversionAdvice(producer).isEmpty()) {
result = QIcon(":/icons/oxygen/32x32/status/task-attempt.png");
} else {
result = QIcon(":/icons/oxygen/32x32/status/task-complete.png");
}
break;
case COLUMN_NAME:
case COLUMN_VID_DESCRIPTION:
case COLUMN_AUD_DESCRIPTION:
case COLUMN_SIZE:
break;
default:
LOG_ERROR() << "Invalid DecorationRole Column" << index.row() << index.column() << roleNames()[role]
<< role;
break;
}
break;
default:
LOG_ERROR() << "Invalid Role" << index.row() << index.column() << roleNames()[role] << role;
break;
}
return result;
}
QVariant ResourceModel::headerData(int section, Qt::Orientation orientation, int role) const
{
switch (role) {
case Qt::DisplayRole: {
switch (section) {
case COLUMN_NAME:
return tr("Name");
case COLUMN_SIZE:
return tr("Size");
case COLUMN_VID_DESCRIPTION:
return tr("Video");
case COLUMN_AUD_DESCRIPTION:
return tr("Audio");
default:
break;
}
}
case Qt::TextAlignmentRole:
switch (section) {
case COLUMN_NAME:
return Qt::AlignLeft;
case COLUMN_VID_DESCRIPTION:
case COLUMN_AUD_DESCRIPTION:
case COLUMN_SIZE:
return Qt::AlignCenter;
default:
break;
}
break;
}
return QVariant();
}
QModelIndex ResourceModel::index(int row, int column, const QModelIndex &parent) const
{
Q_UNUSED(parent)
if (column < 0 || column >= COLUMN_COUNT || row < 0 || row >= m_producers.size())
return QModelIndex();
return createIndex(row, column, (int)0);
}
QModelIndex ResourceModel::parent(const QModelIndex &index) const
{
Q_UNUSED(index)
return QModelIndex();
}
| 14,069
|
C++
|
.cpp
| 440
| 22.993182
| 121
| 0.547707
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,194
|
playlistmodel.cpp
|
mltframework_shotcut/src/models/playlistmodel.cpp
|
/*
* Copyright (c) 2012-2024 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "playlistmodel.h"
#include "util.h"
#include "shotcut_mlt_properties.h"
#include <QDateTime>
#include <QUrl>
#include <QImage>
#include <QColor>
#include <QPainter>
#include <QThreadPool>
#include <Logger.h>
#include <QApplication>
#include <QPalette>
#include <QCryptographicHash>
#include <QScopedPointer>
#include <QDir>
#include "settings.h"
#include "database.h"
#include "mainwindow.h"
#include "proxymanager.h"
static void deleteQImage(QImage *image)
{
delete image;
}
class UpdateThumbnailTask : public QRunnable
{
PlaylistModel *m_model;
Mlt::Producer m_producer;
Mlt::Profile m_profile;
Mlt::Producer *m_tempProducer;
int m_in;
int m_out;
int m_row;
bool m_force;
public:
UpdateThumbnailTask(PlaylistModel *model, Mlt::Producer &producer, int in, int out, int row,
bool force = false)
: QRunnable()
, m_model(model)
, m_producer(producer)
, m_profile("atsc_720p_60")
, m_tempProducer(0)
, m_in(in)
, m_out(out)
, m_row(row)
, m_force(force)
{}
~UpdateThumbnailTask()
{
delete m_tempProducer;
}
Mlt::Producer *tempProducer()
{
if (!m_tempProducer) {
QString service = m_producer.get("mlt_service");
if (service == "avformat-novalidate")
service = "avformat";
else if (service.startsWith("xml"))
service = "xml-nogl";
if (service == "count") {
m_tempProducer = new Mlt::Producer(m_profile, service.toUtf8().constData(), "loader-nogl");
} else if (!Settings.playerGPU() || (service != "xml-nogl" && service != "consumer")) {
m_tempProducer = new Mlt::Producer(m_profile, service.toUtf8().constData(),
m_producer.get("resource"));
}
if (m_tempProducer && m_tempProducer->is_valid()) {
Mlt::Filter scaler(m_profile, "swscale");
Mlt::Filter padder(m_profile, "resize");
Mlt::Filter converter(m_profile, "avcolor_space");
m_tempProducer->attach(scaler);
m_tempProducer->attach(padder);
m_tempProducer->attach(converter);
}
}
return m_tempProducer;
}
QString cacheKey(int frameNumber)
{
QString time = m_producer.frames_to_time(frameNumber, Settings.timeFormat());
// Reduce the precision to centiseconds to increase chance for cache hit
// without much loss of accuracy.
time = time.left(time.size() - 1);
QString key;
QString resource = m_producer.get(kShotcutHashProperty);
if (resource.isEmpty()) {
key = QStringLiteral("%1 %2 %3")
.arg(m_producer.get("mlt_service"))
.arg(m_producer.get("resource"))
.arg(time);
QCryptographicHash hash(QCryptographicHash::Sha1);
hash.addData(key.toUtf8());
key = hash.result().toHex();
} else {
key = QStringLiteral("%1 %2").arg(resource).arg(time);
}
return key;
}
void run()
{
QString setting = Settings.playlistThumbnails();
if (setting == "hidden")
return;
// Scale the in and out point frame numbers to this member profile's fps.
int inPoint = qRound(m_in / MLT.profile().fps() * m_profile.fps());
int outPoint = qRound(m_out / MLT.profile().fps() * m_profile.fps());
QImage image = DB.getThumbnail(cacheKey(inPoint));
if (m_force || image.isNull()) {
image = makeThumbnail(inPoint);
m_producer.set(kThumbnailInProperty, new QImage(image), 0, (mlt_destructor) deleteQImage, NULL);
DB.putThumbnail(cacheKey(inPoint), image);
} else {
m_producer.set(kThumbnailInProperty, new QImage(image), 0, (mlt_destructor) deleteQImage, NULL);
}
m_model->showThumbnail(m_row);
if (setting == "tall" || setting == "wide") {
image = DB.getThumbnail(cacheKey(outPoint));
if (m_force || image.isNull()) {
image = makeThumbnail(outPoint);
m_producer.set(kThumbnailOutProperty, new QImage(image), 0, (mlt_destructor) deleteQImage, NULL);
DB.putThumbnail(cacheKey(outPoint), image);
} else {
m_producer.set(kThumbnailOutProperty, new QImage(image), 0, (mlt_destructor) deleteQImage, NULL);
}
m_model->showThumbnail(m_row);
}
}
QImage makeThumbnail(int frameNumber)
{
int height = PlaylistModel::THUMBNAIL_HEIGHT * 2;
int width = PlaylistModel::THUMBNAIL_WIDTH * 2;
auto producer = tempProducer();
if (producer && producer->is_valid()) {
return MLT.image(*tempProducer(), frameNumber, width, height);
} else {
return QImage();
}
}
signals:
void thumbnailUpdated(int row);
};
PlaylistModel::PlaylistModel(QObject *parent)
: QAbstractTableModel(parent)
, m_playlist(nullptr)
, m_dropRow(-1)
, m_mode(Invalid)
{
qRegisterMetaType<QVector<int> >("QVector<int>");
connect(this, &QAbstractItemModel::rowsAboutToBeRemoved, this,
&PlaylistModel::onRowsAboutToBeRemoved);
}
PlaylistModel::~PlaylistModel()
{
delete m_playlist;
m_playlist = nullptr;
}
int PlaylistModel::rowCount(const QModelIndex & /*parent*/) const
{
return m_playlist ? m_playlist->count() : 0;
}
int PlaylistModel::columnCount(const QModelIndex & /*parent*/) const
{
switch (m_mode) {
case Detailed:
return COLUMN_COUNT;
case Tiled:
case Icons:
case Invalid:
return 1;
}
return 0;
}
QVariant PlaylistModel::data(const QModelIndex &index, int role) const
{
if (!m_playlist)
return QVariant();
int field = role;
if (role < Qt::UserRole) {
if (role == Qt::DisplayRole) {
if (m_mode == Detailed || index.column() > 0)
field = FIELD_INDEX + index.column();
else
field = FIELD_RESOURCE;
} else if (role == Qt::ToolTipRole) {
field = FIELD_RESOURCE;
} else if (role == Qt::DecorationRole) {
if (m_mode == Detailed && index.column() != COLUMN_THUMBNAIL)
return QVariant();
field = FIELD_THUMBNAIL;
} else
return QVariant();
}
QScopedPointer<Mlt::ClipInfo> info(m_playlist->clip_info(index.row()));
if (info)
switch (field) {
case FIELD_INDEX:
return QString::number(index.row() + 1);
case FIELD_RESOURCE: {
QString result;
if (role == Qt::DisplayRole) {
// Prefer caption for display
if (info->producer && info->producer->is_valid()) {
result = info->producer->get(kShotcutCaptionProperty);
if (result.isEmpty()) {
result = Util::baseName(ProxyManager::resource(*info->producer));
if (!::qstrcmp(info->producer->get("mlt_service"), "timewarp")) {
double speed = ::qAbs(info->producer->get_double("warp_speed"));
result = QStringLiteral("%1 (%2x)").arg(result).arg(speed);
}
}
if (result == "<producer>") {
result = QString::fromUtf8(info->producer->get("mlt_service"));
}
if (info->producer->get_int(kIsProxyProperty)) {
result.append("\n" + tr("(PROXY)"));
}
}
} else {
// Prefer detail or full path for tooltip
if (info->producer && info->producer->is_valid()) {
result = info->producer->get(kShotcutDetailProperty);
if (result.isEmpty()) {
result = ProxyManager::resource(*info->producer);
if (!result.isEmpty() && QFileInfo(result).isRelative()) {
QString basePath = QFileInfo(MAIN.fileName()).canonicalPath();
result = QFileInfo(basePath, result).filePath();
}
result = QDir::toNativeSeparators(result);
}
if ((result.isEmpty() || Util::baseName(result) == "<producer>")) {
result = info->producer->get(kShotcutCaptionProperty);
}
if (result.isEmpty()) {
result = QString::fromUtf8(info->producer->get("mlt_service"));
}
}
}
if (!info->producer->get(kShotcutHashProperty)) {
Util::getHash(*info->producer);
}
return result;
}
case FIELD_IN:
if (info->producer && info->producer->is_valid()) {
return QString::fromLatin1(info->producer->frames_to_time(info->frame_in, Settings.timeFormat()));
} else {
return "";
}
case FIELD_DURATION:
if (info->producer && info->producer->is_valid()) {
return QString::fromLatin1(info->producer->frames_to_time(info->frame_count,
Settings.timeFormat()));
} else {
return "";
}
case FIELD_START:
if (info->producer && info->producer->is_valid()) {
return QString::fromLatin1(info->producer->frames_to_time(info->start, Settings.timeFormat()));
} else {
return "";
}
case FIELD_DATE:
if (info->producer && info->producer->is_valid()) {
int64_t ms = info->producer->get_creation_time();
if (!ms) {
return "";
} else {
return QDateTime::fromMSecsSinceEpoch(ms).toString("yyyy-MM-dd HH:mm:ss");
}
} else {
return "";
}
case FIELD_THUMBNAIL: {
QString setting = Settings.playlistThumbnails();
if (setting == "hidden")
return QImage();
QScopedPointer<Mlt::Producer> producer(m_playlist->get_clip(index.row()));
Mlt::Producer parent(producer->get_parent());
int width = THUMBNAIL_WIDTH;
QImage image;
if (setting == "wide")
image = QImage(width * 2, THUMBNAIL_HEIGHT, QImage::Format_ARGB32);
else if (setting == "tall")
image = QImage(width, THUMBNAIL_HEIGHT * 2, QImage::Format_ARGB32);
else if (setting == "large")
image = QImage(width * 2, THUMBNAIL_HEIGHT * 2, QImage::Format_ARGB32);
else
image = QImage(width, THUMBNAIL_HEIGHT, QImage::Format_ARGB32);
if (parent.is_valid() && parent.get_data(kThumbnailInProperty)) {
QPainter painter(&image);
image.fill(QApplication::palette().base().color().rgb());
// draw the in thumbnail
QImage *thumb = (QImage *) parent.get_data(kThumbnailInProperty);
QRect rect = thumb->rect();
if (setting != "large") {
rect.setWidth(width);
rect.setHeight(THUMBNAIL_HEIGHT);
}
painter.drawImage(rect, *thumb);
if ((setting == "wide" || setting == "tall") && parent.get_data(kThumbnailOutProperty)) {
// draw the out thumbnail
thumb = (QImage *) parent.get_data(kThumbnailOutProperty);
if (setting == "wide") {
rect.setWidth(width * 2);
rect.setLeft(width);
} else if (setting == "tall") {
rect.setHeight(THUMBNAIL_HEIGHT * 2);
rect.setTop(THUMBNAIL_HEIGHT);
}
painter.drawImage(rect, *thumb);
}
if (parent.is_valid() && parent.get_int(kPlaylistIndexProperty) == index.row() + 1) {
QPen pen(Qt::red);
pen.setWidthF(1.5 * MAIN.devicePixelRatioF());
painter.setPen(pen);
rect.setX(0);
rect.setY(0);
rect.setWidth(rect.width() - 1);
rect.setHeight(rect.height() - 1);
painter.drawRect(rect);
}
painter.end();
} else {
image.fill(QApplication::palette().base().color().rgb());
}
return image;
}
}
return QVariant();
}
PlaylistModel::ViewMode PlaylistModel::viewMode() const
{
return m_mode;
}
void PlaylistModel::setViewMode(ViewMode mode)
{
if (mode == m_mode)
return;
beginResetModel();
m_mode = mode;
endResetModel();
}
QVariant PlaylistModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (role == Qt::DisplayRole && orientation == Qt::Horizontal) {
switch (section) {
case COLUMN_INDEX:
return tr("#");
case COLUMN_THUMBNAIL:
return tr("Thumbnails");
case COLUMN_RESOURCE:
return tr("Clip");
case COLUMN_IN:
return tr("In");
case COLUMN_DURATION:
return tr("Duration");
case COLUMN_START:
return tr("Start");
case COLUMN_DATE:
return tr("Date");
default:
break;
}
}
return QVariant();
}
Qt::DropActions PlaylistModel::supportedDropActions() const
{
return Qt::CopyAction | Qt::MoveAction | Qt::LinkAction;
}
bool PlaylistModel::insertRows(int row, int count, const QModelIndex &parent)
{
Q_UNUSED(count)
Q_UNUSED(parent)
if (!m_playlist) return false;
if (m_dropRow == -1)
m_dropRow = row;
return true;
}
bool PlaylistModel::removeRows(int row, int count, const QModelIndex &parent)
{
Q_UNUSED(count)
Q_UNUSED(parent)
if (!m_playlist || m_dropRow == -1 ) return false;
if (row < m_dropRow) {
if (!m_rowsRemoved.contains(row)) {
int adjustment = 0;
foreach (int i, m_rowsRemoved) {
if (row > i)
--adjustment;
}
m_rowsRemoved << row;
emit moveClip(row + adjustment, m_dropRow - 1);
}
} else {
if (!m_rowsRemoved.contains(row)) {
foreach (int i, m_rowsRemoved) {
if (row >= i)
++row;
}
}
m_rowsRemoved << m_dropRow;
if (row != m_dropRow)
emit moveClip(row, m_dropRow++);
}
m_dropRow = -1;
return true;
}
bool PlaylistModel::moveRows(const QModelIndex &, int sourceRow, int count, const QModelIndex &,
int destinationChild)
{
Q_ASSERT(count == 1);
move(sourceRow, destinationChild);
return true;
}
void PlaylistModel::sort(int column, Qt::SortOrder order)
{
if (!m_playlist) return;
int index = 0;
int count = rowCount();
if (count < 2) return;
// Create a list mapping values to their original index.
QVector<QPair<QString, int>> indexMap(count);
for (index = 0; index < count; index++) {
QModelIndex modelIndex = createIndex(index, column);
QString key = data(modelIndex, Qt::DisplayRole).toString().toLower();
indexMap[index] = qMakePair(key, index);
}
// Sort the list.
std::sort(indexMap.begin(), indexMap.end());
// Move the sorted indexes into a list to be used to reorder the playlist.
QVector<int> indexList(count);
QVector<QPair<QString, int>>::iterator itr = indexMap.begin();
index = 0;
while (itr != indexMap.end()) {
if (order == Qt::AscendingOrder) {
indexList[index] = itr->second;
} else {
indexList[count - index - 1] = itr->second;
}
index++;
itr++;
}
m_playlist->reorder(indexList.data());
emit dataChanged(createIndex(0, 0), createIndex(rowCount(), columnCount()));
emit modified();
}
QStringList PlaylistModel::mimeTypes() const
{
QStringList ls = QAbstractTableModel::mimeTypes();
ls.append(Mlt::XmlMimeType);
ls.append("text/uri-list");
return ls;
}
QMimeData *PlaylistModel::mimeData(const QModelIndexList &indexes) const
{
QMimeData *mimeData = new QMimeData;
int count = 0;
foreach (auto index, indexes) {
if (index.column()) continue;
count += m_playlist->clip_length(index.row());
}
Mlt::Playlist playlist(MLT.profile());
foreach (auto index, indexes) {
if (index.column()) continue;
QScopedPointer<Mlt::ClipInfo> info(m_playlist->clip_info(index.row()));
if (info && info->producer) {
playlist.append(*info->producer, info->frame_in, info->frame_out);
}
}
mimeData->setData(Mlt::XmlMimeType, MLT.XML(&playlist).toUtf8());
mimeData->setText(QString::number(count));
return mimeData;
}
bool PlaylistModel::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column,
const QModelIndex &parent)
{
Q_UNUSED(column)
Q_UNUSED(parent)
// Internal reorder
if (action == Qt::MoveAction && !data->hasUrls()) {
m_dropRow = row;
m_rowsRemoved.clear();
return true;
}
// Dragged from player or file manager
else if (data->hasFormat(Mlt::XmlMimeType) || data->hasUrls()) {
emit dropped(data, row);
return true;
}
// Dragged from Recent dock
else if (data->hasFormat("application/x-qabstractitemmodeldatalist")) {
QByteArray encoded = data->data("application/x-qabstractitemmodeldatalist");
QDataStream stream(&encoded, QIODevice::ReadOnly);
QMap<int, QVariant> roleDataMap;
while (!stream.atEnd()) {
int row, col;
stream >> row >> col >> roleDataMap;
}
if (roleDataMap.contains(Qt::ToolTipRole)) {
QMimeData *mimeData = new QMimeData;
QList<QUrl> urls;
// DisplayRole is just basename, ToolTipRole contains full path
urls.append(roleDataMap[Qt::ToolTipRole].toUrl());
mimeData->setUrls(urls);
emit dropped(mimeData, row);
return true;
}
}
return false;
}
Qt::ItemFlags PlaylistModel::flags(const QModelIndex &index) const
{
Qt::ItemFlags defaults = QAbstractTableModel::flags(index);
if (index.isValid())
return Qt::ItemIsDragEnabled | defaults;
else
return Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled | defaults;
}
QModelIndex PlaylistModel::incrementIndex(const QModelIndex &index) const
{
if (index.row() + 1 < rowCount())
return createIndex(index.row() + 1, index.column());
else
return QModelIndex();
}
QModelIndex PlaylistModel::decrementIndex(const QModelIndex &index) const
{
if (index.row() > 0)
return createIndex(index.row() - 1, index.column());
else
return QModelIndex();
}
QModelIndex PlaylistModel::createIndex(int row, int column) const
{
return QAbstractTableModel::createIndex(row, column);
}
void PlaylistModel::clear()
{
if (!m_playlist) return;
if (rowCount()) {
beginRemoveRows(QModelIndex(), 0, rowCount() - 1);
m_playlist->clear();
endRemoveRows();
}
emit cleared();
}
void PlaylistModel::load()
{
if (m_playlist) {
if (rowCount()) {
beginRemoveRows(QModelIndex(), 0, rowCount() - 1);
m_playlist->clear();
endRemoveRows();
}
delete m_playlist;
}
// In some versions of MLT, the resource property is the XML filename,
// but the Mlt::Playlist(Service&) constructor will fail unless it detects
// the type as playlist, and mlt_service_identify() needs the resource
// property to say "<playlist>" to identify it as playlist type.
MLT.producer()->set("mlt_type", "mlt_producer");
MLT.producer()->set("resource", "<playlist>");
m_playlist = new Mlt::Playlist(*MLT.producer());
if (!m_playlist->is_valid()) {
delete m_playlist;
m_playlist = nullptr;
return;
}
if (m_playlist->count() > 0) {
beginInsertRows(QModelIndex(), 0, m_playlist->count() - 1);
endInsertRows();
}
// do not let opening a clip change the profile!
MLT.profile().set_explicit(true);
emit loaded();
}
void PlaylistModel::append(Mlt::Producer &producer, bool emitModified)
{
createIfNeeded();
int count = m_playlist->count();
int in = producer.get_in();
int out = producer.get_out();
producer.set_in_and_out(0, producer.get_length() - 1);
QThreadPool::globalInstance()->start(
new UpdateThumbnailTask(this, producer, in, out, count), 1);
beginInsertRows(QModelIndex(), count, count);
m_playlist->append(producer, in, out);
endInsertRows();
if (emitModified)
emit modified();
}
void PlaylistModel::insert(Mlt::Producer &producer, int row)
{
createIfNeeded();
int in = producer.get_in();
int out = producer.get_out();
producer.set_in_and_out(0, producer.get_length() - 1);
QThreadPool::globalInstance()->start(
new UpdateThumbnailTask(this, producer, in, out, row), 1);
beginInsertRows(QModelIndex(), row, row);
m_playlist->insert(producer, row, in, out);
endInsertRows();
emit modified();
}
void PlaylistModel::remove(int row)
{
if (!m_playlist) return;
beginRemoveRows(QModelIndex(), row, row);
m_playlist->remove(row);
endRemoveRows();
if (m_playlist->count() == 0)
emit cleared();
else
emit modified();
}
void PlaylistModel::update(int row, Mlt::Producer &producer, bool copyFilters)
{
if (!m_playlist) return;
int in = producer.get_in();
int out = producer.get_out();
producer.set_in_and_out(0, producer.get_length() - 1);
QThreadPool::globalInstance()->start(
new UpdateThumbnailTask(this, producer, in, out, row), 1);
if (copyFilters) {
Mlt::Producer oldClip(m_playlist->get_clip(row));
Q_ASSERT(oldClip.is_valid());
Mlt::Controller::copyFilters(oldClip.parent(), producer);
Mlt::Controller::adjustFilters(producer);
}
m_playlist->remove(row);
m_playlist->insert(producer, row, in, out);
emit dataChanged(createIndex(row, 0), createIndex(row, columnCount()));
emit modified();
}
void PlaylistModel::updateThumbnails(int row)
{
if (!m_playlist) return;
QScopedPointer<Mlt::ClipInfo> info(m_playlist->clip_info(row));
if (!info || !info->producer->is_valid()) return;
QThreadPool::globalInstance()->start(
new UpdateThumbnailTask(this, *info->producer, info->frame_in, info->frame_out, row,
true /* force */), 1);
}
void PlaylistModel::appendBlank(int frames)
{
createIfNeeded();
int count = m_playlist->count();
beginInsertRows(QModelIndex(), count, count);
m_playlist->blank(frames - 1);
endInsertRows();
emit modified();
}
void PlaylistModel::insertBlank(int frames, int row)
{
createIfNeeded();
beginInsertRows(QModelIndex(), row, row);
m_playlist->insert_blank(row, frames - 1);
endInsertRows();
emit modified();
}
void PlaylistModel::close()
{
if (!m_playlist) return;
clear();
delete m_playlist;
m_playlist = nullptr;
emit closed();
}
void PlaylistModel::move(int from, int to)
{
if (!m_playlist) return;
m_playlist->move(from, to);
emit dataChanged(createIndex(from, 0), createIndex(from, columnCount()));
emit dataChanged(createIndex(to, 0), createIndex(to, columnCount()));
emit modified();
}
void PlaylistModel::onRowsAboutToBeRemoved(const QModelIndex &parent, int first, int last)
{
if (m_playlist) {
for (int i = first; i <= last; ++i) {
emit removing(m_playlist->get_clip(i));
}
}
}
void PlaylistModel::createIfNeeded()
{
if (!m_playlist) {
m_playlist = new Mlt::Playlist(MLT.profile());
// do not let opening a clip change the profile!
MLT.profile().set_explicit(true);
emit created();
}
}
void PlaylistModel::showThumbnail(int row)
{
emit dataChanged(createIndex(row, 0), createIndex(row, columnCount()));
}
void PlaylistModel::refreshThumbnails()
{
if (m_playlist && m_playlist->is_valid()) {
for (int i = 0; i < m_playlist->count(); i++) {
Mlt::ClipInfo *info = m_playlist->clip_info(i);
if (info && info->producer && info->producer->is_valid()) {
QThreadPool::globalInstance()->start(
new UpdateThumbnailTask(this, *info->producer, info->frame_in, info->frame_out, i), 1);
}
delete info;
}
}
}
void PlaylistModel::setPlaylist(Mlt::Playlist &playlist)
{
if (playlist.is_valid()) {
if (m_playlist) {
if (rowCount()) {
beginRemoveRows(QModelIndex(), 0, rowCount() - 1);
m_playlist->clear();
endRemoveRows();
}
delete m_playlist;
}
m_playlist = new Mlt::Playlist(playlist);
if (!m_playlist->is_valid()) {
delete m_playlist;
m_playlist = 0;
return;
}
if (m_playlist->count() > 0) {
beginInsertRows(QModelIndex(), 0, m_playlist->count() - 1);
endInsertRows();
}
// do not let opening a clip change the profile!
MLT.profile().set_explicit(true);
if (Settings.playerGPU() && Settings.playlistThumbnails() != "hidden")
refreshThumbnails();
emit loaded();
}
}
void PlaylistModel::setInOut(int row, int in, int out)
{
if (!m_playlist || row < 0 || row >= m_playlist->count()) return;
bool inChanged = false, outChanged = false;
QScopedPointer<Mlt::ClipInfo> info(m_playlist->clip_info(row));
if (info && info->producer && info->producer->is_valid()) {
if (MLT.producer()->get_producer() == info->producer->get_producer()) {
inChanged = info->frame_in != in;
outChanged = info->frame_out != out;
}
m_playlist->resize_clip(row, in, out);
QThreadPool::globalInstance()->start(
new UpdateThumbnailTask(this, *info->producer, in, out, row), 1);
emit dataChanged(createIndex(row, COLUMN_IN), createIndex(row, COLUMN_START));
emit modified();
if (inChanged) emit this->inChanged(in);
if (outChanged) emit this->outChanged(out);
}
}
| 27,952
|
C++
|
.cpp
| 772
| 27.392487
| 114
| 0.578794
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,195
|
colorbarswidget.cpp
|
mltframework_shotcut/src/widgets/colorbarswidget.cpp
|
/*
* Copyright (c) 2012-2019 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "shotcut_mlt_properties.h"
#include "colorbarswidget.h"
#include "ui_colorbarswidget.h"
#include "util.h"
#include "mltcontroller.h"
#include <MltProfile.h>
static const char *kParamType = "0";
static const char *kParamAspect = "1";
enum {
ASPECT_SQUARE = 0,
ASPECT_PAL,
ASPECT_PAL_WIDE,
ASPECT_NTSC,
ASPECT_NTSC_WIDE,
ASPECT_HDV
};
ColorBarsWidget::ColorBarsWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::ColorBarsWidget)
{
ui->setupUi(this);
ui->comboBox->setCurrentIndex(4);
Util::setColorsToHighlight(ui->label_2);
}
ColorBarsWidget::~ColorBarsWidget()
{
delete ui;
}
static double map_value_backward(double v, double min, double max)
{
return (v - min) / (max - min);
}
Mlt::Producer *ColorBarsWidget::newProducer(Mlt::Profile &profile)
{
Mlt::Producer *p = new Mlt::Producer(profile, "frei0r.test_pat_B");
p->set(kParamType, ui->comboBox->currentIndex());
if (profile.sample_aspect_num() == 16 && profile.sample_aspect_den() == 15)
p->set(kParamAspect, map_value_backward(ASPECT_PAL, 0, 6.9999));
else if (profile.sample_aspect_num() == 64 && profile.sample_aspect_den() == 45)
p->set(kParamAspect, map_value_backward(ASPECT_PAL_WIDE, 0, 6.9999));
else if (profile.sample_aspect_num() == 8 && profile.sample_aspect_den() == 9)
p->set(kParamAspect, map_value_backward(ASPECT_NTSC, 0, 6.9999));
else if (profile.sample_aspect_num() == 32 && profile.sample_aspect_den() == 27)
p->set(kParamAspect, map_value_backward(ASPECT_NTSC_WIDE, 0, 6.9999));
else if (profile.sample_aspect_num() == 4 && profile.sample_aspect_den() == 3)
p->set(kParamAspect, map_value_backward(ASPECT_HDV, 0, 6.9999));
MLT.setDurationFromDefault(p);
p->set(kShotcutCaptionProperty, ui->comboBox->currentText().toUtf8().constData());
p->set(kShotcutDetailProperty, ui->comboBox->currentText().toUtf8().constData());
return p;
}
Mlt::Properties ColorBarsWidget::getPreset() const
{
Mlt::Properties p;
p.set(kParamType, ui->comboBox->currentIndex());
return p;
}
void ColorBarsWidget::loadPreset(Mlt::Properties &p)
{
ui->comboBox->setCurrentIndex(p.get_int(kParamType));
}
void ColorBarsWidget::on_comboBox_activated(int index)
{
if (m_producer) {
m_producer->set(kParamType, index);
m_producer->set(kShotcutCaptionProperty, ui->comboBox->currentText().toUtf8().constData());
m_producer->set(kShotcutDetailProperty, ui->comboBox->currentText().toUtf8().constData());
emit producerChanged(producer());
}
}
| 3,295
|
C++
|
.cpp
| 86
| 34.790698
| 99
| 0.707409
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
13,196
|
newprojectfolder.cpp
|
mltframework_shotcut/src/widgets/newprojectfolder.cpp
|
/*
* Copyright (c) 2018-2024 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "newprojectfolder.h"
#include "ui_newprojectfolder.h"
#include "settings.h"
#include "mainwindow.h"
#include "util.h"
#include "dialogs/customprofiledialog.h"
#include "dialogs/listselectiondialog.h"
#include "qmltypes/qmlapplication.h"
#include <Logger.h>
#include <QDir>
#include <QFileDialog>
#include <QFileInfo>
#include <QMessageBox>
#include <QListWidgetItem>
#include <QActionGroup>
NewProjectFolder::NewProjectFolder(QWidget *parent) :
QWidget(parent),
ui(new Ui::NewProjectFolder),
m_isOpening(false)
{
ui->setupUi(this);
setColors();
ui->actionProfileAutomatic->setData(QString());
ui->recentListView->setModel(&m_model);
m_profileGroup = new QActionGroup(this);
connect(m_profileGroup, SIGNAL(triggered(QAction *)), SLOT(onProfileTriggered(QAction *)));
ui->label->setToolTip(ui->projectsFolderButton->toolTip());
ui->label_2->setToolTip(ui->projectNameLineEdit->toolTip());
}
NewProjectFolder::~NewProjectFolder()
{
delete ui;
}
void NewProjectFolder::showEvent(QShowEvent *)
{
QString external = Settings.playerExternal();
bool ok = false;
external.toInt(&ok);
m_profile = Settings.playerProfile();
// Automatic not permitted for SDI/HDMI
if (!external.isEmpty() && !ok && m_profile.isEmpty())
m_profile = "atsc_720p_50";
bool found = false;
foreach (QAction *a, MAIN.profileGroup()->actions()) {
if (a->data().toString() == m_profile) {
ui->videoModeButton->setText(a->text());
found = true;
break;
}
}
if (!found)
ui->videoModeButton->setText(ui->actionProfileAutomatic->text());
// Update Video Mode menu.
m_videoModeMenu.clear();
if (external.isEmpty() || ok) {
m_profileGroup->addAction(ui->actionProfileAutomatic);
m_videoModeMenu.addAction(ui->actionProfileAutomatic);
}
MAIN.buildVideoModeMenu(&m_videoModeMenu, m_customProfileMenu, m_profileGroup,
ui->actionAddCustomProfile, ui->actionProfileRemove);
// Check the current menu item.
foreach (QAction *a, m_profileGroup->actions()) {
if (a->data().toString() == m_profile) {
LOG_DEBUG() << "m_profile" << m_profile << "action.data" << a->data().toString();
a->setChecked(true);
break;
}
}
updateRecentProjects();
setProjectFolderButtonText(Settings.projectsFolder());
}
void NewProjectFolder::hideEvent(QHideEvent *)
{
ui->projectNameLineEdit->setText(QString());
}
bool NewProjectFolder::event(QEvent *event)
{
bool result = QWidget::event(event);
if (event->type() == QEvent::PaletteChange)
setColors();
return result;
}
void NewProjectFolder::updateRecentProjects()
{
m_model.clear();
for (auto &s : Settings.projects()) {
if (!s.isEmpty()) {
QStandardItem *item = new QStandardItem(Util::baseName(s));
item->setToolTip(QDir::toNativeSeparators(s));
m_model.appendRow(item);
}
}
}
void NewProjectFolder::on_projectsFolderButton_clicked()
{
QString dirName = QFileDialog::getExistingDirectory(this, tr("Projects Folder"),
Settings.projectsFolder(),
Util::getFileDialogOptions());
if (!dirName.isEmpty()) {
setProjectFolderButtonText(dirName);
Settings.setProjectsFolder(dirName);
}
}
void NewProjectFolder::on_videoModeButton_clicked()
{
m_videoModeMenu.exec(ui->videoModeButton->mapToGlobal(QPoint(0, 0)));
}
void NewProjectFolder::onProfileTriggered(QAction *action)
{
m_profile = action->data().toString();
ui->videoModeButton->setText(action->text());
}
void NewProjectFolder::on_actionAddCustomProfile_triggered()
{
CustomProfileDialog dialog(this);
dialog.setWindowModality(QmlApplication::dialogModality());
if (dialog.exec() == QDialog::Accepted) {
QString name = dialog.profileName();
if (!name.isEmpty()) {
ui->videoModeButton->setText(name);
MAIN.addCustomProfile(name, m_customProfileMenu, ui->actionProfileRemove, m_profileGroup);
MAIN.addCustomProfile(name, MAIN.customProfileMenu(), MAIN.actionProfileRemove(),
MAIN.profileGroup());
} else if (m_profileGroup->checkedAction()) {
ui->videoModeButton->setText(tr("Custom"));
m_profileGroup->checkedAction()->setChecked(false);
MAIN.profileGroup()->checkedAction()->setChecked(false);
}
// Use the new profile.
emit MAIN.profileChanged();
}
}
void NewProjectFolder::on_actionProfileRemove_triggered()
{
QDir dir(Settings.appDataLocation());
if (dir.cd("profiles")) {
// Setup the dialog.
QStringList profiles = dir.entryList(QDir::Files | QDir::NoDotAndDotDot | QDir::Readable);
ListSelectionDialog dialog(profiles, this);
dialog.setWindowModality(QmlApplication::dialogModality());
dialog.setWindowTitle(tr("Remove Video Mode"));
// Show the dialog.
if (dialog.exec() == QDialog::Accepted) {
MAIN.removeCustomProfiles(dialog.selection(), dir, m_customProfileMenu, ui->actionProfileRemove);
MAIN.removeCustomProfiles(dialog.selection(), dir, MAIN.customProfileMenu(),
MAIN.actionProfileRemove());
if (dialog.selection().indexOf(ui->videoModeButton->text()) >= 0) {
ui->actionProfileAutomatic->setChecked(true);
ui->videoModeButton->setText(ui->actionProfileAutomatic->text());
}
}
}
}
void NewProjectFolder::on_startButton_clicked()
{
QDir dir(Settings.projectsFolder());
QString projectName = m_projectName;
QString fileName = projectName;
if (projectName.contains('/') || projectName.contains('\\')) {
QMessageBox::warning(this, ui->newProjectLabel->text(),
tr("The project name cannot include a slash."));
ui->startButton->setDisabled(true);
return;
}
if (projectName.endsWith(".mlt"))
projectName = projectName.mid(0, projectName.length() - 4);
else
fileName += ".mlt";
// Check if the project folder exists.
if (dir.cd(projectName)) {
// Check if the project file exists.
if (dir.exists(fileName)) {
QMessageBox::warning(this, ui->newProjectLabel->text(),
tr("There is already a project with that name.\n"
"Try again with a different name."));
return;
}
} else {
// Create the project folder if needed.
if (!dir.mkpath(projectName)) {
QMessageBox::warning(this, ui->newProjectLabel->text(),
tr("Unable to create folder %1\n"
"Perhaps you do not have permission.\n"
"Try again with a different folder.").arg(projectName));
return;
}
dir.cd(projectName);
}
// Create the project file.
QFileInfo info(dir.absolutePath(), fileName);
if (Util::warnIfNotWritable(info.absoluteFilePath(), this, ui->newProjectLabel->text()))
return;
MAIN.newProject(info.absoluteFilePath(), true);
// Change the video mode.
if (m_profileGroup->checkedAction()) {
Settings.setPlayerProfile(m_profile);
MAIN.setProfile(m_profile);
foreach (QAction *a, MAIN.profileGroup()->actions()) {
if (a->data().toString() == m_profile) {
a->setChecked(true);
break;
}
}
}
hide();
}
void NewProjectFolder::on_projectNameLineEdit_textChanged(const QString &arg1)
{
m_projectName = arg1.trimmed();
ui->startButton->setDisabled(arg1.isEmpty());
}
void NewProjectFolder::on_recentListView_clicked(const QModelIndex &index)
{
if (!m_isOpening) {
m_isOpening = true;
auto data = m_model.itemData(index);
MAIN.open(data[Qt::ToolTipRole].toString());
m_isOpening = false;
}
}
void NewProjectFolder::setColors()
{
QPalette palette = ui->frame->palette();
palette.setColor(QPalette::WindowText, QPalette().color(QPalette::Highlight));
ui->frame->setPalette(palette);
ui->frame_2->setPalette(palette);
palette.setColor(QPalette::WindowText, QPalette().color(QPalette::WindowText));
ui->widget->setPalette(palette);
ui->widget_2->setPalette(palette);
Util::setColorsToHighlight(ui->newProjectLabel);
Util::setColorsToHighlight(ui->newProjectLabel_2);
}
void NewProjectFolder::setProjectFolderButtonText(const QString &text)
{
auto path = QDir::toNativeSeparators(text);
QString elidedText = ui->projectsFolderButton->fontMetrics().elidedText(path, Qt::ElideLeft,
ui->recentListView->width() / 1.5);
ui->projectsFolderButton->setText(elidedText);
if (path != elidedText)
ui->projectsFolderButton->setToolTip(path);
else
ui->projectsFolderButton->setToolTip(ui->label->toolTip());
}
void NewProjectFolder::on_recentListView_doubleClicked(const QModelIndex &index)
{
on_recentListView_clicked(index);
}
void NewProjectFolder::on_recentListView_customContextMenuRequested(const QPoint &pos)
{
if (ui->recentListView->currentIndex().isValid()) {
QMenu menu(this);
menu.addAction(ui->actionRecentRemove);
menu.exec(ui->recentListView->mapToGlobal(pos));
}
}
void NewProjectFolder::on_actionRecentRemove_triggered()
{
if (ui->recentListView->currentIndex().isValid()) {
auto index = ui->recentListView->currentIndex();
auto data = m_model.itemData(index);
auto projects = Settings.projects();
auto url = data[Qt::ToolTipRole].toString();
url = QDir::fromNativeSeparators(url);
if (projects.removeAll(url) > 0) {
m_model.removeRow(index.row());
Settings.setProjects(projects);
emit deletedProject(url);
} else {
LOG_WARNING() << "Failed to remove project" << url;
}
}
}
| 11,064
|
C++
|
.cpp
| 288
| 31.104167
| 111
| 0.648231
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,197
|
servicepresetwidget.cpp
|
mltframework_shotcut/src/widgets/servicepresetwidget.cpp
|
/*
* Copyright (c) 2012-2020 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "servicepresetwidget.h"
#include "ui_servicepresetwidget.h"
#include "qmltypes/qmlapplication.h"
#include "settings.h"
#include <Logger.h>
#include <QDir>
#include <QInputDialog>
#include <QMessageBox>
ServicePresetWidget::ServicePresetWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::ServicePresetWidget),
m_widgetName(parent->objectName())
{
ui->setupUi(this);
}
ServicePresetWidget::~ServicePresetWidget()
{
delete ui;
}
// This should be called after saveDefaultPreset()
void ServicePresetWidget::loadPresets()
{
// build the presets combo
ui->presetCombo->clear();
QDir dir(Settings.appDataLocation());
if (dir.cd("presets")) {
ui->presetCombo->addItems(dir.entryList(QDir::Files));
QStringList entries = dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::Executable);
foreach (QString s, entries) {
if (s == m_widgetName && dir.cd(s)) {
ui->presetCombo->addItem("", "");
QStringList entries2 = dir.entryList(QDir::Files | QDir::Readable);
foreach (QString s2, entries2)
ui->presetCombo->addItem(s2);
dir.cdUp();
}
}
}
}
static void saveProperties(const Mlt::Properties &properties, const QString &filePath)
{
// Save properties as YAML to file.
char *yamlStr = const_cast<Mlt::Properties &>(properties).serialise_yaml();
QString yaml = yamlStr;
free(yamlStr);
QFile yamlFile(filePath);
if (!yamlFile.open(QIODevice::WriteOnly)) {
LOG_ERROR() << "Failed to save preset: " << filePath;
} else {
yamlFile.write(yaml.toUtf8());
yamlFile.close();
}
}
void ServicePresetWidget::saveDefaultPreset(const Mlt::Properties &properties)
{
savePreset(properties, tr("(defaults)"));
}
void ServicePresetWidget::savePreset(const Mlt::Properties &properties)
{
QInputDialog dialog(this);
dialog.setInputMode(QInputDialog::TextInput);
dialog.setWindowTitle(tr("Save Preset"));
dialog.setLabelText(tr("Name:"));
dialog.setWindowModality(QmlApplication::dialogModality());
int r = dialog.exec();
QString preset = dialog.textValue();
if (r == QDialog::Accepted && !preset.isEmpty()) {
QDir dir(Settings.appDataLocation());
if (!dir.exists())
dir.mkpath(dir.path());
if (!dir.cd("presets")) {
if (dir.mkdir("presets"))
dir.cd("presets");
}
if (!dir.cd(m_widgetName)) {
if (dir.mkdir(m_widgetName))
dir.cd(m_widgetName);
}
saveProperties(properties, dir.filePath(preset));
// add the preset and select it
loadPresets();
for (int i = 0; i < ui->presetCombo->count(); i++) {
if (ui->presetCombo->itemText(i) == preset) {
ui->presetCombo->setCurrentIndex(i);
break;
}
}
}
}
void ServicePresetWidget::savePreset(const Mlt::Properties &properties, QString name)
{
QDir dir(Settings.appDataLocation());
if (!dir.exists())
dir.mkpath(dir.path());
if (!dir.cd("presets")) {
if (dir.mkdir("presets"))
dir.cd("presets");
}
if (!dir.cd(m_widgetName)) {
if (dir.mkdir(m_widgetName))
dir.cd(m_widgetName);
}
saveProperties(properties, dir.filePath(name));
}
void ServicePresetWidget::on_presetCombo_activated(int index)
{
QString preset = ui->presetCombo->itemText(index);
QDir dir(Settings.appDataLocation());
Mlt::Properties *properties;
if (!dir.cd("presets") || !dir.cd(m_widgetName))
return;
// Detect the preset file format
bool isYaml = false;
QFile presetFile(dir.filePath(preset));
if (presetFile.open(QIODevice::ReadOnly)) {
isYaml = (presetFile.readLine(4) == "---");
presetFile.close();
}
if (isYaml) {
// Load from YAML file.
properties = Mlt::Properties::parse_yaml(dir.filePath(preset).toUtf8().constData());
} else {
// Load from legacy preset file.
properties = new Mlt::Properties;
properties->load(dir.filePath(preset).toUtf8().constData());
}
emit selected(properties);
}
void ServicePresetWidget::on_savePresetButton_clicked()
{
emit saveClicked();
}
void ServicePresetWidget::on_deletePresetButton_clicked()
{
QString preset = ui->presetCombo->currentText();
QMessageBox dialog(QMessageBox::Question,
tr("Delete Preset"),
tr("Are you sure you want to delete %1?").arg(preset),
QMessageBox::No | QMessageBox::Yes,
this);
dialog.setDefaultButton(QMessageBox::Yes);
dialog.setEscapeButton(QMessageBox::No);
dialog.setWindowModality(QmlApplication::dialogModality());
int result = dialog.exec();
if (result == QMessageBox::Yes) {
QDir dir(Settings.appDataLocation());
if (dir.cd("presets") && dir.cd(m_widgetName))
QFile(dir.filePath(preset)).remove();
ui->presetCombo->removeItem(ui->presetCombo->currentIndex());
ui->presetCombo->setCurrentIndex(0);
}
}
| 5,936
|
C++
|
.cpp
| 168
| 29.041667
| 98
| 0.647407
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
13,198
|
toneproducerwidget.cpp
|
mltframework_shotcut/src/widgets/toneproducerwidget.cpp
|
/*
* Copyright (c) 2015-2020 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "shotcut_mlt_properties.h"
#include "toneproducerwidget.h"
#include "ui_toneproducerwidget.h"
#include "util.h"
#include <MltProfile.h>
ToneProducerWidget::ToneProducerWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::ToneProducerWidget)
{
ui->setupUi(this);
Util::setColorsToHighlight(ui->nameLabel);
ui->preset->saveDefaultPreset(getPreset());
ui->preset->loadPresets();
}
ToneProducerWidget::~ToneProducerWidget()
{
delete ui;
}
Mlt::Producer *ToneProducerWidget::newProducer(Mlt::Profile &profile)
{
Mlt::Producer *p = new Mlt::Producer(profile, "tone:");
p->set("frequency", ui->frequencySpinBox->value());
p->set("level", ui->levelSpinBox->value());
p->set(kShotcutCaptionProperty, ui->nameLabel->text().toUtf8().constData());
p->set(kShotcutDetailProperty, detail().toUtf8().constData());
return p;
}
Mlt::Properties ToneProducerWidget::getPreset() const
{
Mlt::Properties p;
p.set("frequency", ui->frequencySpinBox->value());
p.set("level", ui->levelSpinBox->value());
return p;
}
void ToneProducerWidget::loadPreset(Mlt::Properties &p)
{
ui->frequencySpinBox->setValue(p.get_int("frequency"));
ui->levelSpinBox->setValue(p.get_int("level"));
p.set(kShotcutDetailProperty, detail().toUtf8().constData());
}
void ToneProducerWidget::on_frequencySpinBox_valueChanged(int value)
{
if (m_producer) {
m_producer->set("frequency", value);
m_producer->set(kShotcutDetailProperty, detail().toUtf8().constData());
emit modified();
}
}
void ToneProducerWidget::on_levelSpinBox_valueChanged(int value)
{
if (m_producer) {
m_producer->set("level", value);
m_producer->set(kShotcutDetailProperty, detail().toUtf8().constData());
emit modified();
}
}
void ToneProducerWidget::on_preset_selected(void *p)
{
Mlt::Properties *properties = (Mlt::Properties *) p;
loadPreset(*properties);
delete properties;
}
void ToneProducerWidget::on_preset_saveClicked()
{
ui->preset->savePreset(getPreset());
}
QString ToneProducerWidget::detail() const
{
return tr("Tone: %1Hz %2dB").arg(ui->frequencySpinBox->value()).arg(
ui->levelSpinBox->value());
}
| 2,934
|
C++
|
.cpp
| 87
| 30.367816
| 80
| 0.717207
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,199
|
directshowvideowidget.cpp
|
mltframework_shotcut/src/widgets/directshowvideowidget.cpp
|
/*
* Copyright (c) 2014-2022 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "directshowvideowidget.h"
#include "ui_directshowvideowidget.h"
#include "mltcontroller.h"
#include "util.h"
#include "shotcut_mlt_properties.h"
#include "settings.h"
#include <Logger.h>
#include <QString>
#include <QDir>
#include <QFileInfo>
#include <QProcess>
#include <QRegularExpression>
DirectShowVideoWidget::DirectShowVideoWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::DirectShowVideoWidget)
{
ui->setupUi(this);
Util::setColorsToHighlight(ui->label);
#ifdef Q_OS_WIN
QFileInfo ffmpegPath(qApp->applicationDirPath(), "ffmpeg");
QProcess proc;
QStringList args;
args << "-hide_banner" << "-list_devices" << "true" << "-f" << "dshow" << "-i" << "dummy";
LOG_DEBUG() << ffmpegPath.absoluteFilePath() << args;
proc.setStandardOutputFile(QProcess::nullDevice());
proc.setReadChannel(QProcess::StandardError);
proc.start(ffmpegPath.absoluteFilePath(), args, QIODevice::ReadOnly);
bool started = proc.waitForStarted(2000);
bool finished = false;
QCoreApplication::processEvents();
if (started) {
finished = proc.waitForFinished(4000);
QCoreApplication::processEvents();
}
bool isVideo = true;
QString description;
QString name;
auto currentVideo = 1;
auto currentAudio = 1;
if (started && finished && proc.exitStatus() == QProcess::NormalExit) {
QString output = proc.readAll();
foreach (const QString &line, output.split(QRegularExpression("[\r\n]"), Qt::SkipEmptyParts)) {
auto i = line.indexOf("] \"");
if (i > -1) {
auto j = line.indexOf("\" (");
if (j > -1) {
description = line.mid(i + 3, j - i - 3);
isVideo = line.mid(j + 3).startsWith("video");
}
} else {
QString s("] Alternative name \"");
i = line.indexOf(s);
if (i > -1) {
name = line.mid(i + s.size()).replace('\"', "");
LOG_DEBUG() << (isVideo ? "video" : "audio") << description << name;
if (isVideo) {
if (Settings.videoInput() == name) {
currentVideo = ui->videoCombo->count();
}
ui->videoCombo->addItem(description, name);
} else {
if (Settings.audioInput() == name) {
currentAudio = ui->audioCombo->count();
}
ui->audioCombo->addItem(description, name);
}
}
}
}
}
if (ui->videoCombo->count() > 1)
ui->videoCombo->setCurrentIndex(currentVideo);
if (ui->audioCombo->count() > 1)
ui->audioCombo->setCurrentIndex(currentAudio);
#endif
}
DirectShowVideoWidget::~DirectShowVideoWidget()
{
delete ui;
}
Mlt::Producer *DirectShowVideoWidget::newProducer(Mlt::Profile &profile)
{
Mlt::Producer *p = 0;
if (ui->videoCombo->currentIndex() > 0) {
LOG_DEBUG() << ui->videoCombo->currentData().toString();
p = new Mlt::Producer(profile, QStringLiteral("dshow:video=%1")
.arg(ui->videoCombo->currentData().toString())
.toUtf8().constData());
}
if (ui->audioCombo->currentIndex() > 0) {
Mlt::Producer *audio = new Mlt::Producer(profile,
QStringLiteral("dshow:audio=%1").arg(ui->audioCombo->currentData().toString())
.toLatin1().constData());
if (p && p->is_valid() && audio->is_valid()) {
Mlt::Tractor *tractor = new Mlt::Tractor;
tractor->set("_profile", profile.get_profile(), 0);
tractor->set("resource1", p->get("resource"));
tractor->set("resource2", audio->get("resource"));
tractor->set_track(*p, 0);
delete p;
tractor->set_track(*audio, 1);
delete audio;
p = tractor;
} else {
p = audio;
}
}
if (!p || !p->is_valid()) {
delete p;
p = new Mlt::Producer(profile, "color:");
if (ui->videoCombo->currentIndex() > 0) {
p->set("resource", QStringLiteral("dshow:video=%1")
.arg(ui->videoCombo->currentData().toString())
.toUtf8().constData());
}
if (ui->audioCombo->currentIndex() > 0) {
QString resource = QStringLiteral("dshow:audio=%1").arg(ui->audioCombo->currentData().toString());
if (ui->videoCombo->currentIndex() > 0) {
p->set("resource2", resource.toUtf8().constData());
} else {
p->set("resource", resource.toUtf8().constData());
}
}
p->set("error", 1);
}
p->set("force_seekable", 0);
p->set(kBackgroundCaptureProperty, 1);
p->set(kShotcutCaptionProperty, tr("Audio/Video Device").toUtf8().constData());
if (ui->audioCombo->currentIndex() > 0) {
Settings.setAudioInput(ui->audioCombo->currentData().toString());
}
if (ui->videoCombo->currentIndex() > 0) {
Settings.setVideoInput(ui->videoCombo->currentData().toString());
}
return p;
}
void DirectShowVideoWidget::setProducer(Mlt::Producer *producer)
{
QString resource = producer->get("resource1") ? QString(producer->get("resource1")) : QString(
producer->get("resource"));
QString resource2 = QString(producer->get("resource2"));
LOG_DEBUG() << "resource" << resource;
LOG_DEBUG() << "resource2" << resource2;
const char *videoDevice = "dshow:video=";
const char *audioDevice = "dshow:audio=";
ui->videoCombo->setCurrentIndex(0);
ui->audioCombo->setCurrentIndex(0);
if (resource.startsWith(videoDevice)) {
auto name = resource.mid(qstrlen(videoDevice));
for (int i = 1; i < ui->videoCombo->count(); i++) {
if (ui->videoCombo->itemData(i).toString() == name) {
ui->videoCombo->setCurrentIndex(i);
break;
}
}
} else if (resource.startsWith(audioDevice)) {
auto name = resource.mid(qstrlen(audioDevice));
for (int i = 1; i < ui->audioCombo->count(); i++) {
if (ui->audioCombo->itemData(i).toString() == name) {
ui->audioCombo->setCurrentIndex(i);
break;
}
}
}
if (resource2.startsWith(audioDevice)) {
auto name = resource2.mid(qstrlen(audioDevice));
for (int i = 1; i < ui->audioCombo->count(); i++) {
if (ui->audioCombo->itemData(i).toString() == name) {
ui->audioCombo->setCurrentIndex(i);
break;
}
}
}
AbstractProducerWidget::setProducer(producer);
}
void DirectShowVideoWidget::on_videoCombo_activated(int index)
{
Q_UNUSED(index)
if (m_producer) {
MLT.close();
AbstractProducerWidget::setProducer(0);
emit producerChanged(0);
QCoreApplication::processEvents();
Mlt::Producer *p = newProducer(MLT.profile());
AbstractProducerWidget::setProducer(p);
MLT.setProducer(p);
MLT.play();
emit producerChanged(p);
}
}
void DirectShowVideoWidget::on_audioCombo_activated(int index)
{
on_videoCombo_activated(index);
}
| 8,220
|
C++
|
.cpp
| 210
| 30.104762
| 127
| 0.57675
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,201
|
decklinkproducerwidget.cpp
|
mltframework_shotcut/src/widgets/decklinkproducerwidget.cpp
|
/*
* Copyright (c) 2012-2018 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "decklinkproducerwidget.h"
#include "ui_decklinkproducerwidget.h"
#include "mltcontroller.h"
#include "util.h"
#include "shotcut_mlt_properties.h"
DecklinkProducerWidget::DecklinkProducerWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::DecklinkProducerWidget)
{
ui->setupUi(this);
Util::setColorsToHighlight(ui->label);
ui->profileCombo->addItem(tr("Detect Automatically"), "auto");
ui->profileCombo->addItem("HD 720p 50 fps", "atsc_720p_50");
ui->profileCombo->addItem("HD 720p 59.94 fps", "atsc_720p_5994");
ui->profileCombo->addItem("HD 720p 60 fps", "atsc_720p_60");
ui->profileCombo->addItem("HD 1080i 25 fps", "atsc_1080i_50");
ui->profileCombo->addItem("HD 1080i 29.97 fps", "atsc_1080i_5994");
ui->profileCombo->addItem("HD 1080p 23.98 fps", "atsc_1080p_2398");
ui->profileCombo->addItem("HD 1080p 24 fps", "atsc_1080p_24");
ui->profileCombo->addItem("HD 1080p 25 fps", "atsc_1080p_25");
ui->profileCombo->addItem("HD 1080p 29.97 fps", "atsc_1080p_2997");
ui->profileCombo->addItem("HD 1080p 30 fps", "atsc_1080p_30");
ui->profileCombo->addItem("SD NTSC", "dv_ntsc");
ui->profileCombo->addItem("SD PAL", "dv_pal");
ui->profileCombo->addItem("UHD 2160p 23.98 fps", "uhd_2160p_2398");
ui->profileCombo->addItem("UHD 2160p 24 fps", "uhd_2160p_24");
ui->profileCombo->addItem("UHD 2160p 25 fps", "uhd_2160p_25");
ui->profileCombo->addItem("UHD 2160p 29.97 fps", "uhd_2160p_2997");
ui->profileCombo->addItem("UHD 2160p 30 fps", "uhd_2160p_30");
ui->profileCombo->addItem("UHD 2160p 50 fps", "uhd_2160p_50");
ui->profileCombo->addItem("UHD 2160p 59.94 fps", "uhd_2160p_5994");
ui->profileCombo->addItem("UHD 2160p 60 fps", "uhd_2160p_60");
Mlt::Profile profile;
Mlt::Producer p(profile, "decklink:");
if (p.is_valid()) {
p.set("list_devices", 1);
int n = p.get_int("devices");
for (int i = 0; i < n; ++i) {
QString device(p.get(QStringLiteral("device.%1").arg(i).toLatin1().constData()));
if (!device.isEmpty())
ui->deviceCombo->addItem(device);
}
}
}
DecklinkProducerWidget::~DecklinkProducerWidget()
{
delete ui;
}
Mlt::Producer *DecklinkProducerWidget::newProducer(Mlt::Profile &profile)
{
Mlt::Producer *p = new Mlt::Producer(profile,
QStringLiteral("consumer:decklink:%1").arg(ui->deviceCombo->currentIndex()).toLatin1().constData());
if (p->is_valid()) {
p->set("profile", ui->profileCombo->itemData(
ui->profileCombo->currentIndex()).toString().toLatin1().constData());
p->set(kBackgroundCaptureProperty, 2);
p->set(kShotcutCaptionProperty, tr("SDI/HDMI").toUtf8().constData());
}
return p;
}
Mlt::Properties DecklinkProducerWidget::getPreset() const
{
Mlt::Properties p;
p.set("card", ui->deviceCombo->currentIndex());
p.set("profile", ui->profileCombo->currentIndex());
return p;
}
void DecklinkProducerWidget::loadPreset(Mlt::Properties &p)
{
ui->deviceCombo->setCurrentIndex(p.get_int("card"));
for (int i = 0; i < ui->profileCombo->count(); ++i) {
if (ui->profileCombo->itemData(i).toString() == p.get("profile")) {
ui->profileCombo->setCurrentIndex(i);
break;
}
}
}
void DecklinkProducerWidget::on_deviceCombo_activated(int /*index*/)
{
if (m_producer) {
MLT.close();
AbstractProducerWidget::setProducer(0);
emit producerChanged(0);
QCoreApplication::processEvents();
Mlt::Producer *p = newProducer(MLT.profile());
AbstractProducerWidget::setProducer(p);
MLT.setProducer(p);
MLT.play();
emit producerChanged(p);
}
}
void DecklinkProducerWidget::on_profileCombo_activated(int index)
{
on_deviceCombo_activated(index);
}
| 4,600
|
C++
|
.cpp
| 111
| 36.216216
| 141
| 0.669346
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,202
|
jackproducerwidget.cpp
|
mltframework_shotcut/src/widgets/jackproducerwidget.cpp
|
/*
* Copyright (c) 2012-2017 Meltytech, LLC
* Author: Dan Dennedy <dan@dennedy.org>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "jackproducerwidget.h"
#include "ui_jackproducerwidget.h"
#include "util.h"
#include "shotcut_mlt_properties.h"
JackProducerWidget::JackProducerWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::JackProducerWidget)
{
ui->setupUi(this);
Util::setColorsToHighlight(ui->label_2);
}
JackProducerWidget::~JackProducerWidget()
{
delete ui;
}
Mlt::Producer *JackProducerWidget::newProducer(Mlt::Profile &profile)
{
Mlt::Producer *p = new Mlt::Producer(profile, "jack:Shotcut");
p->set(kBackgroundCaptureProperty, 1);
p->set(kShotcutCaptionProperty, "JACK");
return p;
}
| 1,354
|
C++
|
.cpp
| 39
| 32.282051
| 72
| 0.751335
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
13,203
|
slideshowgeneratorwidget.cpp
|
mltframework_shotcut/src/widgets/slideshowgeneratorwidget.cpp
|
/*
* Copyright (c) 2020-2024 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "slideshowgeneratorwidget.h"
#include "Logger.h"
#include "mltcontroller.h"
#include "settings.h"
#include "shotcut_mlt_properties.h"
#include "widgets/producerpreviewwidget.h"
#include "qmltypes/qmlapplication.h"
#include <QComboBox>
#include <QDebug>
#include <QDoubleSpinBox>
#include <QGridLayout>
#include <QLabel>
#include <QSpinBox>
#include <QtConcurrent/QtConcurrent>
#include <math.h>
enum {
ASPECT_CONVERSION_PAD_BLACK,
ASPECT_CONVERSION_CROP_CENTER,
ASPECT_CONVERSION_CROP_PAN,
ASPECT_CONVERSION_PAD_BLUR,
};
static const int minTransitionFrames = 2;
static const int randomIndex = 0;
static const int cutIndex = 1;
static const int dissolveIndex = 2;
SlideshowGeneratorWidget::SlideshowGeneratorWidget(Mlt::Playlist *clips, QWidget *parent)
: QWidget(parent)
, m_clips(clips)
, m_refreshPreview(false)
{
QGridLayout *grid = new QGridLayout();
setLayout(grid);
grid->addWidget(new QLabel(tr("Clip duration")), 0, 0, Qt::AlignRight);
m_clipDurationSpinner = new QDoubleSpinBox();
m_clipDurationSpinner->setToolTip(tr("Set the duration of each clip in the slideshow."));
m_clipDurationSpinner->setSuffix(" s");
m_clipDurationSpinner->setDecimals(1);
m_clipDurationSpinner->setMinimum(0.2);
m_clipDurationSpinner->setMaximum(3600 * 4);
m_clipDurationSpinner->setValue(Settings.slideshowClipDuration(10.0));
connect(m_clipDurationSpinner, SIGNAL(valueChanged(double)), this, SLOT(on_parameterChanged()));
grid->addWidget(m_clipDurationSpinner, 0, 1);
grid->addWidget(new QLabel(tr("Aspect ratio conversion")), 1, 0, Qt::AlignRight);
m_aspectConversionCombo = new QComboBox();
m_aspectConversionCombo->addItem(tr("Pad Black"));
m_aspectConversionCombo->addItem(tr("Crop Center"));
m_aspectConversionCombo->addItem(tr("Crop and Pan"));
{
QScopedPointer<Mlt::Properties> mltFilters(MLT.repository()->filters());
if (mltFilters && mltFilters->property_exists("pillar_echo")) {
m_aspectConversionCombo->addItem(tr("Pad Blur"));
}
}
m_aspectConversionCombo->setToolTip(tr("Choose an aspect ratio conversion method."));
m_aspectConversionCombo->setCurrentIndex(Settings.slideshowAspectConversion(
ASPECT_CONVERSION_CROP_CENTER));
connect(m_aspectConversionCombo, SIGNAL(currentIndexChanged(int)), this,
SLOT(on_parameterChanged()));
grid->addWidget(m_aspectConversionCombo, 1, 1);
grid->addWidget(new QLabel(tr("Zoom effect")), 2, 0, Qt::AlignRight);
m_zoomPercentSpinner = new QSpinBox();
m_zoomPercentSpinner->setToolTip(
tr("Set the percentage of the zoom-in effect.\n0% will result in no zoom effect."));
m_zoomPercentSpinner->setSuffix(" %");
m_zoomPercentSpinner->setMinimum(-50);
m_zoomPercentSpinner->setMaximum(50);
m_zoomPercentSpinner->setValue(Settings.slideshowZoomPercent(10));
connect(m_zoomPercentSpinner, SIGNAL(valueChanged(int)), this, SLOT(on_parameterChanged()));
grid->addWidget(m_zoomPercentSpinner, 2, 1);
grid->addWidget(new QLabel(tr("Transition duration")), 3, 0, Qt::AlignRight);
m_transitionDurationSpinner = new QDoubleSpinBox();
m_transitionDurationSpinner->setToolTip(
tr("Set the duration of the transition.\nMay not be longer than half the duration of the clip.\nIf the duration is 0, no transition will be created."));
m_transitionDurationSpinner->setSuffix(" s");
m_transitionDurationSpinner->setDecimals(1);
m_transitionDurationSpinner->setMinimum(0);
m_transitionDurationSpinner->setMaximum(10);
m_transitionDurationSpinner->setValue(Settings.slideshowTransitionDuration(2.0));
connect(m_transitionDurationSpinner, SIGNAL(valueChanged(double)), this,
SLOT(on_parameterChanged()));
grid->addWidget(m_transitionDurationSpinner, 3, 1);
grid->addWidget(new QLabel(tr("Transition type")), 4, 0, Qt::AlignRight);
m_transitionStyleCombo = new QComboBox();
m_transitionStyleCombo->setMaximumWidth(350);
m_transitionStyleCombo->addItem(tr("Random"));
m_transitionStyleCombo->addItem(tr("Cut"));
m_transitionStyleCombo->addItem(tr("Dissolve"));
m_transitionStyleCombo->addItem(tr("Bar Horizontal"));
m_transitionStyleCombo->addItem(tr("Bar Vertical"));
m_transitionStyleCombo->addItem(tr("Barn Door Horizontal"));
m_transitionStyleCombo->addItem(tr("Barn Door Vertical"));
m_transitionStyleCombo->addItem(tr("Barn Door Diagonal SW-NE"));
m_transitionStyleCombo->addItem(tr("Barn Door Diagonal NW-SE"));
m_transitionStyleCombo->addItem(tr("Diagonal Top Left"));
m_transitionStyleCombo->addItem(tr("Diagonal Top Right"));
m_transitionStyleCombo->addItem(tr("Matrix Waterfall Horizontal"));
m_transitionStyleCombo->addItem(tr("Matrix Waterfall Vertical"));
m_transitionStyleCombo->addItem(tr("Matrix Snake Horizontal"));
m_transitionStyleCombo->addItem(tr("Matrix Snake Parallel Horizontal"));
m_transitionStyleCombo->addItem(tr("Matrix Snake Vertical"));
m_transitionStyleCombo->addItem(tr("Matrix Snake Parallel Vertical"));
m_transitionStyleCombo->addItem(tr("Barn V Up"));
m_transitionStyleCombo->addItem(tr("Iris Circle"));
m_transitionStyleCombo->addItem(tr("Double Iris"));
m_transitionStyleCombo->addItem(tr("Iris Box"));
m_transitionStyleCombo->addItem(tr("Box Bottom Right"));
m_transitionStyleCombo->addItem(tr("Box Bottom Left"));
m_transitionStyleCombo->addItem(tr("Box Right Center"));
m_transitionStyleCombo->addItem(tr("Clock Top"));
for (auto &s : QmlApplication::wipes()) {
m_transitionStyleCombo->addItem(QFileInfo(s).fileName(), s);
}
m_transitionStyleCombo->setToolTip(tr("Choose a transition effect."));
m_transitionStyleCombo->setCurrentIndex(Settings.slideshowTransitionStyle(dissolveIndex));
connect(m_transitionStyleCombo, SIGNAL(currentIndexChanged(int)), this,
SLOT(on_parameterChanged()));
grid->addWidget(m_transitionStyleCombo, 4, 1);
grid->addWidget(new QLabel(tr("Transition softness")), 5, 0, Qt::AlignRight);
m_softnessSpinner = new QSpinBox();
m_softnessSpinner->setToolTip(tr("Change the softness of the edge of the wipe."));
m_softnessSpinner->setSuffix(" %");
m_softnessSpinner->setMaximum(100);
m_softnessSpinner->setMinimum(0);
m_softnessSpinner->setValue(Settings.slideshowTransitionSoftness(20));
connect(m_softnessSpinner, SIGNAL(valueChanged(int)), this, SLOT(on_parameterChanged()));
grid->addWidget(m_softnessSpinner, 5, 1);
m_preview = new ProducerPreviewWidget(MLT.profile().dar());
grid->addWidget(m_preview, 6, 0, 1, 2, Qt::AlignCenter);
on_parameterChanged();
}
SlideshowGeneratorWidget::~SlideshowGeneratorWidget()
{
m_future.waitForFinished();
m_preview->stop();
}
Mlt::Playlist *SlideshowGeneratorWidget::getSlideshow()
{
SlideshowConfig config;
m_mutex.lock();
// take a snapshot of the config.
config = m_config;
m_mutex.unlock();
int framesPerClip = round(config.clipDuration * MLT.profile().fps());
int count = m_clips->count();
Mlt::Playlist *slideshow = new Mlt::Playlist(MLT.profile());
Mlt::ClipInfo info;
// Copy clips
for (int i = 0; i < count; i++) {
Mlt::ClipInfo *c = m_clips->clip_info(i, &info);
if (c) {
Mlt::Producer producer(MLT.profile(), "xml-string", MLT.XML(c->producer).toUtf8().constData());
slideshow->append(producer, c->frame_in, c->frame_in + framesPerClip - 1);
}
}
// Add filters
for (int i = 0; i < count; i++) {
Mlt::ClipInfo *c = slideshow->clip_info(i, &info);
if (c && c->producer) {
if (!c->producer->property_exists("meta.media.width")) {
delete c->producer->get_frame(); // makes avformat producer set meta.media.width and .height
}
attachAffineFilter(config, c->producer, c->frame_count - 1);
attachBlurFilter(config, c->producer);
}
}
// Add transitions
int framesPerTransition = round(config.transitionDuration * MLT.profile().fps());
if (framesPerTransition > (framesPerClip / 2 - 1)) {
framesPerTransition = (framesPerClip / 2 - 1);
}
if (framesPerTransition < minTransitionFrames) {
framesPerTransition = 0;
}
if (framesPerTransition > 0) {
for (int i = 0; i < count - 1; i++) {
Mlt::ClipInfo *c = slideshow->clip_info(i, &info);
if (c->frame_count < framesPerTransition) {
// Do not add a transition if the first clip is too short
continue;
}
c = slideshow->clip_info(i + 1, &info);
if (c->frame_count < framesPerTransition) {
// Do not add a transition if the second clip is too short
continue;
}
// Create playlist mix
slideshow->mix(i, framesPerTransition);
QScopedPointer<Mlt::Producer> producer(slideshow->get_clip(i + 1));
if ( producer.isNull() ) {
break;
}
producer->parent().set(kShotcutTransitionProperty, "lumaMix");
// Add mix transition
Mlt::Transition crossFade(MLT.profile(), "mix:-1");
slideshow->mix_add(i + 1, &crossFade);
// Add luma transition
Mlt::Transition luma(MLT.profile(), Settings.playerGPU() ? "movit.luma_mix" : "luma");
applyLumaTransitionProperties(&luma, config);
slideshow->mix_add(i + 1, &luma);
count++;
i++;
}
}
Settings.setSlideshowClipDuration(m_config.clipDuration);
Settings.setSlideshowAspectConversion(m_config.aspectConversion);
Settings.setSlideshowZoomPercent(m_config.zoomPercent);
Settings.setSlideshowTransitionDuration(m_config.transitionDuration);
Settings.setSlideshowTransitionStyle(m_config.transitionStyle);
Settings.setSlideshowTransitionSoftness(m_config.transitionSoftness);
return slideshow;
}
void SlideshowGeneratorWidget::attachAffineFilter(SlideshowConfig &config, Mlt::Producer *producer,
int endPosition)
{
if (config.zoomPercent == 0 &&
config.aspectConversion != ASPECT_CONVERSION_CROP_CENTER &&
config.aspectConversion != ASPECT_CONVERSION_CROP_PAN) {
return;
}
mlt_rect beginRect;
mlt_rect endRect;
beginRect.x = 0;
beginRect.y = 0;
beginRect.w = MLT.profile().width();
beginRect.h = MLT.profile().height();
beginRect.o = 1;
endRect.x = beginRect.x;
endRect.y = beginRect.y;
endRect.w = beginRect.w;
endRect.h = beginRect.h;
endRect.o = 1;
double destDar = MLT.profile().dar();
double sourceW = producer->get_double("meta.media.width");
double sourceH = producer->get_double("meta.media.height");
double sourceAr = producer->get_double("meta.media.aspect_ratio");
if (!sourceAr) {
sourceAr = producer->get_double("aspect_ratio");
}
double sourceDar = destDar;
if (sourceW && sourceH && sourceAr) {
sourceDar = sourceW * sourceAr / sourceH;
}
if (sourceDar == destDar && config.zoomPercent == 0) {
// Aspect ratios match and no zoom. No need for affine.
return;
}
if (config.aspectConversion == ASPECT_CONVERSION_CROP_CENTER ||
config.aspectConversion == ASPECT_CONVERSION_CROP_PAN) {
if (sourceDar > destDar) {
// Crop sides to fit height
beginRect.w = (double)MLT.profile().width() * sourceDar / destDar;
beginRect.h = MLT.profile().height();
beginRect.y = 0;
endRect.w = beginRect.w;
endRect.h = beginRect.h;
endRect.y = beginRect.y;
if (config.aspectConversion == ASPECT_CONVERSION_CROP_CENTER) {
beginRect.x = ((double)MLT.profile().width() - beginRect.w) / 2.0;
endRect.x = beginRect.x;
} else {
beginRect.x = 0;
endRect.x = (double)MLT.profile().width() - endRect.w;
}
} else if (destDar > sourceDar) {
// Crop top and bottom to fit width.
beginRect.w = MLT.profile().width();
beginRect.h = (double)MLT.profile().height() * destDar / sourceDar;
beginRect.x = 0;
endRect.w = beginRect.w;
endRect.h = beginRect.h;
endRect.x = beginRect.x;
if (config.aspectConversion == ASPECT_CONVERSION_CROP_CENTER) {
beginRect.y = ((double)MLT.profile().height() - beginRect.h) / 2.0;
endRect.y = beginRect.y;
} else {
beginRect.y = 0;
endRect.y = (double)MLT.profile().height() - endRect.h;
}
}
} else {
// Pad: modify rect to fit the aspect ratio of the source
if (sourceDar > destDar) {
beginRect.w = MLT.profile().width();
beginRect.h = (double)MLT.profile().height() * destDar / sourceDar;
beginRect.x = 0;
beginRect.y = ((double)MLT.profile().height() - beginRect.h) / 2.0;
} else if (destDar > sourceDar) {
beginRect.w = (double)MLT.profile().width() * sourceDar / destDar;
beginRect.h = MLT.profile().height();
beginRect.x = ((double)MLT.profile().width() - beginRect.w) / 2.0;
beginRect.y = 0;
}
endRect.w = beginRect.w;
endRect.h = beginRect.h;
endRect.y = beginRect.y;
endRect.x = beginRect.x;
}
if (config.zoomPercent > 0) {
double endScale = (double)config.zoomPercent / 100.0;
endRect.x = endRect.x - (endScale * endRect.w / 2.0);
endRect.y = endRect.y - (endScale * endRect.h / 2.0);
endRect.w = endRect.w + (endScale * endRect.w);
endRect.h = endRect.h + (endScale * endRect.h);
} else if (config.zoomPercent < 0) {
double beginScale = -1.0 * (double)config.zoomPercent / 100.0;
beginRect.x = beginRect.x - (beginScale * beginRect.w / 2.0);
beginRect.y = beginRect.y - (beginScale * beginRect.h / 2.0);
beginRect.w = beginRect.w + (beginScale * beginRect.w);
beginRect.h = beginRect.h + (beginScale * beginRect.h);
}
Mlt::Filter filter(MLT.profile(), Settings.playerGPU() ? "movit.rect" : "affine");
if (Settings.playerGPU()) {
filter.anim_set("rect", beginRect, 0);
filter.anim_set("rect", endRect, endPosition);
filter.set("fill", 1);
filter.set("distort", 0);
filter.set("valign", "middle");
filter.set("halign", "center");
filter.set(kShotcutFilterProperty, "movitSizePosition");
} else {
filter.anim_set("transition.rect", beginRect, 0);
filter.anim_set("transition.rect", endRect, endPosition);
filter.set("transition.fill", 1);
filter.set("transition.distort", 0);
filter.set("transition.valign", "middle");
filter.set("transition.halign", "center");
filter.set("transition.threads", 0);
filter.set("background", "color:#000000");
filter.set(kShotcutFilterProperty, "affineSizePosition");
}
filter.set(kShotcutAnimInProperty, producer->frames_to_time(endPosition + 1, mlt_time_clock));
filter.set(kShotcutAnimOutProperty, producer->frames_to_time(0, mlt_time_clock));
producer->attach(filter);
}
void SlideshowGeneratorWidget::attachBlurFilter(SlideshowConfig &config, Mlt::Producer *producer)
{
if (config.aspectConversion != ASPECT_CONVERSION_PAD_BLUR) {
return;
}
mlt_rect rect;
rect.x = 0;
rect.y = 0;
rect.w = MLT.profile().width();
rect.h = MLT.profile().height();
rect.o = 1;
double destDar = MLT.profile().dar();
double sourceW = producer->get_double("meta.media.width");
double sourceH = producer->get_double("meta.media.height");
double sourceAr = producer->get_double("meta.media.aspect_ratio");
if (!sourceAr) {
sourceAr = producer->get_double("aspect_ratio");
}
double sourceDar = destDar;
if ( sourceW && sourceH && sourceAr ) {
sourceDar = sourceW * sourceAr / sourceH;
}
if (sourceDar == destDar) {
// Aspect ratios match. No need for pad.
return;
}
if (sourceDar > destDar) {
// Blur top/bottom to pad.
rect.h = MLT.profile().height() * destDar / sourceDar;
rect.y = ((double)MLT.profile().height() - rect.h) / 2.0;
} else if (destDar > sourceDar) {
// Blur sides to pad.
rect.w = MLT.profile().width() * sourceDar / destDar;
rect.x = ((double)MLT.profile().width() - rect.w) / 2.0;
}
Mlt::Filter filter(MLT.profile(), "pillar_echo");
filter.set("rect", rect);
filter.set("blur", 4);
filter.set(kShotcutFilterProperty, "blur_pad");
producer->attach(filter);
}
void SlideshowGeneratorWidget::applyLumaTransitionProperties(Mlt::Transition *luma,
SlideshowConfig &config)
{
int index = config.transitionStyle;
if (index == randomIndex) {
// Random: pick any number other than randomIndex (0) or cutIndex (1)
index = rand() % (m_transitionStyleCombo->count() - 2) + 2;
}
if (index == cutIndex) {
luma->set("resource", "color:#7f7f7f");
luma->set("softness", 0);
} else if (index == dissolveIndex) {
luma->set("resource", "");
luma->set("softness", 0);
} else if (index <= 24) {
luma->set("resource", QStringLiteral("%luma%1.pgm").arg(index - 2, 2, 10,
QChar('0')).toLatin1().constData());
luma->set("softness", config.transitionSoftness / 100.0);
} else {
luma->set("resource", m_transitionStyleCombo->itemData(index).toString().toUtf8().constData());
luma->set("softness", config.transitionSoftness / 100.0);
}
luma->set("progressive", 1);
if (!Settings.playerGPU()) {
luma->set("alpha_over", 1);
luma->set("fix_background_alpha", 1);
}
}
void SlideshowGeneratorWidget::on_parameterChanged()
{
if (m_transitionDurationSpinner->value() > m_clipDurationSpinner->value() / 2 ) {
m_transitionDurationSpinner->setValue(m_clipDurationSpinner->value() / 2);
}
if (m_transitionDurationSpinner->value() == randomIndex) {
m_transitionStyleCombo->setEnabled(false);
m_softnessSpinner->setEnabled(false);
} else if (m_transitionStyleCombo->currentIndex() == cutIndex) {
m_transitionStyleCombo->setEnabled(true);
m_softnessSpinner->setEnabled(false);
} else if (m_transitionStyleCombo->currentIndex() == dissolveIndex) {
m_transitionStyleCombo->setEnabled(true);
m_softnessSpinner->setEnabled(false);
} else {
m_transitionStyleCombo->setEnabled(true);
m_softnessSpinner->setEnabled(true);
}
m_preview->stop();
m_preview->showText(Settings.playerGPU() ? tr("Preview is not available with GPU Effects") :
tr("Generating Preview..."));
m_mutex.lock();
m_refreshPreview = true;
m_config.clipDuration = m_clipDurationSpinner->value();
m_config.aspectConversion = m_aspectConversionCombo->currentIndex();
m_config.zoomPercent = m_zoomPercentSpinner->value();
m_config.transitionDuration = m_transitionDurationSpinner->value();
m_config.transitionStyle = m_transitionStyleCombo->currentIndex();
m_config.transitionSoftness = m_softnessSpinner->value();
if (m_future.isFinished() || m_future.isCanceled()) {
// Generate the preview producer in another thread because it can take some time
m_future = QtConcurrent::run(&SlideshowGeneratorWidget::generatePreviewSlideshow, this);
}
m_mutex.unlock();
}
void SlideshowGeneratorWidget::generatePreviewSlideshow()
{
m_mutex.lock();
while (m_refreshPreview) {
m_refreshPreview = false;
m_mutex.unlock();
Mlt::Producer newProducer = getSlideshow();
m_mutex.lock();
if (!m_refreshPreview) {
m_previewProducer = newProducer;
QMetaObject::invokeMethod(this, "startPreview", Qt::QueuedConnection);
}
}
m_mutex.unlock();
}
void SlideshowGeneratorWidget::startPreview()
{
m_mutex.lock();
if (m_previewProducer.is_valid()) {
m_preview->start(m_previewProducer);
}
m_previewProducer = Mlt::Producer();
m_mutex.unlock();
}
| 21,472
|
C++
|
.cpp
| 478
| 37.598326
| 160
| 0.652981
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,204
|
audioscale.cpp
|
mltframework_shotcut/src/widgets/audioscale.cpp
|
/*
* Copyright (c) 2015-2022 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "audioscale.h"
#include "iecscale.h"
#include <QFont>
#include <QPainter>
#include <Logger.h>
AudioScale::AudioScale(QWidget *parent) :
QWidget(parent)
{
const QFont &font = QWidget::font();
const int fontSize = font.pointSize() - (font.pointSize() > 10 ? 2 : (font.pointSize() > 8 ? 1 :
0));
setFont(QFont(font.family(), fontSize));
setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding);
setMinimumWidth(fontMetrics().horizontalAdvance("-60"));
setFocusPolicy(Qt::NoFocus);
dbscale << 5 << 0 << -5 << -10 << -15 << -20 << -25 << -30 << -35 << -40 << -50;
}
void AudioScale::paintEvent(QPaintEvent *)
{
QPainter p(this);
const int h = IEC_Scale(-dbscale[0]) * height() - 2;
foreach (int i, dbscale) {
if (height() > width()) {
if (i != dbscale[0]) {
double xf = IEC_Scale(i) * h;
QString s = QString::asprintf("%d", i);
p.drawText(width() - fontMetrics().horizontalAdvance(s), height() - xf - 1, s);
}
} else {
double xf = IEC_Scale(i) * (double) width();
p.drawText(xf * 40.0 / 42.0 - 10, height() - 2, QString::asprintf("%d", i));
}
}
p.end();
}
| 2,012
|
C++
|
.cpp
| 51
| 33.27451
| 100
| 0.611338
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,205
|
video4linuxwidget.cpp
|
mltframework_shotcut/src/widgets/video4linuxwidget.cpp
|
/*
* Copyright (c) 2012-2022 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "video4linuxwidget.h"
#include "ui_video4linuxwidget.h"
#include "pulseaudiowidget.h"
#include "jackproducerwidget.h"
#include "alsawidget.h"
#include "mltcontroller.h"
#include "util.h"
#include "shotcut_mlt_properties.h"
#include "settings.h"
#include <QtWidgets>
Video4LinuxWidget::Video4LinuxWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Video4LinuxWidget),
m_audioWidget(0)
{
ui->setupUi(this);
Util::setColorsToHighlight(ui->label_3);
ui->applyButton->hide();
ui->preset->saveDefaultPreset(getPreset());
ui->preset->loadPresets();
ui->v4lLineEdit->setText(Settings.videoInput());
}
Video4LinuxWidget::~Video4LinuxWidget()
{
delete ui;
}
QString Video4LinuxWidget::URL() const
{
QString s = QStringLiteral("video4linux2:%1?width=%2&height=%3")
.arg(ui->v4lLineEdit->text())
.arg(ui->v4lWidthSpinBox->value())
.arg(ui->v4lHeightSpinBox->value());
if (ui->v4lFramerateSpinBox->value() > 0)
s += QStringLiteral("&framerate=%1").arg(ui->v4lFramerateSpinBox->value());
if (ui->v4lStandardCombo->currentIndex() > 0)
s += QStringLiteral("&standard=") + ui->v4lStandardCombo->currentText();
if (ui->v4lChannelSpinBox->value() > 0)
s += QStringLiteral("&channel=%1").arg(ui->v4lChannelSpinBox->value());
return s;
}
Mlt::Producer *Video4LinuxWidget::newProducer(Mlt::Profile &profile)
{
if (!profile.is_explicit()) {
Mlt::Profile ntscProfile("dv_ntsc");
Mlt::Profile palProfile("dv_pal");
if (ui->v4lWidthSpinBox->value() == ntscProfile.width()
&& ui->v4lHeightSpinBox->value() == ntscProfile.height()) {
profile.set_sample_aspect(ntscProfile.sample_aspect_num(), ntscProfile.sample_aspect_den());
profile.set_progressive(ntscProfile.progressive());
profile.set_colorspace(ntscProfile.colorspace());
profile.set_frame_rate(ntscProfile.frame_rate_num(), ntscProfile.frame_rate_den());
} else if (ui->v4lWidthSpinBox->value() == palProfile.width()
&& ui->v4lHeightSpinBox->value() == palProfile.height()) {
profile.set_sample_aspect(palProfile.sample_aspect_num(), palProfile.sample_aspect_den());
profile.set_progressive(palProfile.progressive());
profile.set_colorspace(palProfile.colorspace());
profile.set_frame_rate(palProfile.frame_rate_num(), palProfile.frame_rate_den());
} else {
profile.set_width(ui->v4lWidthSpinBox->value());
profile.set_height(ui->v4lHeightSpinBox->value());
profile.set_sample_aspect(1, 1);
profile.set_progressive(1);
profile.set_colorspace(601);
profile.set_frame_rate(ui->v4lFramerateSpinBox->value() * 10000, 10000);
}
MLT.updatePreviewProfile();
MLT.setPreviewScale(Settings.playerPreviewScale());
}
Mlt::Producer *p = new Mlt::Producer(profile, URL().toLatin1().constData());
if (!p->is_valid()) {
delete p;
p = new Mlt::Producer(profile, "color:");
p->set("resource1", QStringLiteral("video4linux2:%1")
.arg(ui->v4lLineEdit->text()).toLatin1().constData());
p->set("error", 1);
} else if (m_audioWidget) {
Mlt::Producer *audio = dynamic_cast<AbstractProducerWidget *>(m_audioWidget)->newProducer(profile);
Mlt::Tractor *tractor = new Mlt::Tractor;
tractor->set("_profile", profile.get_profile(), 0);
tractor->set_track(*p, 0);
delete p;
tractor->set_track(*audio, 1);
delete audio;
p = new Mlt::Producer(tractor->get_producer());
delete tractor;
p->set("resource1", QStringLiteral("video4linux2:%1")
.arg(ui->v4lLineEdit->text()).toLatin1().constData());
}
p->set("device", ui->v4lLineEdit->text().toLatin1().constData());
p->set("width", ui->v4lWidthSpinBox->value());
p->set("height", ui->v4lHeightSpinBox->value());
if (ui->v4lFramerateSpinBox->value() > 0)
p->set("framerate", ui->v4lFramerateSpinBox->value());
p->set("standard", ui->v4lStandardCombo->currentText().toLatin1().constData());
p->set("channel", ui->v4lChannelSpinBox->value());
p->set("audio_ix", ui->v4lAudioComboBox->currentIndex());
p->set("force_seekable", 0);
p->set(kBackgroundCaptureProperty, 1);
p->set(kShotcutCaptionProperty, "Video4Linux");
Settings.setVideoInput(ui->v4lLineEdit->text());
return p;
}
Mlt::Properties Video4LinuxWidget::getPreset() const
{
Mlt::Properties p;
p.set("device", ui->v4lLineEdit->text().toLatin1().constData());
p.set("width", ui->v4lWidthSpinBox->value());
p.set("height", ui->v4lHeightSpinBox->value());
p.set("framerate", ui->v4lFramerateSpinBox->value());
p.set("standard", ui->v4lStandardCombo->currentText().toLatin1().constData());
p.set("channel", ui->v4lChannelSpinBox->value());
p.set("audio_ix", ui->v4lAudioComboBox->currentIndex());
return p;
}
void Video4LinuxWidget::loadPreset(Mlt::Properties &p)
{
ui->v4lLineEdit->setText(p.get("device"));
ui->v4lWidthSpinBox->setValue(p.get_int("width"));
ui->v4lHeightSpinBox->setValue(p.get_int("height"));
ui->v4lFramerateSpinBox->setValue(p.get_double("framerate"));
QString s(p.get("standard"));
for (int i = 0; i < ui->v4lStandardCombo->count(); i++) {
if (ui->v4lStandardCombo->itemText(i) == s) {
ui->v4lStandardCombo->setCurrentIndex(i);
break;
}
}
ui->v4lChannelSpinBox->setValue(p.get_int("channel"));
ui->v4lAudioComboBox->setCurrentIndex(p.get_int("audio_ix"));
on_v4lAudioComboBox_activated(p.get_int("audio_ix"));
}
void Video4LinuxWidget::on_v4lAudioComboBox_activated(int index)
{
if (m_audioWidget)
delete m_audioWidget;
m_audioWidget = 0;
if (index == 1)
m_audioWidget = new PulseAudioWidget(this);
else if (index == 2)
m_audioWidget = new JackProducerWidget(this);
else if (index == 3)
m_audioWidget = new AlsaWidget(this);
if (m_audioWidget)
ui->audioLayout->addWidget(m_audioWidget);
}
void Video4LinuxWidget::on_preset_selected(void *p)
{
Mlt::Properties *properties = (Mlt::Properties *) p;
loadPreset(*properties);
delete properties;
}
void Video4LinuxWidget::on_preset_saveClicked()
{
ui->preset->savePreset(getPreset());
}
void Video4LinuxWidget::setProducer(Mlt::Producer *producer)
{
ui->applyButton->show();
if (producer)
loadPreset(*producer);
}
void Video4LinuxWidget::on_applyButton_clicked()
{
MLT.close();
AbstractProducerWidget::setProducer(0);
emit producerChanged(0);
QCoreApplication::processEvents();
Mlt::Producer *p = newProducer(MLT.profile());
AbstractProducerWidget::setProducer(p);
MLT.setProducer(p);
MLT.play();
emit producerChanged(p);
}
| 7,678
|
C++
|
.cpp
| 189
| 34.878307
| 107
| 0.667202
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,206
|
statuslabelwidget.cpp
|
mltframework_shotcut/src/widgets/statuslabelwidget.cpp
|
/*
* Copyright (c) 2022 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "statuslabelwidget.h"
#include "settings.h"
#include <QAction>
#include <QApplication>
#include <QGraphicsOpacityEffect>
#include <QHBoxLayout>
#include <QPropertyAnimation>
#include <QPushButton>
static const int STATUS_ANIMATION_MS = 350;
StatusLabelWidget::StatusLabelWidget(QWidget *parent)
: QWidget(parent)
, m_width(0)
{
m_layout = new QHBoxLayout;
m_layout->setContentsMargins(0, 0, 0, 0);
m_label = new QPushButton();
m_label->setFlat(true);
m_label->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred);
m_label->setAutoFillBackground(true);
m_layout->addWidget(m_label);
m_layout->addStretch(1);
if (Settings.drawMethod() != Qt::AA_UseOpenGLES) {
QGraphicsOpacityEffect *effect = new QGraphicsOpacityEffect(this);
m_label->setGraphicsEffect(effect);
m_fadeIn = new QPropertyAnimation(effect, "opacity", this);
m_fadeIn->setDuration(STATUS_ANIMATION_MS);
m_fadeIn->setStartValue(0);
m_fadeIn->setEndValue(1);
m_fadeIn->setEasingCurve(QEasingCurve::InBack);
m_fadeOut = new QPropertyAnimation(effect, "opacity", this);
m_fadeOut->setDuration(STATUS_ANIMATION_MS);
m_fadeOut->setStartValue(0);
m_fadeOut->setEndValue(0);
m_fadeOut->setEasingCurve(QEasingCurve::OutBack);
m_timer.setSingleShot(true);
connect(&m_timer, SIGNAL(timeout()), m_fadeOut, SLOT(start()));
connect(m_fadeOut, &QPropertyAnimation::finished, this, &StatusLabelWidget::onFadeOutFinished);
m_fadeOut->start();
} else {
connect(&m_timer, &QTimer::timeout, this, &StatusLabelWidget::onFadeOutFinished);
}
setLayout(m_layout);
}
StatusLabelWidget::~StatusLabelWidget()
{
}
void StatusLabelWidget::setWidth(int width)
{
m_width = width;
}
void StatusLabelWidget::showText(const QString &text, int timeoutSeconds, QAction *action,
QPalette::ColorRole role)
{
auto width = m_width ? m_width : m_layout->maximumSize().width();
QString s = QStringLiteral(" %1 ").arg(
m_label->fontMetrics().elidedText(text, Qt::ElideRight, width - 30));
m_label->setText(s);
m_label->setToolTip(text);
auto palette = QApplication::palette();
if (role == QPalette::ToolTipBase) {
palette.setColor(QPalette::Button, palette.color(role));
palette.setColor(QPalette::ButtonText, palette.color(QPalette::ToolTipText));
} else {
palette.setColor(QPalette::Button, palette.color(role));
palette.setColor(QPalette::ButtonText, palette.color(QPalette::WindowText));
}
m_label->setPalette(palette);
if (action)
connect(m_label, &QPushButton::clicked, action, &QAction::triggered);
else
disconnect(m_label, &QPushButton::clicked, 0, 0);
if (Settings.drawMethod() != Qt::AA_UseOpenGLES) {
// Cancel the fade out.
if (m_fadeOut->state() == QAbstractAnimation::Running) {
m_fadeOut->stop();
}
if (text.isEmpty()) {
// Make it transparent.
m_timer.stop();
m_fadeOut->setStartValue(0);
m_fadeOut->start();
} else {
// Reset the fade out animation.
m_fadeOut->setStartValue(1);
// Fade in.
if (m_fadeIn->state() != QAbstractAnimation::Running && !m_timer.isActive()) {
m_fadeIn->start();
if (timeoutSeconds > 0)
m_timer.start(timeoutSeconds * 1000);
}
}
} else { // DirectX
if (text.isEmpty()) {
m_label->hide();
} else {
m_label->show();
if (timeoutSeconds > 0)
m_timer.start(timeoutSeconds * 1000);
}
}
}
void StatusLabelWidget::onFadeOutFinished()
{
m_label->disconnect(SIGNAL(clicked(bool)));
m_label->setToolTip(QString());
emit statusCleared();
}
| 4,684
|
C++
|
.cpp
| 123
| 31.479675
| 103
| 0.653034
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,207
|
gdigrabwidget.cpp
|
mltframework_shotcut/src/widgets/gdigrabwidget.cpp
|
/*
* Copyright (c) 2015-2022 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "gdigrabwidget.h"
#include "ui_gdigrabwidget.h"
#include "mltcontroller.h"
#include "shotcut_mlt_properties.h"
#include "util.h"
#include "settings.h"
#include <QtWidgets>
#include <QMediaDevices>
#include <QAudioDevice>
GDIgrabWidget::GDIgrabWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::GDIgrabWidget)
{
ui->setupUi(this);
Util::setColorsToHighlight(ui->label_9);
ui->applyButton->hide();
const QRect &r = QGuiApplication::primaryScreen()->geometry();
ui->widthSpinBox->setValue(r.size().width());
ui->heightSpinBox->setValue(r.size().height());
ui->preset->saveDefaultPreset(getPreset());
ui->preset->loadPresets();
if (QMediaDevices::audioInputs().count() > 0) {
for (const auto &deviceInfo : QMediaDevices::audioInputs())
ui->audioComboBox->addItem(deviceInfo.description());
} else {
ui->audioLabel->hide();
ui->audioComboBox->hide();
}
}
GDIgrabWidget::~GDIgrabWidget()
{
delete ui;
}
QString GDIgrabWidget::URL(Mlt::Profile &profile) const
{
if (!profile.is_explicit()) {
profile.set_width(ui->widthSpinBox->value());
profile.set_height(ui->heightSpinBox->value());
profile.set_sample_aspect(1, 1);
profile.set_progressive(1);
profile.set_colorspace(709);
profile.set_frame_rate(25, 1);
MLT.updatePreviewProfile();
MLT.setPreviewScale(Settings.playerPreviewScale());
}
QString s =
QStringLiteral("gdigrab:desktop?offset_x=%1&offset_y=%2&video_size=%3x%4&framerate=%5&show_region=%6&draw_mouse=%7")
.arg(ui->xSpinBox->value())
.arg(ui->ySpinBox->value())
.arg(ui->widthSpinBox->value())
.arg(ui->heightSpinBox->value())
.arg(profile.fps())
.arg(ui->showRegionCheckBox->isChecked() ? 1 : 0)
.arg(ui->drawMouseCheckBox->isChecked() ? 1 : 0);
return s;
}
Mlt::Producer *GDIgrabWidget::newProducer(Mlt::Profile &profile)
{
Mlt::Producer *p = new Mlt::Producer(profile, URL(profile).toLatin1().constData());
if (!p->is_valid()) {
delete p;
p = new Mlt::Producer(profile, "color:");
p->set("error", 1);
} else if (ui->audioComboBox->currentIndex() > 0) {
Mlt::Producer *audio = new Mlt::Producer(profile,
QStringLiteral("dshow:audio=%1").arg(ui->audioComboBox->currentText())
.toLatin1().constData());
Mlt::Tractor *tractor = new Mlt::Tractor;
tractor->set("_profile", profile.get_profile(), 0);
tractor->set_track(*p, 0);
delete p;
tractor->set_track(*audio, 1);
delete audio;
p = new Mlt::Producer(tractor->get_producer());
delete tractor;
}
p->set("xpos", ui->xSpinBox->value());
p->set("ypos", ui->ySpinBox->value());
p->set("width", ui->widthSpinBox->value());
p->set("height", ui->heightSpinBox->value());
p->set("show_region", ui->showRegionCheckBox->isChecked() ? 1 : 0);
p->set("draw_mouse", ui->drawMouseCheckBox->isChecked() ? 1 : 0);
p->set("audio_ix", ui->audioComboBox->currentIndex());
p->set(kBackgroundCaptureProperty, 1);
p->set("force_seekable", 0);
return p;
}
Mlt::Properties GDIgrabWidget::getPreset() const
{
Mlt::Properties p;
p.set("xpos", ui->xSpinBox->value());
p.set("ypos", ui->ySpinBox->value());
p.set("width", ui->widthSpinBox->value());
p.set("height", ui->heightSpinBox->value());
p.set("show_region", ui->showRegionCheckBox->isChecked() ? 1 : 0);
p.set("draw_mouse", ui->drawMouseCheckBox->isChecked() ? 1 : 0);
p.set("audio_ix", ui->audioComboBox->currentIndex());
p.set(kBackgroundCaptureProperty, 1);
return p;
}
void GDIgrabWidget::loadPreset(Mlt::Properties &p)
{
ui->xSpinBox->setValue(p.get_int("xpos"));
ui->ySpinBox->setValue(p.get_int("ypos"));
ui->widthSpinBox->setValue(p.get_int("width"));
ui->heightSpinBox->setValue(p.get_int("height"));
ui->showRegionCheckBox->setChecked(p.get_int("show_region"));
ui->drawMouseCheckBox->setChecked(p.get_int("draw_mouse"));
ui->audioComboBox->setCurrentIndex(p.get_int("audio_ix"));
}
void GDIgrabWidget::on_preset_selected(void *p)
{
Mlt::Properties *properties = (Mlt::Properties *) p;
loadPreset(*properties);
delete properties;
}
void GDIgrabWidget::on_preset_saveClicked()
{
ui->preset->savePreset(getPreset());
}
void GDIgrabWidget::setProducer(Mlt::Producer *producer)
{
ui->applyButton->show();
if (producer)
loadPreset(*producer);
}
void GDIgrabWidget::on_applyButton_clicked()
{
MLT.setProducer(newProducer(MLT.profile()));
MLT.play();
}
| 5,456
|
C++
|
.cpp
| 147
| 31.891156
| 124
| 0.655843
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,208
|
colorproducerwidget.cpp
|
mltframework_shotcut/src/widgets/colorproducerwidget.cpp
|
/*
* Copyright (c) 2012-2023 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <QColorDialog>
#include <QFileInfo>
#include "colorproducerwidget.h"
#include "ui_colorproducerwidget.h"
#include "shotcut_mlt_properties.h"
#include "util.h"
#include "mltcontroller.h"
#include "qmltypes/qmlapplication.h"
#include "Logger.h"
static const QString kTransparent = QObject::tr("transparent", "Open Other > Color");
static QString colorToString(const QColor &color)
{
return (color == QColor(0, 0, 0, 0)) ? kTransparent
: QString::asprintf("#%02X%02X%02X%02X",
qAlpha(color.rgba()),
qRed(color.rgba()),
qGreen(color.rgba()),
qBlue(color.rgba()));
}
static QString colorStringToResource(const QString &s)
{
return (s == kTransparent) ? "#00000000" : s;
}
ColorProducerWidget::ColorProducerWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::ColorProducerWidget)
{
ui->setupUi(this);
m_title = ui->lineEdit->text();
ui->colorLabel->setText(kTransparent);
Util::setColorsToHighlight(ui->lineEdit, QPalette::Base);
ui->preset->saveDefaultPreset(getPreset());
Mlt::Properties p;
p.set("resource", "#FF000000");
ui->preset->savePreset(p, tr("black"));
p.set("resource", "#00000000");
ui->preset->savePreset(p, tr("transparent"));
ui->preset->loadPresets();
ui->notesLabel->setVisible(false);
ui->notesTextEdit->setVisible(false);
}
ColorProducerWidget::~ColorProducerWidget()
{
delete ui;
}
void ColorProducerWidget::on_colorButton_clicked()
{
QColor color = colorStringToResource(ui->colorLabel->text());
if (m_producer) {
color = QColor(QFileInfo(m_producer->get("resource")).baseName());
}
QColorDialog::ColorDialogOptions flags = QColorDialog::ShowAlphaChannel;
#if defined(Q_OS_UNIX) && !defined(Q_OS_MAC)
flags = flags | QColorDialog::DontUseNativeDialog;
#endif
auto newColor = QColorDialog::getColor(color, this, QString(), flags);
if (newColor.isValid()) {
auto rgb = newColor;
auto transparent = QColor(0, 0, 0, 0);
rgb.setAlpha(color.alpha());
if (newColor.alpha() == 0 && (rgb != color ||
(newColor == transparent && color == transparent))) {
newColor.setAlpha(255);
}
ui->colorLabel->setText(colorToString(newColor));
ui->colorLabel->setStyleSheet(QStringLiteral("color: %1; background-color: %2")
.arg(Util::textColor(newColor), newColor.name()));
if (m_producer) {
m_producer->set("resource", colorStringToResource(ui->colorLabel->text()).toLatin1().constData());
if (ui->lineEdit->text().isEmpty() || ui->lineEdit->text() == m_title) {
m_producer->set(kShotcutCaptionProperty, ui->colorLabel->text().toLatin1().constData());
} else {
m_producer->set(kShotcutCaptionProperty, ui->lineEdit->text().toUtf8().constData());
}
m_producer->set(kShotcutDetailProperty, ui->colorLabel->text().toLatin1().constData());
emit producerChanged(m_producer.data());
}
}
}
Mlt::Producer *ColorProducerWidget::newProducer(Mlt::Profile &profile)
{
Mlt::Producer *p = new Mlt::Producer(profile, "color:");
p->set("resource", colorStringToResource(ui->colorLabel->text()).toLatin1().constData());
p->set("mlt_image_format", "rgba");
MLT.setDurationFromDefault(p);
if (ui->lineEdit->text().isEmpty() || ui->lineEdit->text() == m_title) {
p->set(kShotcutCaptionProperty, ui->colorLabel->text().toLatin1().constData());
} else {
p->set(kShotcutCaptionProperty, ui->lineEdit->text().toUtf8().constData());
}
p->set(kShotcutDetailProperty, ui->colorLabel->text().toLatin1().constData());
return p;
}
Mlt::Properties ColorProducerWidget::getPreset() const
{
Mlt::Properties p;
QString color = colorStringToResource(ui->colorLabel->text());
p.set("resource", color.toLatin1().constData());
return p;
}
void ColorProducerWidget::loadPreset(Mlt::Properties &p)
{
QColor color(QFileInfo(p.get("resource")).baseName());
ui->colorLabel->setText(colorToString(color));
ui->colorLabel->setStyleSheet(QStringLiteral("color: %1; background-color: %2")
.arg(Util::textColor(color), color.name()));
QString caption, detail;
if (m_producer) {
m_producer->set("resource", colorStringToResource(ui->colorLabel->text()).toLatin1().constData());
caption = m_producer->get(kShotcutCaptionProperty);
detail = m_producer->get(kShotcutDetailProperty);
if (caption.isEmpty() || caption == detail)
m_producer->set(kShotcutCaptionProperty, ui->colorLabel->text().toLatin1().constData());
m_producer->set(kShotcutDetailProperty, ui->colorLabel->text().toLatin1().constData());
emit producerChanged(m_producer.data());
} else {
caption = p.get(kShotcutCaptionProperty);
detail = p.get(kShotcutDetailProperty);
}
if (caption.isEmpty() || caption == detail) {
caption = m_title;
}
ui->lineEdit->setText(caption);
ui->notesLabel->setVisible(true);
ui->notesTextEdit->setVisible(true);
ui->notesTextEdit->setPlainText(QString::fromUtf8(p.get(kCommentProperty)));
}
void ColorProducerWidget::rename()
{
ui->lineEdit->setFocus();
ui->lineEdit->selectAll();
}
void ColorProducerWidget::on_preset_selected(void *p)
{
Mlt::Properties *properties = (Mlt::Properties *) p;
loadPreset(*properties);
delete properties;
}
void ColorProducerWidget::on_preset_saveClicked()
{
ui->preset->savePreset(getPreset());
}
void ColorProducerWidget::on_lineEdit_editingFinished()
{
if (m_producer) {
const auto caption = ui->lineEdit->text();
if (caption.isEmpty()) {
m_producer->set(kShotcutCaptionProperty, ui->colorLabel->text().toLatin1().constData());
ui->lineEdit->setText(m_title);
} else {
m_producer->set(kShotcutCaptionProperty, caption.toUtf8().constData());
}
emit modified();
}
}
void ColorProducerWidget::on_notesTextEdit_textChanged()
{
if (m_producer && m_producer->is_valid()) {
QString existing = QString::fromUtf8(m_producer->get(kCommentProperty));
if (ui->notesTextEdit->toPlainText() != existing) {
m_producer->set(kCommentProperty, ui->notesTextEdit->toPlainText().toUtf8().constData());
emit modified();
}
}
}
| 7,317
|
C++
|
.cpp
| 181
| 34.209945
| 110
| 0.658287
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,209
|
imageproducerwidget.cpp
|
mltframework_shotcut/src/widgets/imageproducerwidget.cpp
|
/*
* Copyright (c) 2012-2023 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "imageproducerwidget.h"
#include "ui_imageproducerwidget.h"
#include "settings.h"
#include "mainwindow.h"
#include "shotcut_mlt_properties.h"
#include "util.h"
#include "dialogs/filedatedialog.h"
#include "proxymanager.h"
#include "qmltypes/qmlapplication.h"
#include <Logger.h>
#include <QFileInfo>
#include <QDir>
#include <QMenu>
#include <QClipboard>
#include <QMessageBox>
// This legacy property is only used in this widget.
#define kShotcutResourceProperty "shotcut_resource"
ImageProducerWidget::ImageProducerWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::ImageProducerWidget),
m_defaultDuration(-1)
{
ui->setupUi(this);
Util::setColorsToHighlight(ui->filenameLabel, QPalette::Base);
}
ImageProducerWidget::~ImageProducerWidget()
{
delete ui;
}
Mlt::Producer *ImageProducerWidget::newProducer(Mlt::Profile &profile)
{
QString resource = QString::fromUtf8(m_producer->get("resource"));
if (!resource.contains("?begin=") && m_producer->get("begin")) {
resource.append(QStringLiteral("?begin=%1").arg(m_producer->get("begin")));
}
LOG_DEBUG() << resource;
Mlt::Producer *p = new Mlt::Producer(profile, resource.toUtf8().constData());
if (p->is_valid()) {
if (ui->durationSpinBox->value() > p->get_length())
p->set("length", p->frames_to_time(ui->durationSpinBox->value(), mlt_time_clock));
p->set_in_and_out(0, ui->durationSpinBox->value() - 1);
}
return p;
}
void ImageProducerWidget::setProducer(Mlt::Producer *p)
{
AbstractProducerWidget::setProducer(p);
if (m_defaultDuration == -1)
m_defaultDuration = m_producer->get_length();
QString resource;
if (m_producer->get(kShotcutResourceProperty)) {
resource = QString::fromUtf8(m_producer->get(kShotcutResourceProperty));
} else if (m_producer->get(kOriginalResourceProperty)) {
resource = QString::fromUtf8(m_producer->get(kOriginalResourceProperty));
} else {
resource = QString::fromUtf8(m_producer->get("resource"));
p->set("ttl", 1);
}
QString name = Util::baseName(resource);
QString caption = m_producer->get(kShotcutCaptionProperty);
if (caption.isEmpty()) {
caption = name;
m_producer->set(kShotcutCaptionProperty, caption.toUtf8().constData());
}
ui->filenameLabel->setText(ui->filenameLabel->fontMetrics().elidedText(caption, Qt::ElideLeft,
width() - 30));
updateDuration();
resource = QDir::toNativeSeparators(resource);
ui->filenameLabel->setToolTip(resource);
bool isProxy = m_producer->get_int(kIsProxyProperty) && m_producer->get(kOriginalResourceProperty);
ui->resolutionLabel->setText(QStringLiteral("%1x%2 %3").arg(p->get("meta.media.width")).arg(
p->get("meta.media.height"))
.arg(isProxy ? tr("(PROXY)") : ""));
ui->aspectNumSpinBox->blockSignals(true);
if (p->get(kAspectRatioNumerator) && p->get(kAspectRatioDenominator)) {
ui->aspectNumSpinBox->setValue(p->get_int(kAspectRatioNumerator));
ui->aspectDenSpinBox->setValue(p->get_int(kAspectRatioDenominator));
} else {
double sar = m_producer->get_double("aspect_ratio");
if (m_producer->get("force_aspect_ratio"))
sar = m_producer->get_double("force_aspect_ratio");
if (sar == 1.0) {
ui->aspectNumSpinBox->setValue(1);
ui->aspectDenSpinBox->setValue(1);
} else {
ui->aspectNumSpinBox->setValue(1000 * sar);
ui->aspectDenSpinBox->setValue(1000);
}
}
ui->aspectNumSpinBox->blockSignals(false);
if (m_producer->get_int("ttl"))
ui->repeatSpinBox->setValue(m_producer->get_int("ttl"));
ui->sequenceCheckBox->setChecked(m_producer->get_int(kShotcutSequenceProperty));
ui->repeatSpinBox->setEnabled(m_producer->get_int(kShotcutSequenceProperty));
ui->durationSpinBox->setEnabled(!m_producer->get_int(kShotcutSequenceProperty));
ui->defaultDurationButton->setEnabled(ui->durationSpinBox->isEnabled());
ui->notesTextEdit->setPlainText(QString::fromUtf8(m_producer->get(kCommentProperty)));
}
void ImageProducerWidget::updateDuration()
{
if (m_producer->get(kFilterOutProperty))
ui->durationSpinBox->setValue(m_producer->get_int(kFilterOutProperty) - m_producer->get_int(
kFilterInProperty) + 1);
else
ui->durationSpinBox->setValue(m_producer->get_playtime());
}
void ImageProducerWidget::rename()
{
ui->filenameLabel->setFocus();
ui->filenameLabel->selectAll();
}
void ImageProducerWidget::reopen(Mlt::Producer *p)
{
int position = m_producer->position();
if (position > p->get_out())
position = p->get_out();
p->set("in", m_producer->get_in());
MLT.stop();
if (MLT.setProducer(p)) {
AbstractProducerWidget::setProducer(nullptr);
return;
}
setProducer(p);
emit producerReopened(false);
emit producerChanged(p);
if (p->get_int(kShotcutSequenceProperty)) {
MLT.play();
} else {
MLT.seek(position);
}
}
void ImageProducerWidget::recreateProducer()
{
QString resource = m_producer->get("resource");
if (!resource.startsWith("qimage:") && !resource.startsWith("pixbuf:")) {
QString serviceName = m_producer->get("mlt_service");
if (!serviceName.isEmpty()) {
if (QFileInfo(resource).isRelative()) {
QString basePath = QFileInfo(MAIN.fileName()).canonicalPath();
QFileInfo fi(basePath, resource);
resource = fi.filePath();
}
resource.prepend(':').prepend(serviceName);
m_producer->set("resource", resource.toUtf8().constData());
}
}
Mlt::Producer *p = newProducer(MLT.profile());
p->pass_list(*m_producer, "force_aspect_ratio," kAspectRatioNumerator "," kAspectRatioDenominator
", begin, ttl," kShotcutResourceProperty ", autolength, length," kShotcutSequenceProperty ", "
kPlaylistIndexProperty
", " kCommentProperty "," kOriginalResourceProperty "," kDisableProxyProperty "," kIsProxyProperty);
Mlt::Controller::copyFilters(*m_producer, *p);
if (m_producer->get(kMultitrackItemProperty)) {
emit producerChanged(p);
delete p;
} else {
reopen(p);
}
}
void ImageProducerWidget::on_resetButton_clicked()
{
if (!m_producer)
return;
const char *s = m_producer->get(kShotcutResourceProperty);
if (!s)
s = m_producer->get(kOriginalResourceProperty);
if (!s)
s = m_producer->get("resource");
if (!s)
return;
Mlt::Producer *p = new Mlt::Producer(MLT.profile(), s);
Mlt::Controller::copyFilters(*m_producer, *p);
if (m_producer->get(kMultitrackItemProperty)) {
emit producerChanged(p);
delete p;
} else {
reopen(p);
}
}
void ImageProducerWidget::on_aspectNumSpinBox_valueChanged(int)
{
if (m_producer) {
double new_sar = double(ui->aspectNumSpinBox->value()) /
double(ui->aspectDenSpinBox->value());
double sar = m_producer->get_double("aspect_ratio");
if (m_producer->get("force_aspect_ratio") || new_sar != sar) {
m_producer->set("force_aspect_ratio", QString::number(new_sar).toLatin1().constData());
m_producer->set(kAspectRatioNumerator, ui->aspectNumSpinBox->text().toLatin1().constData());
m_producer->set(kAspectRatioDenominator, ui->aspectDenSpinBox->text().toLatin1().constData());
}
emit producerChanged(producer());
}
}
void ImageProducerWidget::on_aspectDenSpinBox_valueChanged(int i)
{
on_aspectNumSpinBox_valueChanged(i);
}
void ImageProducerWidget::on_durationSpinBox_editingFinished()
{
if (!m_producer)
return;
if (ui->durationSpinBox->value() == m_producer->get_playtime())
return;
recreateProducer();
}
void ImageProducerWidget::on_sequenceCheckBox_clicked(bool checked)
{
QString resource = m_producer->get("resource");
if (checked && m_producer->get_int(kIsProxyProperty)
&& m_producer->get(kOriginalResourceProperty)) {
// proxy is not currently supported for image sequence, disable it
resource = m_producer->get(kOriginalResourceProperty);
m_producer->set(kDisableProxyProperty, 1);
m_producer->Mlt::Properties::clear(kIsProxyProperty);
m_producer->Mlt::Properties::clear(kOriginalResourceProperty);
}
ui->repeatSpinBox->setEnabled(checked);
if (checked && !m_producer->get(kShotcutResourceProperty))
m_producer->set(kShotcutResourceProperty, resource.toUtf8().constData());
m_producer->set(kShotcutSequenceProperty, checked);
m_producer->set("autolength", checked);
m_producer->set("ttl", ui->repeatSpinBox->value());
if (checked) {
QFileInfo info(resource);
QString name(info.fileName());
QString begin = "";
int i = name.length();
int count = 0;
// find the last numeric digit
for (; i && !name[i - 1].isDigit(); i--) {};
// count the digits and build the begin value
for (; i && name[i - 1].isDigit(); i--, count++)
begin.prepend(name[i - 1]);
if (count) {
m_producer->set("begin", begin.toLatin1().constData());
name.replace(i, count, QStringLiteral("0%1d").arg(count).prepend('%'));
QString serviceName = m_producer->get("mlt_service");
if (!serviceName.isEmpty())
resource = serviceName + ":" + info.path() + "/" + name;
else
resource = info.path() + "/" + name;
m_producer->set("resource", resource.toUtf8().constData());
// Count the number of consecutive files.
// Allow for gaps of up to 100 missing files as is supported by producer_qimage
MAIN.showStatusMessage(tr("Getting length of image sequence..."));
QCoreApplication::processEvents();
name = info.fileName();
name.replace(i, count, "%1");
resource = info.path().append('/').append(name);
int imageCount = 0;
i = begin.toInt();
for (int gap = 0; gap < 100;) {
if (QFile::exists(resource.arg(i, count, 10, QChar('0')))) {
imageCount++;
gap = 0;
} else {
gap ++;
}
i++;
if (i % 100 == 0)
QCoreApplication::processEvents();
}
m_producer->set("length", m_producer->frames_to_time(imageCount * m_producer->get_int("ttl"),
mlt_time_clock));
ui->durationSpinBox->setValue(imageCount);
ui->durationSpinBox->setEnabled(false);
MAIN.showStatusMessage(tr("Reloading image sequence..."));
QCoreApplication::processEvents();
}
} else {
m_producer->Mlt::Properties::clear(kDisableProxyProperty);
m_producer->Mlt::Properties::clear("begin");
m_producer->set("resource", m_producer->get(kShotcutResourceProperty));
m_producer->set("length", m_producer->frames_to_time(qRound(MLT.profile().fps() *
Mlt::kMaxImageDurationSecs), mlt_time_clock));
ui->durationSpinBox->setValue(qRound(MLT.profile().fps() * Settings.imageDuration()));
ui->durationSpinBox->setEnabled(true);
}
ui->defaultDurationButton->setEnabled(ui->durationSpinBox->isEnabled());
recreateProducer();
}
void ImageProducerWidget::on_repeatSpinBox_editingFinished()
{
m_producer->set("ttl", ui->repeatSpinBox->value());
ui->durationSpinBox->setValue(m_producer->get_length());
MAIN.showStatusMessage(tr("Reloading image sequence..."));
QCoreApplication::processEvents();
recreateProducer();
}
void ImageProducerWidget::on_defaultDurationButton_clicked()
{
Settings.setImageDuration(ui->durationSpinBox->value() / MLT.profile().fps());
}
void ImageProducerWidget::on_notesTextEdit_textChanged()
{
QString existing = QString::fromUtf8(m_producer->get(kCommentProperty));
if (ui->notesTextEdit->toPlainText() != existing) {
m_producer->set(kCommentProperty, ui->notesTextEdit->toPlainText().toUtf8().constData());
emit modified();
}
}
void ImageProducerWidget::on_menuButton_clicked()
{
QMenu menu;
if (!MLT.resource().contains("://")) // not a network stream
menu.addAction(ui->actionOpenFolder);
menu.addAction(ui->actionCopyFullFilePath);
menu.addAction(ui->actionSetFileDate);
menu.exec(ui->menuButton->mapToGlobal(QPoint(0, 0)));
}
static QString GetFilenameFromProducer(Mlt::Producer *producer, bool useOriginal = true)
{
QString resource;
if (useOriginal && producer->get(kOriginalResourceProperty)) {
resource = QString::fromUtf8(producer->get(kOriginalResourceProperty));
} else if (producer->get(kShotcutResourceProperty)) {
resource = QString::fromUtf8(producer->get(kShotcutResourceProperty));
} else {
resource = QString::fromUtf8(producer->get("resource"));
}
if (QFileInfo(resource).isRelative()) {
QString basePath = QFileInfo(MAIN.fileName()).canonicalPath();
QFileInfo fi(basePath, resource);
resource = fi.filePath();
}
return resource;
}
void ImageProducerWidget::on_actionCopyFullFilePath_triggered()
{
auto s = GetFilenameFromProducer(producer());
qApp->clipboard()->setText(QDir::toNativeSeparators(s));
}
void ImageProducerWidget::on_actionOpenFolder_triggered()
{
Util::showInFolder(GetFilenameFromProducer(producer()));
}
void ImageProducerWidget::on_actionSetFileDate_triggered()
{
QString resource = GetFilenameFromProducer(producer());
FileDateDialog dialog(resource, producer(), this);
dialog.setModal(QmlApplication::dialogModality());
dialog.exec();
}
void ImageProducerWidget::on_filenameLabel_editingFinished()
{
if (m_producer) {
auto caption = ui->filenameLabel->text();
if (caption.isEmpty()) {
caption = Util::baseName(GetFilenameFromProducer(m_producer.data()));
ui->filenameLabel->setText(caption);
m_producer->set(kShotcutCaptionProperty, caption.toUtf8().constData());
} else {
m_producer->set(kShotcutCaptionProperty, caption.toUtf8().constData());
}
emit modified();
}
}
void ImageProducerWidget::on_actionDisableProxy_triggered(bool checked)
{
if (checked) {
producer()->set(kDisableProxyProperty, 1);
// Replace with original
if (producer()->get_int(kIsProxyProperty) && producer()->get(kOriginalResourceProperty)) {
Mlt::Producer original(MLT.profile(), producer()->get(kOriginalResourceProperty));
if (original.is_valid()) {
original.set(kDisableProxyProperty, 1);
MAIN.replaceAllByHash(Util::getHash(original), original, true);
}
}
} else {
producer()->Mlt::Properties::clear(kDisableProxyProperty);
}
}
void ImageProducerWidget::on_actionMakeProxy_triggered()
{
ProxyManager::generateImageProxy(*producer());
}
void ImageProducerWidget::on_actionDeleteProxy_triggered()
{
// Delete the file if it exists
QString hash = Util::getHash(*producer());
QString fileName = hash + ProxyManager::imageFilenameExtension();
QDir dir = ProxyManager::dir();
LOG_DEBUG() << "removing" << dir.filePath(fileName);
dir.remove(dir.filePath(fileName));
// Delete the pending file if it exists));
fileName = hash + ProxyManager::pendingImageExtension();
dir.remove(dir.filePath(fileName));
// Replace with original
if (producer()->get_int(kIsProxyProperty) && producer()->get(kOriginalResourceProperty)) {
Mlt::Producer original(MLT.profile(), producer()->get(kOriginalResourceProperty));
if (original.is_valid()) {
MAIN.replaceAllByHash(hash, original, true);
}
}
}
void ImageProducerWidget::on_actionCopyHashCode_triggered()
{
qApp->clipboard()->setText(Util::getHash(*producer()));
QMessageBox::information(this, qApp->applicationName(),
tr("The hash code below is already copied to your clipboard:\n\n") +
Util::getHash(*producer()),
QMessageBox::Ok);
}
void ImageProducerWidget::on_proxyButton_clicked()
{
QMenu menu;
if (ProxyManager::isValidImage(*producer())) {
menu.addAction(ui->actionMakeProxy);
}
#ifndef Q_OS_WIN
menu.addAction(ui->actionDeleteProxy);
#endif
menu.addAction(ui->actionDisableProxy);
menu.addAction(ui->actionCopyHashCode);
bool proxyDisabled = m_producer->get_int(kDisableProxyProperty);
ui->actionMakeProxy->setDisabled(proxyDisabled);
ui->actionDisableProxy->setChecked(proxyDisabled);
menu.exec(ui->proxyButton->mapToGlobal(QPoint(0, 0)));
}
| 18,037
|
C++
|
.cpp
| 436
| 34.192661
| 117
| 0.652283
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,210
|
isingwidget.cpp
|
mltframework_shotcut/src/widgets/isingwidget.cpp
|
/*
* Copyright (c) 2012-2018 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "shotcut_mlt_properties.h"
#include "isingwidget.h"
#include "ui_isingwidget.h"
#include "util.h"
static const char *kParamTemperature = "0";
static const char *kParamBorderGrowth = "1";
static const char *kParamSpontaneous = "2";
IsingWidget::IsingWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::IsingWidget)
{
ui->setupUi(this);
Util::setColorsToHighlight(ui->nameLabel);
ui->preset->saveDefaultPreset(getPreset());
ui->preset->loadPresets();
}
IsingWidget::~IsingWidget()
{
delete ui;
}
void IsingWidget::on_tempDial_valueChanged(int value)
{
if (m_producer) {
m_producer->set(kParamTemperature, value / 100.0);
emit producerChanged(m_producer.data());
}
ui->tempSpinner->setValue(value / 100.0);
}
void IsingWidget::on_tempSpinner_valueChanged(double value)
{
ui->tempDial->setValue(value * 100);
}
void IsingWidget::on_borderGrowthDial_valueChanged(int value)
{
if (m_producer) {
m_producer->set(kParamBorderGrowth, value / 100.0);
emit producerChanged(m_producer.data());
}
ui->borderGrowthSpinner->setValue(value / 100.0);
}
void IsingWidget::on_borderGrowthSpinner_valueChanged(double value)
{
ui->borderGrowthDial->setValue(value * 100);
}
void IsingWidget::on_spontGrowthDial_valueChanged(int value)
{
if (m_producer) {
m_producer->set(kParamSpontaneous, value / 100.0);
emit producerChanged(producer());
}
ui->spontGrowthSpinner->setValue(value / 100.0);
}
void IsingWidget::on_spontGrowthSpinner_valueChanged(double value)
{
ui->spontGrowthDial->setValue(value * 100);
}
Mlt::Producer *IsingWidget::newProducer(Mlt::Profile &profile)
{
Mlt::Producer *p = new Mlt::Producer(profile, "frei0r.ising0r");
p->set(kParamTemperature, ui->tempSpinner->text().toLatin1().constData());
p->set(kParamBorderGrowth, ui->borderGrowthSpinner->text().toLatin1().constData());
p->set(kParamSpontaneous, ui->spontGrowthSpinner->text().toLatin1().constData());
p->set(kShotcutCaptionProperty, ui->nameLabel->text().toUtf8().constData());
p->set(kShotcutDetailProperty, ui->nameLabel->text().toUtf8().constData());
return p;
}
Mlt::Properties IsingWidget::getPreset() const
{
Mlt::Properties p;
p.set(kParamTemperature, ui->tempSpinner->text().toLatin1().constData());
p.set(kParamBorderGrowth, ui->borderGrowthSpinner->text().toLatin1().constData());
p.set(kParamSpontaneous, ui->spontGrowthSpinner->text().toLatin1().constData());
return p;
}
void IsingWidget::loadPreset(Mlt::Properties &p)
{
ui->tempSpinner->setValue(p.get_double(kParamTemperature));
ui->borderGrowthSpinner->setValue(p.get_double(kParamBorderGrowth));
ui->spontGrowthSpinner->setValue(p.get_double(kParamSpontaneous));
}
void IsingWidget::on_preset_selected(void *p)
{
Mlt::Properties *properties = (Mlt::Properties *) p;
loadPreset(*properties);
delete properties;
}
void IsingWidget::on_preset_saveClicked()
{
ui->preset->savePreset(getPreset());
}
| 3,744
|
C++
|
.cpp
| 106
| 32.150943
| 87
| 0.732542
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
13,211
|
playlisttable.cpp
|
mltframework_shotcut/src/widgets/playlisttable.cpp
|
/*
* Copyright (c) 2015-2022 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "playlisttable.h"
#include <Logger.h>
#include <QKeyEvent>
PlaylistTable::PlaylistTable(QWidget *parent)
: QTableView(parent)
{
}
void PlaylistTable::keyPressEvent(QKeyEvent *event)
{
if (event->key() == Qt::Key_Left || event->key() == Qt::Key_Right) {
/* make sure we ignore left/right keypresses here so it can bubble its way up to the top
* level where it's handled as a global keyboard shortcut. There's seemingly no way to keep
* QTableView from using left/right for moving between cells, so this is a slight hack to
* prevent that behavior. */
event->ignore();
return;
}
// Ignore select all
if (event->key() == Qt::Key_A && event->modifiers() == Qt::ControlModifier) {
event->ignore();
return;
}
QTableView::keyPressEvent(event);
event->ignore();
}
void PlaylistTable::dropEvent(QDropEvent *event)
{
QModelIndex index = indexAt(event->position().toPoint());
if (event->dropAction() == Qt::MoveAction && index.row() == -1) {
event->acceptProposedAction();
emit movedToEnd();
} else {
QTableView::dropEvent(event);
}
}
| 1,875
|
C++
|
.cpp
| 51
| 32.647059
| 99
| 0.68994
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,212
|
pulseaudiowidget.cpp
|
mltframework_shotcut/src/widgets/pulseaudiowidget.cpp
|
/*
* Copyright (c) 2012-2017 Meltytech, LLC
* Author: Dan Dennedy <dan@dennedy.org>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "pulseaudiowidget.h"
#include "ui_pulseaudiowidget.h"
#include "util.h"
#include "shotcut_mlt_properties.h"
PulseAudioWidget::PulseAudioWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::PulseAudioWidget)
{
ui->setupUi(this);
Util::setColorsToHighlight(ui->label);
}
PulseAudioWidget::~PulseAudioWidget()
{
delete ui;
}
Mlt::Producer *PulseAudioWidget::newProducer(Mlt::Profile &profile)
{
Mlt::Producer *p = new Mlt::Producer(profile, "pulse:default?name=Shotcut");
p->set(kBackgroundCaptureProperty, 1);
p->set(kShotcutCaptionProperty, "PulseAudio");
return p;
}
| 1,356
|
C++
|
.cpp
| 39
| 32.333333
| 80
| 0.750952
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
13,213
|
lumamixtransition.cpp
|
mltframework_shotcut/src/widgets/lumamixtransition.cpp
|
/*
* Copyright (c) 2014-2023 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "lumamixtransition.h"
#include "ui_lumamixtransition.h"
#include "settings.h"
#include "mltcontroller.h"
#include "util.h"
#include "widgets/producerpreviewwidget.h"
#include "qmltypes/qmlapplication.h"
#include <QFileDialog>
#include <QFileInfo>
#include <Logger.h>
static const int kLumaComboDissolveIndex = 0;
static const int kLumaComboCutIndex = 1;
static const int kLumaComboCustomIndex = 2;
LumaMixTransition::LumaMixTransition(Mlt::Producer &producer, QWidget *parent)
: QWidget(parent)
, ui(new Ui::LumaMixTransition)
, m_producer(producer)
{
ui->setupUi(this);
Util::setColorsToHighlight(ui->label_2);
m_maxStockIndex = ui->lumaCombo->count() - 1;
// Load the wipes in AppDataDir/wipes
for (auto &s : QmlApplication::wipes()) {
auto i = new QListWidgetItem(QFileInfo(s).fileName());
i->setData(Qt::UserRole, s);
ui->lumaCombo->addItem(i);
}
for (int i = 0; i < ui->lumaCombo->count(); ++i) {
auto item = ui->lumaCombo->item(i);
item->setToolTip(item->text());
}
QScopedPointer<Mlt::Transition> transition(getTransition("luma"));
if (transition && transition->is_valid()) {
QString resource = transition->get("resource");
ui->lumaCombo->blockSignals(true);
if (!resource.isEmpty() && resource.indexOf("%luma") != -1) {
ui->lumaCombo->setCurrentRow(resource.mid(resource.indexOf("%luma") + 5).left(2).toInt() + 2);
} else if (!resource.isEmpty() && resource.startsWith("color:")) {
ui->lumaCombo->setCurrentRow(kLumaComboCutIndex);
ui->softnessLabel->setText(tr("Position"));
ui->softnessSlider->setValue(qRound(QColor(resource.mid(6)).redF() * 100.0));
ui->invertCheckBox->setDisabled(true);
} else if (!resource.isEmpty()) {
for (int i = m_maxStockIndex + 1; i < ui->lumaCombo->count(); ++i) {
if (ui->lumaCombo->item(i)->data(Qt::UserRole).toString() == resource) {
ui->lumaCombo->setCurrentRow(i);
break;
}
}
if (ui->lumaCombo->currentRow() < 0) {
ui->lumaCombo->blockSignals(true);
ui->lumaCombo->setCurrentRow(kLumaComboCustomIndex);
ui->lumaCombo->blockSignals(false);
}
} else {
ui->lumaCombo->setCurrentRow(kLumaComboDissolveIndex);
ui->invertCheckBox->setDisabled(true);
ui->softnessSlider->setDisabled(true);
ui->softnessSpinner->setDisabled(true);
}
ui->lumaCombo->blockSignals(false);
ui->invertCheckBox->setChecked(transition->get_int("invert"));
if (transition->get("softness") && !resource.startsWith("color:"))
ui->softnessSlider->setValue(qRound(transition->get_double("softness") * 100.0));
updateCustomLumaLabel(*transition);
}
transition.reset(getTransition("mix"));
if (transition && transition->is_valid()) {
if (transition->get_int("start") == -1) {
ui->crossfadeRadioButton->setChecked(true);
ui->mixSlider->setDisabled(true);
ui->mixSpinner->setDisabled(true);
} else {
ui->mixRadioButton->setChecked(true);
}
ui->mixSlider->setValue(qRound(transition->get_double("start") * 100.0));
}
ui->previewCheckBox->setChecked(Settings.timelinePreviewTransition());
m_preview = new ProducerPreviewWidget(MLT.profile().dar(), 180);
m_preview->setLooping(false);
if (Settings.playerGPU())
m_preview->showText(tr("Preview Not Available"));
ui->horizontalLayout->addWidget(m_preview, 0, Qt::AlignCenter);
connect(this, SIGNAL(modified()), this, SLOT(startPreview()), Qt::QueuedConnection);
ui->getCustomLabel->setText(
QString::fromLatin1("<a href=\"https://shotcut.org/resources/#transitions\">%1</a>").arg(
ui->getCustomLabel->text()));
}
LumaMixTransition::~LumaMixTransition()
{
m_preview->stop();
delete ui;
}
void LumaMixTransition::onPlaying()
{
if (m_preview) {
m_preview->stop(false);
}
}
void LumaMixTransition::on_invertCheckBox_clicked(bool checked)
{
QScopedPointer<Mlt::Transition> transition(getTransition("luma"));
if (transition && transition->is_valid()) {
transition->set("invert", checked);
MLT.refreshConsumer();
emit modified();
}
}
static void setColor(Mlt::Transition *transition, int value)
{
qreal r = qreal(value) / 100.0;
QColor color = QColor::fromRgbF(r, r, r);
QString resource = QStringLiteral("color:%1").arg(color.name());
transition->set("resource", resource.toLatin1().constData());
}
void LumaMixTransition::on_softnessSlider_valueChanged(int value)
{
QScopedPointer<Mlt::Transition> transition(getTransition("luma"));
if (transition && transition->is_valid()) {
if (kLumaComboCutIndex == ui->lumaCombo->currentRow()) {
setColor(transition.data(), value);
} else {
transition->set("softness", value / 100.0);
}
MLT.refreshConsumer();
emit modified();
}
}
void LumaMixTransition::on_crossfadeRadioButton_clicked()
{
QScopedPointer<Mlt::Transition> transition(getTransition("mix"));
if (transition && transition->is_valid()) {
transition->set("start", -1);
}
ui->mixSlider->setDisabled(true);
ui->mixSpinner->setDisabled(true);
}
void LumaMixTransition::on_mixRadioButton_clicked()
{
QScopedPointer<Mlt::Transition> transition(getTransition("mix"));
if (transition && transition->is_valid()) {
transition->set("start", ui->mixSlider->value() / 100.0);
}
ui->mixSlider->setEnabled(true);
ui->mixSpinner->setEnabled(true);
}
void LumaMixTransition::on_mixSlider_valueChanged(int value)
{
QScopedPointer<Mlt::Transition> transition(getTransition("mix"));
if (transition && transition->is_valid()) {
transition->set("start", value / 100.0);
}
}
Mlt::Transition *LumaMixTransition::getTransition(const QString &name)
{
QScopedPointer<Mlt::Service> service(m_producer.producer());
while (service && service->is_valid()) {
if (service->type() == mlt_service_transition_type) {
Mlt::Transition transition(*service);
if (name == transition.get("mlt_service"))
return new Mlt::Transition(transition);
else if (name == "luma" && QStringLiteral("movit.luma_mix") == transition.get("mlt_service"))
return new Mlt::Transition(transition);
}
service.reset(service->producer());
}
return nullptr;
}
void LumaMixTransition::updateCustomLumaLabel(Mlt::Transition &transition)
{
ui->customLumaLabel->hide();
ui->favoriteButton->hide();
ui->customLumaLabel->setToolTip(QString());
QString resource = transition.get("resource");
if (resource.isEmpty() || resource.indexOf("%luma") != -1 || resource.startsWith("color:")
|| ui->lumaCombo->currentRow() > m_maxStockIndex) {
} else if (!resource.isEmpty() && !resource.startsWith("color:")) {
ui->customLumaLabel->setText(QFileInfo(transition.get("resource")).fileName());
ui->customLumaLabel->setToolTip(transition.get("resource"));
ui->customLumaLabel->show();
ui->favoriteButton->show();
}
}
void LumaMixTransition::on_lumaCombo_currentRowChanged(int index)
{
if (index == kLumaComboDissolveIndex || index == kLumaComboCutIndex) {
on_invertCheckBox_clicked(false);
ui->invertCheckBox->setChecked(false);
}
ui->invertCheckBox->setEnabled( index != kLumaComboDissolveIndex && index != kLumaComboCutIndex);
ui->softnessSlider->setEnabled( index != kLumaComboDissolveIndex);
ui->softnessSpinner->setEnabled(index != kLumaComboDissolveIndex);
QScopedPointer<Mlt::Transition> transition(getTransition("luma"));
if (transition && transition->is_valid()) {
if (index == kLumaComboDissolveIndex) {
transition->set("resource", "");
ui->softnessLabel->setText(tr("Softness"));
transition->set("softness", ui->softnessSlider->value() / 100.0);
} else if (index == kLumaComboCutIndex) { // Cut
ui->softnessLabel->setText(tr("Position"));
setColor(transition.data(), ui->softnessSlider->value());
} else if (index == kLumaComboCustomIndex) {
ui->softnessLabel->setText(tr("Softness"));
// Custom file
QString path = Settings.openPath();
#ifdef Q_OS_MAC
path.append("/*");
#endif
QString filename = QFileDialog::getOpenFileName(this, tr("Open File"), path,
QString(), nullptr, Util::getFileDialogOptions());
activateWindow();
if (!filename.isEmpty()) {
transition->set("resource", filename.toUtf8().constData());
Util::getHash(*transition);
Settings.setOpenPath(QFileInfo(filename).path());
}
} else if (index > m_maxStockIndex) {
// Custom file in app data dir
auto filename = ui->lumaCombo->item(index)->data(Qt::UserRole).toString();
ui->softnessLabel->setText(tr("Softness"));
transition->set("resource", filename.toUtf8().constData());
Util::getHash(*transition);
} else {
ui->softnessLabel->setText(tr("Softness"));
transition->set("resource", QStringLiteral("%luma%1.pgm").arg(index - 2, 2, 10,
QChar('0')).toLatin1().constData());
}
if (qstrcmp(transition->get("resource"), "")) {
transition->set("progressive", 1);
if (index == kLumaComboCutIndex) {
transition->set("invert", 0);
transition->set("softness", 0);
} else {
transition->set("invert", ui->invertCheckBox->isChecked());
transition->set("softness", ui->softnessSlider->value() / 100.0);
}
}
updateCustomLumaLabel(*transition);
MLT.refreshConsumer();
emit modified();
}
}
void LumaMixTransition::startPreview()
{
if (Settings.timelinePreviewTransition() && m_producer.is_valid() && MLT.isPaused()) {
m_preview->stop();
m_previewProducer = new Mlt::Producer(MLT.profile(), "xml-string",
MLT.XML(&m_producer).toUtf8().constData());
m_preview->start(m_previewProducer);
}
}
void LumaMixTransition::on_previewCheckBox_clicked(bool checked)
{
Settings.setTimelinePreviewTransition(checked);
if (checked) {
startPreview();
}
}
void LumaMixTransition::on_favoriteButton_clicked()
{
QmlApplication::addWipe(ui->customLumaLabel->toolTip());
const auto transitions = QString::fromLatin1("transitions");
QDir dir(Settings.appDataLocation());
if (!dir.exists(transitions)) {
dir.mkdir(transitions);
}
}
| 11,883
|
C++
|
.cpp
| 283
| 34.409894
| 110
| 0.635398
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,214
|
frameratewidget.cpp
|
mltframework_shotcut/src/widgets/frameratewidget.cpp
|
/*
* Copyright (c) 2020 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "widgets/frameratewidget.h"
#include "util.h"
#include <QComboBox>
#include <QDoubleSpinBox>
#include <QHBoxLayout>
FrameRateWidget::FrameRateWidget(QWidget *parent)
: QWidget(parent)
, m_fps(0.0)
{
QHBoxLayout *layout = new QHBoxLayout(this);
layout->setContentsMargins(0, 0, 0, 0);
layout->setSpacing(0);
m_fpsSpinner = new QDoubleSpinBox();
m_fpsSpinner->setDecimals(6);
m_fpsSpinner->setMinimum(1.0);
m_fpsSpinner->setMaximum(1000);
m_fpsSpinner->setValue(25.0);
connect(m_fpsSpinner, SIGNAL(editingFinished()), this, SLOT(on_fpsSpinner_editingFinished()));
layout->addWidget(m_fpsSpinner);
m_fpsComboBox = new QComboBox();
m_fpsComboBox->setMaximumSize(20, 16777215);
m_fpsComboBox->addItem("");
m_fpsComboBox->addItem("23.976024");
m_fpsComboBox->addItem("24");
m_fpsComboBox->addItem("25");
m_fpsComboBox->addItem("29.970030");
m_fpsComboBox->addItem("30");
m_fpsComboBox->addItem("48");
m_fpsComboBox->addItem("50");
m_fpsComboBox->addItem("59.940060");
m_fpsComboBox->addItem("60");
connect(m_fpsComboBox, SIGNAL(currentTextChanged(const QString &)), this,
SLOT(on_fpsComboBox_activated(const QString &)));
layout->addWidget(m_fpsComboBox);
}
double FrameRateWidget::fps()
{
return m_fpsSpinner->value();
}
void FrameRateWidget::setFps(double fps)
{
m_fpsSpinner->setValue(fps);
}
void FrameRateWidget::on_fpsSpinner_editingFinished()
{
if (m_fpsSpinner->value() != m_fps) {
const QString caption(tr("Convert Frames/sec"));
if (m_fpsSpinner->value() == 23.98 || m_fpsSpinner->value() == 23.976) {
Util::showFrameRateDialog(caption, 24000, m_fpsSpinner, this);
} else if (m_fpsSpinner->value() == 29.97) {
Util::showFrameRateDialog(caption, 30000, m_fpsSpinner, this);
} else if (m_fpsSpinner->value() == 47.95) {
Util::showFrameRateDialog(caption, 48000, m_fpsSpinner, this);
} else if (m_fpsSpinner->value() == 59.94) {
Util::showFrameRateDialog(caption, 60000, m_fpsSpinner, this);
}
m_fps = m_fpsSpinner->value();
emit fpsChanged(m_fps);
}
}
void FrameRateWidget::on_fpsComboBox_activated(const QString &arg1)
{
if (!arg1.isEmpty())
m_fpsSpinner->setValue(arg1.toDouble());
}
| 3,056
|
C++
|
.cpp
| 81
| 33.259259
| 98
| 0.691062
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
13,215
|
plasmawidget.cpp
|
mltframework_shotcut/src/widgets/plasmawidget.cpp
|
/*
* Copyright (c) 2012-2018 Meltytech, LLC
* Author: Dan Dennedy <dan@dennedy.org>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "shotcut_mlt_properties.h"
#include "plasmawidget.h"
#include "ui_plasmawidget.h"
#include "util.h"
static const char *kParamSpeed1 = "0";
static const char *kParamSpeed2 = "1";
static const char *kParamSpeed3 = "2";
static const char *kParamSpeed4 = "3";
static const char *kParamMove1 = "4";
static const char *kParamMove2 = "5";
PlasmaWidget::PlasmaWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::PlasmaWidget)
{
ui->setupUi(this);
Util::setColorsToHighlight(ui->nameLabel);
ui->preset->saveDefaultPreset(getPreset());
ui->preset->loadPresets();
}
PlasmaWidget::~PlasmaWidget()
{
delete ui;
}
void PlasmaWidget::on_speed1Dial_valueChanged(int value)
{
if (m_producer) {
m_producer->set(kParamSpeed1, value / 100.0);
emit producerChanged(producer());
}
ui->speed1Spinner->setValue(value / 100.0);
}
void PlasmaWidget::on_speed1Spinner_valueChanged(double value)
{
ui->speed1Dial->setValue(value * 100);
}
void PlasmaWidget::on_speed2Dial_valueChanged(int value)
{
if (m_producer) {
m_producer->set(kParamSpeed2, value / 100.0);
emit producerChanged(producer());
}
ui->speed2Spinner->setValue(value / 100.0);
}
void PlasmaWidget::on_speed2Spinner_valueChanged(double value)
{
ui->speed2Dial->setValue(value * 100);
}
void PlasmaWidget::on_speed3Dial_valueChanged(int value)
{
if (m_producer) {
m_producer->set(kParamSpeed3, value / 100.0);
emit producerChanged(producer());
}
ui->speed3Spinner->setValue(value / 100.0);
}
void PlasmaWidget::on_speed3Spinner_valueChanged(double value)
{
ui->speed3Dial->setValue(value * 100);
}
void PlasmaWidget::on_speed4Dial_valueChanged(int value)
{
if (m_producer) {
m_producer->set(kParamSpeed4, value / 100.0);
emit producerChanged(producer());
}
ui->speed4Spinner->setValue(value / 100.0);
}
void PlasmaWidget::on_speed4Spinner_valueChanged(double value)
{
ui->speed4Dial->setValue(value * 100);
}
void PlasmaWidget::on_move1Dial_valueChanged(int value)
{
if (m_producer) {
m_producer->set(kParamMove1, value / 100.0);
emit producerChanged(producer());
}
ui->move1Spinner->setValue(value / 100.0);
}
void PlasmaWidget::on_move1Spinner_valueChanged(double value)
{
ui->move1Dial->setValue(value * 100);
}
void PlasmaWidget::on_move2Dial_valueChanged(int value)
{
if (m_producer) {
m_producer->set(kParamMove2, value / 100.0);
emit producerChanged(producer());
}
ui->move2Spinner->setValue(value / 100.0);
}
void PlasmaWidget::on_move2Spinner_valueChanged(double value)
{
ui->move2Dial->setValue(value * 100);
}
Mlt::Producer *PlasmaWidget::newProducer(Mlt::Profile &profile)
{
Mlt::Producer *p = new Mlt::Producer(profile, "frei0r.plasma");
p->set(kParamSpeed1, ui->speed1Spinner->text().toLatin1().constData());
p->set(kParamSpeed2, ui->speed2Spinner->text().toLatin1().constData());
p->set(kParamSpeed3, ui->speed3Spinner->text().toLatin1().constData());
p->set(kParamSpeed4, ui->speed4Spinner->text().toLatin1().constData());
p->set(kParamMove1, ui->move1Spinner->text().toLatin1().constData());
p->set(kParamMove2, ui->move2Spinner->text().toLatin1().constData());
p->set(kShotcutCaptionProperty, ui->nameLabel->text().toUtf8().constData());
p->set(kShotcutDetailProperty, ui->nameLabel->text().toUtf8().constData());
return p;
}
Mlt::Properties PlasmaWidget::getPreset() const
{
Mlt::Properties p;
p.set(kParamSpeed1, ui->speed1Spinner->text().toLatin1().constData());
p.set(kParamSpeed2, ui->speed2Spinner->text().toLatin1().constData());
p.set(kParamSpeed3, ui->speed3Spinner->text().toLatin1().constData());
p.set(kParamSpeed4, ui->speed4Spinner->text().toLatin1().constData());
p.set(kParamMove1, ui->move1Spinner->text().toLatin1().constData());
p.set(kParamMove2, ui->move2Spinner->text().toLatin1().constData());
return p;
}
void PlasmaWidget::loadPreset(Mlt::Properties &p)
{
ui->speed1Spinner->setValue(p.get_double(kParamSpeed1));
ui->speed2Spinner->setValue(p.get_double(kParamSpeed2));
ui->speed3Spinner->setValue(p.get_double(kParamSpeed3));
ui->speed4Spinner->setValue(p.get_double(kParamSpeed4));
ui->move1Spinner->setValue(p.get_double(kParamMove1));
ui->move2Spinner->setValue(p.get_double(kParamMove2));
}
void PlasmaWidget::on_preset_selected(void *p)
{
Mlt::Properties *properties = (Mlt::Properties *) p;
loadPreset(*properties);
delete properties;
}
void PlasmaWidget::on_preset_saveClicked()
{
ui->preset->savePreset(getPreset());
}
| 5,411
|
C++
|
.cpp
| 155
| 31.529032
| 80
| 0.716905
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
13,217
|
playlisticonview.cpp
|
mltframework_shotcut/src/widgets/playlisticonview.cpp
|
/*
* Copyright (c) 2016-2023 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "playlisticonview.h"
#include "models/playlistmodel.h"
#include "settings.h"
#include <Logger.h>
#include <QDebug>
#include <QPainter>
#include <QMouseEvent>
#include <QtMath>
#include <QScrollBar>
PlaylistIconView::PlaylistIconView(QWidget *parent)
: QAbstractItemView(parent)
, m_gridSize(170, 100)
, m_draggingOverPos(QPoint())
, m_itemsPerRow(3)
{
verticalScrollBar()->setSingleStep(100);
verticalScrollBar()->setPageStep(400);
setContextMenuPolicy(Qt::CustomContextMenu);
connect(&Settings, SIGNAL(playlistThumbnailsChanged()), SLOT(updateSizes()));
}
QRect PlaylistIconView::visualRect(const QModelIndex &index) const
{
int row = index.row() / m_itemsPerRow;
int col = index.row() % m_itemsPerRow;
return QRect(col * m_gridSize.width(), row * m_gridSize.height(),
m_gridSize.width(), m_gridSize.height());
}
void PlaylistIconView::rowsInserted(const QModelIndex &parent, int start, int end)
{
QAbstractItemView::rowsInserted(parent, start, end);
updateSizes();
viewport()->update();
}
void PlaylistIconView::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end)
{
QAbstractItemView::rowsAboutToBeRemoved(parent, start, end);
updateSizes();
viewport()->update();
}
void PlaylistIconView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight,
const QVector<int> &roles)
{
QAbstractItemView::dataChanged(topLeft, bottomRight, roles);
updateSizes();
viewport()->update();
}
void PlaylistIconView::selectionChanged(const QItemSelection &selected,
const QItemSelection &deselected)
{
QAbstractItemView::selectionChanged(selected, deselected);
viewport()->update();
}
void PlaylistIconView::scrollTo(const QModelIndex &index, ScrollHint hint)
{
Q_UNUSED(index);
Q_UNUSED(hint);
}
QModelIndex PlaylistIconView::indexAt(const QPoint &point) const
{
if (!model())
return QModelIndex();
if (point.x() / m_gridSize.width() >= m_itemsPerRow)
return QModelIndex();
int row = (point.y() + verticalScrollBar()->value()) / m_gridSize.height();
int col = (point.x() / m_gridSize.width()) % m_itemsPerRow;
return model()->index(row * m_itemsPerRow + col, 0);
}
QModelIndex PlaylistIconView::moveCursor(CursorAction cursorAction, Qt::KeyboardModifiers modifiers)
{
Q_UNUSED(cursorAction);
Q_UNUSED(modifiers);
return QModelIndex();
}
int PlaylistIconView::horizontalOffset() const
{
return 0;
}
int PlaylistIconView::verticalOffset() const
{
return 0;
}
bool PlaylistIconView::isIndexHidden(const QModelIndex &index) const
{
Q_UNUSED(index);
return false;
}
void PlaylistIconView::setSelection(const QRect &rect, QItemSelectionModel::SelectionFlags command)
{
QModelIndex topLeft;
if (!selectionModel()->selectedIndexes().isEmpty()) {
topLeft = selectionModel()->selectedIndexes().first();
} else if (!m_isRangeSelect) {
selectionModel()->select(indexAt(rect.topLeft()), command);
return;
}
if (m_isToggleSelect) {
command = QItemSelectionModel::Select;
selectionModel()->select(indexAt(rect.bottomRight()), command);
return;
} else if (m_isRangeSelect && topLeft.isValid()) {
QModelIndex bottomRight = indexAt(rect.bottomRight());
selectionModel()->select(QItemSelection(topLeft, bottomRight), command);
return;
} else if (topLeft.isValid()) {
selectionModel()->select(indexAt(rect.topLeft()), command);
return;
}
m_pendingSelect = indexAt(rect.topLeft());
}
QRegion PlaylistIconView::visualRegionForSelection(const QItemSelection &selection) const
{
Q_UNUSED(selection);
return QRegion();
}
void PlaylistIconView::currentChanged(const QModelIndex ¤t, const QModelIndex &previous)
{
viewport()->update();
QAbstractItemView::currentChanged(current, previous);
}
void PlaylistIconView::paintEvent(QPaintEvent *)
{
QPainter painter(viewport());
QPalette pal(palette());
const auto proxy = tr("P", "The first letter or symbol of \"proxy\"");
const auto oldFont = painter.font();
auto boldFont(oldFont);
boldFont.setBold(true);
painter.fillRect(rect(), pal.base());
if (!model())
return;
QAbstractItemModel *m = model();
QRect dragIndicator;
for (int row = 0; row <= m->rowCount() / m_itemsPerRow; row++) {
for (int col = 0; col < m_itemsPerRow; col++) {
const int rowIdx = row * m_itemsPerRow + col;
QModelIndex idx = m->index(rowIdx, 0);
if (!idx.isValid())
break;
QRect itemRect(col * m_gridSize.width(), row * m_gridSize.height() - verticalScrollBar()->value(),
m_gridSize.width(), m_gridSize.height());
if (itemRect.bottom() < 0 || itemRect.top() > this->height())
continue;
const bool selected = selectedIndexes().contains(idx);
const QImage thumb = idx.data(Qt::DecorationRole).value<QImage>();
QRect imageBoundingRect = itemRect;
imageBoundingRect.setHeight(0.7 * imageBoundingRect.height());
imageBoundingRect.adjust(0, 10, 0, 0);
QRect imageRect(QPoint(), thumb.size());
imageRect.moveCenter(imageBoundingRect.center());
QRect textRect = itemRect;
textRect.setTop(imageBoundingRect.bottom());
textRect.adjust(3, 0, -3, 0);
QRect buttonRect = itemRect.adjusted(2, 2, -2, -2);
if (selected) {
painter.fillRect(buttonRect, pal.highlight());
} else {
painter.fillRect(buttonRect, pal.button());
painter.setPen(pal.color(QPalette::Button).lighter());
painter.drawLine(buttonRect.topLeft(), buttonRect.topRight());
painter.drawLine(buttonRect.topLeft(), buttonRect.bottomLeft());
painter.setPen(pal.color(QPalette::Button).darker());
painter.drawLine(buttonRect.topRight(), buttonRect.bottomRight());
painter.drawLine(buttonRect.bottomLeft(), buttonRect.bottomRight());
}
painter.drawImage(imageRect, thumb);
QStringList nameParts = idx.data(Qt::DisplayRole).toString().split('\n');
if (nameParts.size() > 1) {
const auto indexPos = imageRect.topLeft() + QPoint(5, 15);
painter.setFont(boldFont);
painter.setPen(pal.color(QPalette::Dark).darker());
painter.drawText(indexPos, proxy);
painter.setPen(pal.color(QPalette::WindowText));
painter.drawText(indexPos - QPoint(1, 1), proxy);
painter.setFont(oldFont);
}
painter.setPen(pal.color(QPalette::WindowText));
painter.drawText(textRect, Qt::AlignCenter,
painter.fontMetrics().elidedText(nameParts.first(), Qt::ElideMiddle, textRect.width()));
if (!m_draggingOverPos.isNull() && itemRect.contains(m_draggingOverPos)) {
QAbstractItemView::DropIndicatorPosition dropPos =
position(m_draggingOverPos, itemRect, idx);
dragIndicator.setSize(QSize(4, itemRect.height()));
if (dropPos == QAbstractItemView::AboveItem)
dragIndicator.moveTopLeft(itemRect.topLeft() - QPoint(dragIndicator.width() / 2, 0));
else
dragIndicator.moveTopLeft(itemRect.topRight() - QPoint(dragIndicator.width() / 2 - 1, 0));
}
}
}
if (!dragIndicator.isNull()) {
painter.fillRect(dragIndicator, pal.buttonText());
}
}
void PlaylistIconView::mouseReleaseEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton) {
if (m_draggingOverPos.isNull() && m_pendingSelect.isValid()) {
selectionModel()->select(m_pendingSelect, QItemSelectionModel::ClearAndSelect);
viewport()->update();
}
m_pendingSelect = QModelIndex();
}
QAbstractItemView::mouseReleaseEvent(event);
}
void PlaylistIconView::dragMoveEvent(QDragMoveEvent *e)
{
m_draggingOverPos = e->position().toPoint();
QAbstractItemView::dragMoveEvent(e);
}
void PlaylistIconView::dragLeaveEvent(QDragLeaveEvent *e)
{
m_draggingOverPos = QPoint();
QAbstractItemView::dragLeaveEvent(e);
}
void PlaylistIconView::dropEvent(QDropEvent *event)
{
m_draggingOverPos = QPoint();
QModelIndex index = indexAt(event->position().toPoint());
QRect rectAtDropPoint = visualRect(index);
QAbstractItemView::DropIndicatorPosition dropPos =
position(event->position().toPoint(), rectAtDropPoint, index);
if (dropPos == QAbstractItemView::BelowItem)
index = index.sibling(index.row() + 1, index.column());
const Qt::DropAction action = event->dropAction();
int row = (index.row() != -1) ? index.row() : model()->rowCount();
if (model()->dropMimeData(event->mimeData(), action, row, index.column(), index))
event->acceptProposedAction();
stopAutoScroll();
setState(NoState);
viewport()->update();
}
void PlaylistIconView::resizeEvent(QResizeEvent *event)
{
updateSizes();
QAbstractItemView::resizeEvent(event);
}
void PlaylistIconView::setModel(QAbstractItemModel *model)
{
QAbstractItemView::setModel(model);
updateSizes();
viewport()->update();
}
void PlaylistIconView::keyPressEvent(QKeyEvent *event)
{
QAbstractItemView::keyPressEvent(event);
event->ignore();
m_isToggleSelect = (event->modifiers() & Qt::ControlModifier);
m_isRangeSelect = (event->modifiers() & Qt::ShiftModifier);
}
void PlaylistIconView::keyReleaseEvent(QKeyEvent *event)
{
QAbstractItemView::keyPressEvent(event);
event->ignore();
resetMultiSelect();
}
QAbstractItemView::DropIndicatorPosition PlaylistIconView::position(const QPoint &pos,
const QRect &rect, const QModelIndex &index) const
{
Q_UNUSED(index);
if (pos.x() < rect.center().x())
return QAbstractItemView::AboveItem;
else
return QAbstractItemView::BelowItem;
}
void PlaylistIconView::updateSizes()
{
if (!model() || !model()->rowCount()) {
verticalScrollBar()->setRange(0, 0);
return;
}
QSize size;
if (Settings.playlistThumbnails() == "tall")
size = QSize(PlaylistModel::THUMBNAIL_WIDTH, PlaylistModel::THUMBNAIL_HEIGHT * 2);
else if (Settings.playlistThumbnails() == "large")
size = QSize(PlaylistModel::THUMBNAIL_WIDTH * 2, PlaylistModel::THUMBNAIL_HEIGHT * 2);
else if (Settings.playlistThumbnails() == "wide")
size = QSize(PlaylistModel::THUMBNAIL_WIDTH * 2, PlaylistModel::THUMBNAIL_HEIGHT);
else
size = QSize(PlaylistModel::THUMBNAIL_WIDTH, PlaylistModel::THUMBNAIL_HEIGHT);
size.setWidth(size.width() + 10);
m_itemsPerRow = qMax(1, viewport()->width() / size.width());
m_gridSize = QSize(viewport()->width() / m_itemsPerRow, size.height() + 40);
if (!verticalScrollBar())
return;
verticalScrollBar()->setRange(0,
m_gridSize.height() * model()->rowCount() / m_itemsPerRow - height() + m_gridSize.height());
viewport()->update();
}
void PlaylistIconView::resetMultiSelect()
{
m_isToggleSelect = false;
m_isRangeSelect = false;
}
| 12,307
|
C++
|
.cpp
| 309
| 33.113269
| 126
| 0.665103
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,218
|
blipproducerwidget.cpp
|
mltframework_shotcut/src/widgets/blipproducerwidget.cpp
|
/*
* Copyright (c) 2020 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "shotcut_mlt_properties.h"
#include "blipproducerwidget.h"
#include "ui_blipproducerwidget.h"
#include "util.h"
#include <MltProfile.h>
BlipProducerWidget::BlipProducerWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::BlipProducerWidget)
{
ui->setupUi(this);
Util::setColorsToHighlight(ui->nameLabel);
ui->preset->saveDefaultPreset(getPreset());
ui->preset->loadPresets();
on_periodSpinBox_valueChanged(ui->periodSpinBox->value());
}
BlipProducerWidget::~BlipProducerWidget()
{
delete ui;
}
Mlt::Producer *BlipProducerWidget::newProducer(Mlt::Profile &profile)
{
Mlt::Producer *p = new Mlt::Producer(profile, "blipflash:");
p->set("period", ui->periodSpinBox->value());
p->set("force_seekable", 1);
p->set(kShotcutCaptionProperty, ui->nameLabel->text().toUtf8().constData());
p->set(kShotcutDetailProperty, detail().toUtf8().constData());
return p;
}
Mlt::Properties BlipProducerWidget::getPreset() const
{
Mlt::Properties p;
p.set("period", ui->periodSpinBox->value());
return p;
}
void BlipProducerWidget::loadPreset(Mlt::Properties &p)
{
ui->periodSpinBox->setValue(p.get_int("period"));
p.set(kShotcutDetailProperty, detail().toUtf8().constData());
}
void BlipProducerWidget::on_periodSpinBox_valueChanged(int value)
{
ui->periodSpinBox->setSuffix(tr(" second(s)", nullptr, value));
if (m_producer) {
m_producer->set("period", value);
m_producer->set(kShotcutDetailProperty, detail().toUtf8().constData());
emit producerChanged(producer());
}
}
void BlipProducerWidget::on_preset_selected(void *p)
{
Mlt::Properties *properties = (Mlt::Properties *) p;
loadPreset(*properties);
delete properties;
}
void BlipProducerWidget::on_preset_saveClicked()
{
ui->preset->savePreset(getPreset());
}
QString BlipProducerWidget::detail() const
{
return tr("Period: %1s").arg(ui->periodSpinBox->value());
}
| 2,646
|
C++
|
.cpp
| 78
| 30.910256
| 80
| 0.728303
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,219
|
x11grabwidget.cpp
|
mltframework_shotcut/src/widgets/x11grabwidget.cpp
|
/*
* Copyright (c) 2012-2018 Meltytech, LLC
* Author: Dan Dennedy <dan@dennedy.org>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "x11grabwidget.h"
#include "ui_x11grabwidget.h"
#include "pulseaudiowidget.h"
#include "jackproducerwidget.h"
#include "alsawidget.h"
#include "mltcontroller.h"
#include "shotcut_mlt_properties.h"
#include "util.h"
#include <QtWidgets>
X11grabWidget::X11grabWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::X11grabWidget),
m_audioWidget(0)
{
ui->setupUi(this);
ui->applyButton->hide();
Util::setColorsToHighlight(ui->label_9);
ui->preset->saveDefaultPreset(getPreset());
ui->preset->loadPresets();
}
X11grabWidget::~X11grabWidget()
{
delete ui;
}
void X11grabWidget::on_positionComboBox_activated(int index)
{
ui->xSpinBox->setEnabled(index == 1);
ui->ySpinBox->setEnabled(index == 1);
}
void X11grabWidget::on_audioComboBox_activated(int index)
{
if (m_audioWidget)
delete m_audioWidget;
m_audioWidget = 0;
if (index == 1)
m_audioWidget = new PulseAudioWidget(this);
else if (index == 2)
m_audioWidget = new JackProducerWidget(this);
else if (index == 3)
m_audioWidget = new AlsaWidget(this);
if (m_audioWidget)
ui->audioLayout->addWidget(m_audioWidget);
}
QString X11grabWidget::URL(Mlt::Profile &profile) const
{
if (!profile.is_explicit()) {
profile.set_width(ui->widthSpinBox->value());
profile.set_height(ui->heightSpinBox->value());
profile.set_sample_aspect(1, 1);
profile.set_progressive(1);
profile.set_colorspace(709);
profile.set_frame_rate(25, 1);
}
QString s =
QStringLiteral("x11grab:%1+%2,%3?width=%4&height=%5&framerate=%6&show_region=%7&draw_mouse=%8&follow_mouse=%9")
.arg(ui->lineEdit->text())
.arg(ui->xSpinBox->value())
.arg(ui->ySpinBox->value())
.arg(ui->widthSpinBox->value())
.arg(ui->heightSpinBox->value())
.arg(profile.fps())
.arg(ui->showRegionCheckBox->isChecked() ? 1 : 0)
.arg(ui->drawMouseCheckBox->isChecked() ? 1 : 0)
.arg(ui->positionComboBox->currentIndex() - 1);
return s;
}
Mlt::Producer *X11grabWidget::newProducer(Mlt::Profile &profile)
{
Mlt::Producer *p = new Mlt::Producer(profile, URL(profile).toLatin1().constData());
if (!p->is_valid()) {
delete p;
p = new Mlt::Producer(profile, "color:");
p->set("error", 1);
} else if (m_audioWidget) {
Mlt::Producer *audio = dynamic_cast<AbstractProducerWidget *>(m_audioWidget)->newProducer(profile);
Mlt::Tractor *tractor = new Mlt::Tractor;
tractor->set("_profile", profile.get_profile(), 0);
tractor->set_track(*p, 0);
delete p;
tractor->set_track(*audio, 1);
delete audio;
p = new Mlt::Producer(tractor->get_producer());
delete tractor;
}
p->set("display", ui->lineEdit->text().toLatin1().constData());
p->set("xpos", ui->xSpinBox->value());
p->set("ypos", ui->ySpinBox->value());
p->set("width", ui->widthSpinBox->value());
p->set("height", ui->heightSpinBox->value());
p->set("show_region", ui->showRegionCheckBox->isChecked() ? 1 : 0);
p->set("draw_mouse", ui->drawMouseCheckBox->isChecked() ? 1 : 0);
p->set("follow_mouse", ui->positionComboBox->currentIndex() - 1);
p->set("audio_ix", ui->audioComboBox->currentIndex());
p->set(kBackgroundCaptureProperty, 1);
p->set("force_seekable", 0);
return p;
}
Mlt::Properties X11grabWidget::getPreset() const
{
Mlt::Properties p;
p.set("display", ui->lineEdit->text().toLatin1().constData());
p.set("xpos", ui->xSpinBox->value());
p.set("ypos", ui->ySpinBox->value());
p.set("width", ui->widthSpinBox->value());
p.set("height", ui->heightSpinBox->value());
p.set("show_region", ui->showRegionCheckBox->isChecked() ? 1 : 0);
p.set("draw_mouse", ui->drawMouseCheckBox->isChecked() ? 1 : 0);
p.set("follow_mouse", ui->positionComboBox->currentIndex() - 1);
p.set("audio_ix", ui->audioComboBox->currentIndex());
p.set(kBackgroundCaptureProperty, 1);
return p;
}
void X11grabWidget::loadPreset(Mlt::Properties &p)
{
ui->lineEdit->setText(p.get("display"));
ui->xSpinBox->setValue(p.get_int("xpos"));
ui->ySpinBox->setValue(p.get_int("ypos"));
ui->widthSpinBox->setValue(p.get_int("width"));
ui->heightSpinBox->setValue(p.get_int("height"));
ui->showRegionCheckBox->setChecked(p.get_int("show_region"));
ui->drawMouseCheckBox->setChecked(p.get_int("draw_mouse"));
ui->positionComboBox->setCurrentIndex(p.get_int("follow_mouse") + 1);
ui->audioComboBox->setCurrentIndex(p.get_int("audio_ix"));
on_audioComboBox_activated(p.get_int("audio_ix"));
}
void X11grabWidget::on_preset_selected(void *p)
{
Mlt::Properties *properties = (Mlt::Properties *) p;
loadPreset(*properties);
delete properties;
}
void X11grabWidget::on_preset_saveClicked()
{
ui->preset->savePreset(getPreset());
}
void X11grabWidget::setProducer(Mlt::Producer *producer)
{
ui->applyButton->show();
if (producer)
loadPreset(*producer);
}
void X11grabWidget::on_applyButton_clicked()
{
MLT.close();
AbstractProducerWidget::setProducer(0);
emit producerChanged(0);
QCoreApplication::processEvents();
Mlt::Producer *p = newProducer(MLT.profile());
AbstractProducerWidget::setProducer(p);
MLT.setProducer(p);
MLT.play();
emit producerChanged(p);
}
| 6,174
|
C++
|
.cpp
| 170
| 31.8
| 119
| 0.670952
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,221
|
playlistlistview.cpp
|
mltframework_shotcut/src/widgets/playlistlistview.cpp
|
/*
* Copyright (c) 2019-2022 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "playlistlistview.h"
#include <QDropEvent>
PlaylistListView::PlaylistListView(QWidget *parent)
: QListView(parent)
{
}
void PlaylistListView::dropEvent(QDropEvent *event)
{
QModelIndex index = indexAt(event->position().toPoint());
if (event->dropAction() == Qt::MoveAction && index.row() == -1) {
event->acceptProposedAction();
emit movedToEnd();
} else {
QListView::dropEvent(event);
}
}
void PlaylistListView::keyPressEvent(QKeyEvent *event)
{
// Ignore select all
if (event->key() == Qt::Key_A && event->modifiers() == Qt::ControlModifier) {
event->ignore();
return;
}
QListView::keyPressEvent(event);
event->ignore();
}
| 1,415
|
C++
|
.cpp
| 42
| 30.333333
| 81
| 0.710007
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,222
|
textproducerwidget.cpp
|
mltframework_shotcut/src/widgets/textproducerwidget.cpp
|
/*
* Copyright (c) 2018-2024 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <QColorDialog>
#include <QFileInfo>
#include <QFont>
#include "textproducerwidget.h"
#include "ui_textproducerwidget.h"
#include "shotcut_mlt_properties.h"
#include "util.h"
#include "mltcontroller.h"
static const QString kTransparent = QObject::tr("transparent", "Open Other > Color");
static const char *kSimpleFilterName = "dynamicText";
static const char *kRichFilterName = "richText";
static const int kPointSize = 60;
static QString colorToString(const QColor &color)
{
return (color == QColor(0, 0, 0, 0)) ? kTransparent
: QString::asprintf("#%02X%02X%02X%02X",
qAlpha(color.rgba()),
qRed(color.rgba()),
qGreen(color.rgba()),
qBlue(color.rgba()));
}
static QString colorStringToResource(const QString &s)
{
return (s == kTransparent) ? "#00000000" : s;
}
TextProducerWidget::TextProducerWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::TextProducerWidget)
{
ui->setupUi(this);
ui->colorLabel->setText(kTransparent);
Util::setColorsToHighlight(ui->label_2);
ui->preset->saveDefaultPreset(getPreset());
Mlt::Properties p;
p.set("resource", "#FF000000");
ui->preset->savePreset(p, tr("black"));
p.set("resource", "#00000000");
ui->preset->savePreset(p, tr("transparent"));
ui->preset->loadPresets();
}
TextProducerWidget::~TextProducerWidget()
{
delete ui;
}
void TextProducerWidget::on_colorButton_clicked()
{
QColor color = colorStringToResource(ui->colorLabel->text());
if (m_producer) {
color = QColor(QFileInfo(m_producer->get("resource")).baseName());
}
QColorDialog::ColorDialogOptions flags = QColorDialog::ShowAlphaChannel;
#if defined(Q_OS_UNIX) && !defined(Q_OS_MAC)
flags = flags | QColorDialog::DontUseNativeDialog;
#endif
auto newColor = QColorDialog::getColor(color, this, QString(), flags);
if (newColor.isValid()) {
auto rgb = newColor;
auto transparent = QColor(0, 0, 0, 0);
rgb.setAlpha(color.alpha());
if (newColor.alpha() == 0 && (rgb != color ||
(newColor == transparent && color == transparent))) {
newColor.setAlpha(255);
}
ui->colorLabel->setText(colorToString(newColor));
ui->colorLabel->setStyleSheet(QStringLiteral("color: %1; background-color: %2")
.arg(Util::textColor(newColor), newColor.name()));
if (m_producer) {
m_producer->set("resource", colorStringToResource(ui->colorLabel->text()).toLatin1().constData());
m_producer->set(kShotcutCaptionProperty, ui->colorLabel->text().toLatin1().constData());
m_producer->set(kShotcutDetailProperty, ui->colorLabel->text().toLatin1().constData());
emit producerChanged(m_producer.data());
}
}
}
Mlt::Producer *TextProducerWidget::newProducer(Mlt::Profile &profile)
{
Mlt::Producer *p = new Mlt::Producer(profile, "color:");
p->set("resource", colorStringToResource(ui->colorLabel->text()).toLatin1().constData());
p->set("mlt_image_format", "rgba");
MLT.setDurationFromDefault(p);
p->set(kShotcutCaptionProperty, ui->colorLabel->text().toLatin1().constData());
p->set(kShotcutDetailProperty, ui->colorLabel->text().toLatin1().constData());
QScopedPointer<Mlt::Filter> filter(createFilter(profile, p));
p->attach(*filter);
return p;
}
Mlt::Properties TextProducerWidget::getPreset() const
{
Mlt::Properties p;
QString color = colorStringToResource(ui->colorLabel->text());
p.set("resource", color.toLatin1().constData());
if (ui->richRadioButton->isChecked()) {
p.set("html", ui->plainTextEdit->toPlainText().toUtf8().constData());
} else {
p.set("argument", ui->plainTextEdit->toPlainText().toUtf8().constData());
}
return p;
}
void TextProducerWidget::loadPreset(Mlt::Properties &p)
{
QColor color(QFileInfo(p.get("resource")).baseName());
ui->colorLabel->setText(colorToString(color));
ui->colorLabel->setStyleSheet(QStringLiteral("color: %1; background-color: %2")
.arg(Util::textColor(color), color.name()));
if (qstrcmp("", p.get("html"))) {
ui->plainTextEdit->setPlainText(QString::fromUtf8(p.get("html")));
ui->richRadioButton->setChecked(true);
} else {
ui->plainTextEdit->setPlainText(QString::fromUtf8(p.get("argument")));
ui->simpleRadioButton->setChecked(true);
}
if (m_producer) {
m_producer->set("resource", colorStringToResource(ui->colorLabel->text()).toLatin1().constData());
m_producer->set(kShotcutCaptionProperty, ui->colorLabel->text().toLatin1().constData());
m_producer->set(kShotcutDetailProperty, ui->colorLabel->text().toLatin1().constData());
QScopedPointer<Mlt::Filter> filter;
filter.reset(MLT.getFilter(kSimpleFilterName, m_producer.data()));
if (filter && filter->is_valid())
m_producer->detach(*filter);
filter.reset(MLT.getFilter(kRichFilterName, m_producer.data()));
if (filter && filter->is_valid())
m_producer->detach(*filter);
filter.reset(createFilter(MLT.profile(), m_producer.data()));
m_producer->attach(*filter);
emit producerChanged(m_producer.data());
}
}
void TextProducerWidget::on_preset_selected(void *p)
{
Mlt::Properties *properties = (Mlt::Properties *) p;
loadPreset(*properties);
delete properties;
}
void TextProducerWidget::on_preset_saveClicked()
{
ui->preset->savePreset(getPreset());
}
Mlt::Filter *TextProducerWidget::createFilter(Mlt::Profile &profile, Mlt::Producer *p)
{
Mlt::Filter *filter = nullptr;
if (ui->richRadioButton->isChecked()) {
filter = new Mlt::Filter(profile, "qtext");
filter->set(kShotcutFilterProperty, kRichFilterName);
QString text = ui->plainTextEdit->toPlainText();
if (text.isEmpty())
text = tr("Edit your text using the Filters panel.");
QString html = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN"
"http://www.w3.org/TR/REC-html40/strict.dtd\">"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">"
"p, li { white-space: pre-wrap; }"
"</style></head><body style=\" font-family:'Verdana'; font-size:11pt; font-weight:normal; font-style:normal;\">"
#if defined(Q_OS_WIN)
"<p align=\"center\" style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\"font-family:Verdana; font-size:72pt; font-weight:normal; color:#ffffff;\">%1</span></p></body></html>";
#elif defined(Q_OS_MAC)
"<p align=\"center\" style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\"font-family:Helvetica; font-size:72pt; font-weight:normal; color:#ffffff;\">%1</span></p></body></html>";
#else
"<p align=\"center\" style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\"font-family:'sans-serif'; font-size:72pt; font-weight:normal; color:#ffffff;\">%1</span></p></body></html>";
#endif
html = html.arg(text);
filter->set("html", html.toUtf8().constData());
} else {
filter = new Mlt::Filter(profile, "dynamictext");
filter->set(kShotcutFilterProperty, kSimpleFilterName);
if (!ui->plainTextEdit->toPlainText().isEmpty())
filter->set("argument", ui->plainTextEdit->toPlainText().toUtf8().constData());
else
filter->set("argument", tr("Edit your text using the Filters panel.").toUtf8().constData());
}
#if defined(Q_OS_WIN)
filter->set("family", "Verdana");
#elif defined(Q_OS_MAC)
filter->set("family", "Helvetica");
#endif
filter->set("fgcolour", "#ffffffff");
filter->set("bgcolour", "#00000000");
filter->set("olcolour", "#aa000000");
filter->set("outline", 3);
filter->set("weight", QFont::Bold * 10);
filter->set("style", "normal");
filter->set("shotcut:usePointSize", 1);
filter->set("shotcut:pointSize", kPointSize);
QFont font(filter->get("family"), kPointSize, filter->get_int("weight"));
filter->set("size", QFontInfo(font).pixelSize());
filter->set("geometry", QStringLiteral("0 %1 %2 %3 1")
.arg(qRound(0.75 * profile.height()))
.arg(profile.width())
.arg(profile.height() * 0.25)
.toUtf8().constData());
filter->set("valign", "top");
filter->set("halign", "center");
filter->set_in_and_out(p->get_in(), p->get_out());
return filter;
}
| 9,653
|
C++
|
.cpp
| 209
| 39.397129
| 284
| 0.645001
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,223
|
countproducerwidget.cpp
|
mltframework_shotcut/src/widgets/countproducerwidget.cpp
|
/*
* Copyright (c) 2016-2022 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "shotcut_mlt_properties.h"
#include "countproducerwidget.h"
#include "ui_countproducerwidget.h"
#include "util.h"
#include "mltcontroller.h"
#include <MltProfile.h>
void setLength(Mlt::Properties *p, int length)
{
p->set("length", p->frames_to_time(length, mlt_time_clock));
p->set("out", length - 1);
p->set("in", 0);
}
CountProducerWidget::CountProducerWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::CountProducerWidget)
{
ui->setupUi(this);
Util::setColorsToHighlight(ui->nameLabel);
ui->directionCombo->addItem(tr("Down"), QVariant("down"));
ui->directionCombo->addItem(tr("Up"), QVariant("up"));
ui->directionCombo->setCurrentIndex(0);
ui->styleCombo->addItem(tr("Seconds"), QVariant("seconds"));
ui->styleCombo->addItem(tr("Seconds + 1"), QVariant("seconds+1"));
ui->styleCombo->addItem(tr("Frames"), QVariant("frames"));
ui->styleCombo->addItem(tr("Timecode"), QVariant("timecode"));
ui->styleCombo->addItem(tr("Clock"), QVariant("clock"));
ui->styleCombo->setCurrentIndex(0);
ui->soundCombo->addItem(tr("2-Pop"), QVariant("2pop"));
ui->soundCombo->addItem(tr("Silent"), QVariant("silent"));
ui->soundCombo->addItem(tr("Frame 0"), QVariant("frame0"));
ui->soundCombo->setCurrentIndex(0);
ui->backgroundCombo->addItem(tr("Clock"), QVariant("clock"));
ui->backgroundCombo->addItem(tr("None"), QVariant("none"));
ui->backgroundCombo->setCurrentIndex(0);
ui->dropCheckBox->setChecked(true);
ui->durationSpinBox->setValue(qRound(MLT.profile().fps() * 10.0)); // 10 seconds
ui->preset->saveDefaultPreset(getPreset());
ui->preset->loadPresets();
}
CountProducerWidget::~CountProducerWidget()
{
delete ui;
}
QString CountProducerWidget::currentDirection() const
{
return ui->directionCombo->itemData(ui->directionCombo->currentIndex()).toString();
}
QString CountProducerWidget::currentStyle() const
{
return ui->styleCombo->itemData(ui->styleCombo->currentIndex()).toString();
}
QString CountProducerWidget::currentSound() const
{
return ui->soundCombo->itemData(ui->soundCombo->currentIndex()).toString();
}
QString CountProducerWidget::currentBackground() const
{
return ui->backgroundCombo->itemData(ui->backgroundCombo->currentIndex()).toString();
}
Mlt::Producer *CountProducerWidget::newProducer(Mlt::Profile &profile)
{
Mlt::Producer *p = new Mlt::Producer(profile, "count");
p->set("direction", currentDirection().toLatin1().constData());
p->set("style", currentStyle().toLatin1().constData());
p->set("sound", currentSound().toLatin1().constData());
p->set("background", currentBackground().toLatin1().constData());
p->set("drop", ui->dropCheckBox->isChecked());
setLength(p, ui->durationSpinBox->value());
p->set(kShotcutCaptionProperty, ui->nameLabel->text().toUtf8().constData());
p->set(kShotcutDetailProperty, detail().toUtf8().constData());
return p;
}
Mlt::Properties CountProducerWidget::getPreset() const
{
Mlt::Properties p;
p.set("direction", currentDirection().toLatin1().constData());
p.set("style", currentStyle().toLatin1().constData());
p.set("sound", currentSound().toLatin1().constData());
p.set("background", currentBackground().toLatin1().constData());
p.set("drop", ui->dropCheckBox->isChecked());
setLength(&p, ui->durationSpinBox->value());
return p;
}
void CountProducerWidget::loadPreset(Mlt::Properties &p)
{
if (!p.get("direction") || !p.get("style")) return;
int index = -1;
index = ui->directionCombo->findData(QVariant(QString::fromLatin1(p.get("direction"))));
ui->directionCombo->setCurrentIndex(index);
index = ui->styleCombo->findData(QVariant(QString::fromLatin1(p.get("style"))));
ui->styleCombo->setCurrentIndex(index);
index = ui->soundCombo->findData(QVariant(QString::fromLatin1(p.get("sound"))));
ui->soundCombo->setCurrentIndex(index);
index = ui->backgroundCombo->findData(QVariant(QString::fromLatin1(p.get("background"))));
ui->backgroundCombo->setCurrentIndex(index);
ui->dropCheckBox->setChecked(p.get("drop"));
ui->durationSpinBox->setValue(p.get_int("length"));
if (m_producer) {
m_producer->set("direction", p.get("direction"));
m_producer->set("style", p.get("style"));
m_producer->set("sound", p.get("sound"));
m_producer->set("background", p.get("background"));
m_producer->set("drop", p.get("drop"));
setLength(producer(), ui->durationSpinBox->value());
m_producer->set(kShotcutDetailProperty, detail().toUtf8().constData());
emit producerChanged(producer());
}
}
void CountProducerWidget::on_directionCombo_activated(int /*index*/)
{
if (m_producer) {
m_producer->set("direction", currentDirection().toLatin1().constData());
m_producer->set(kShotcutDetailProperty, detail().toUtf8().constData());
emit producerChanged(producer());
}
}
void CountProducerWidget::on_styleCombo_activated(int /*index*/)
{
if (m_producer) {
m_producer->set("style", currentStyle().toLatin1().constData());
m_producer->set(kShotcutDetailProperty, detail().toUtf8().constData());
emit producerChanged(producer());
}
}
void CountProducerWidget::on_soundCombo_activated(int /*index*/)
{
if (m_producer) {
m_producer->set("sound", currentSound().toLatin1().constData());
emit producerChanged(producer());
}
}
void CountProducerWidget::on_backgroundCombo_activated(int /*index*/)
{
if (m_producer) {
m_producer->set("background", currentBackground().toLatin1().constData());
emit producerChanged(producer());
}
}
void CountProducerWidget::on_dropCheckBox_clicked(bool checked)
{
if (m_producer) {
m_producer->set("drop", checked);
emit producerChanged(producer());
}
}
void CountProducerWidget::on_durationSpinBox_editingFinished()
{
if (!m_producer)
return;
if (ui->durationSpinBox->value() == m_producer->get_length())
return;
if (m_producer) {
setLength(producer(), ui->durationSpinBox->value());
MLT.stop();
emit producerReopened(false);
emit producerChanged(producer());
MLT.seek(0);
}
}
void CountProducerWidget::on_preset_selected(void *p)
{
Mlt::Properties *properties = (Mlt::Properties *) p;
loadPreset(*properties);
delete properties;
}
void CountProducerWidget::on_preset_saveClicked()
{
ui->preset->savePreset(getPreset());
}
QString CountProducerWidget::detail() const
{
return tr("Count: %1 %2").arg(ui->directionCombo->currentText()).arg(
ui->styleCombo->currentText());
}
| 7,437
|
C++
|
.cpp
| 190
| 34.921053
| 94
| 0.694718
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,224
|
docktoolbar.cpp
|
mltframework_shotcut/src/widgets/docktoolbar.cpp
|
/*
* Copyright (c) 2022 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your tbOption) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "docktoolbar.h"
#include "settings.h"
#include <QPainter>
#include <QStyle>
#include <QStyleOptionToolBar>
#include <QDebug>
DockToolBar::DockToolBar(const QString &title, QWidget *parent)
: QToolBar(title, parent)
, m_area(Qt::TopToolBarArea)
{
setMovable(false);
setToolButtonStyle(Qt::ToolButtonFollowStyle);
setFloatable(false);
setProperty("Movable", QVariant(false));
updateStyle();
connect(&Settings, SIGNAL(smallIconsChanged()), SLOT(updateStyle()));
}
void DockToolBar::setAreaHint(Qt::ToolBarArea area)
{
m_area = area;
}
void DockToolBar::paintEvent(QPaintEvent *event)
{
QPainter p(this);
QLinearGradient gradient = QLinearGradient(rect().left(), rect().center().y(),
rect().right(), rect().center().y());
gradient.setColorAt(0, palette().window().color().lighter(104));
gradient.setColorAt(1, palette().window().color());
p.fillRect(rect(), gradient);
if (m_area == Qt::TopToolBarArea) {
// Apply the same styling that is applied to main window toolbars.
// This creates extra lines of separation between the toolbar and the
// dock contents.
QColor light = QColor(255, 255, 255, 90);
QColor shadow = QColor(0, 0, 0, 60);
p.setPen(shadow);
p.drawLine(rect().bottomLeft(), rect().bottomRight());
p.setPen(light);
p.drawLine(rect().topLeft(), rect().topRight());
}
}
void DockToolBar::updateStyle()
{
int height = 33;
if (Settings.smallIcons()) {
height = 25;
}
setFixedHeight(height);
setIconSize(QSize(height - 9, height - 9));
QString styleSheet = QString::fromUtf8( " \
QToolButton { \
width:%1px; \
height:%1px; \
} \
QToolButton[popupMode=\"1\"] { \
padding-right: 12px; \
} \
QToolButton:checked { \
color:palette(highlighted-text); \
background-color:palette(highlight); \
} \
QToolBar { \
spacing:3px; \
padding:1px; \
} \
").arg(height - 9);
setStyleSheet(styleSheet);
}
| 3,225
|
C++
|
.cpp
| 84
| 32.642857
| 84
| 0.575168
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,225
|
glaxnimateproducerwidget.cpp
|
mltframework_shotcut/src/widgets/glaxnimateproducerwidget.cpp
|
/*
* Copyright (c) 2022-2024 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <QColorDialog>
#include <QFileInfo>
#include "glaxnimateproducerwidget.h"
#include "mainwindow.h"
#include "settings.h"
#include "ui_glaxnimateproducerwidget.h"
#include "shotcut_mlt_properties.h"
#include "util.h"
#include "mltcontroller.h"
#include "qmltypes/qmlapplication.h"
#include "dialogs/longuitask.h"
#include "videowidget.h"
#include <Logger.h>
#include <QProcess>
#include <QFile>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QFileSystemWatcher>
#include <QMessageBox>
#include <QtConcurrent/QtConcurrentRun>
#include <QFuture>
static const QString kTransparent = QObject::tr("transparent", "Open Other > Animation");
static QString colorToString(const QColor &color)
{
return (color == QColor(0, 0, 0, 0)) ? kTransparent
: QString::asprintf("#%02X%02X%02X%02X",
qAlpha(color.rgba()),
qRed(color.rgba()),
qGreen(color.rgba()),
qBlue(color.rgba()));
}
static QString colorStringToResource(const QString &s)
{
return (s == kTransparent) ? "#00000000" : s;
}
GlaxnimateProducerWidget::GlaxnimateProducerWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::GlaxnimateProducerWidget)
{
ui->setupUi(this);
m_title = ui->lineEdit->text();
ui->colorLabel->setText(kTransparent);
Util::setColorsToHighlight(ui->lineEdit, QPalette::Base);
ui->preset->saveDefaultPreset(getPreset());
Mlt::Properties p;
p.set("background", "#FF000000");
ui->preset->savePreset(p, tr("black"));
p.set("background", "#00000000");
ui->preset->savePreset(p, tr("transparent"));
ui->preset->loadPresets();
ui->notesLabel->setVisible(false);
ui->notesTextEdit->setVisible(false);
ui->editButton->setVisible(false);
ui->reloadButton->setVisible(false);
ui->durationSpinBox->setValue(qRound(5.0 * MLT.profile().fps()));
}
GlaxnimateProducerWidget::~GlaxnimateProducerWidget()
{
GlaxnimateIpcServer::instance().reset();
delete ui;
}
void GlaxnimateProducerWidget::on_colorButton_clicked()
{
QColor color = colorStringToResource(ui->colorLabel->text());
if (m_producer) {
color = QColor(QFileInfo(m_producer->get("background")).baseName());
}
QColorDialog::ColorDialogOptions flags = QColorDialog::ShowAlphaChannel;
#if defined(Q_OS_UNIX) && !defined(Q_OS_MAC)
flags = flags | QColorDialog::DontUseNativeDialog;
#endif
auto newColor = QColorDialog::getColor(color, this, QString(), flags);
if (newColor.isValid()) {
auto rgb = newColor;
auto transparent = QColor(0, 0, 0, 0);
rgb.setAlpha(color.alpha());
if (newColor.alpha() == 0 && (rgb != color ||
(newColor == transparent && color == transparent))) {
newColor.setAlpha(255);
}
ui->colorLabel->setText(colorToString(newColor));
ui->colorLabel->setStyleSheet(QStringLiteral("color: %1; background-color: %2")
.arg(Util::textColor(newColor), newColor.name()));
if (m_producer) {
m_producer->set("background", colorStringToResource(ui->colorLabel->text()).toLatin1().constData());
emit producerChanged(m_producer.get());
}
}
}
static void modifyJsonValue(QJsonValue &destValue, const QString &path, const QJsonValue &newValue)
{
const int indexOfDot = path.indexOf('.');
const QString dotPropertyName = path.left(indexOfDot);
const QString dotSubPath = indexOfDot > 0 ? path.mid(indexOfDot + 1) : QString();
const int indexOfSquareBracketOpen = path.indexOf('[');
const int indexOfSquareBracketClose = path.indexOf(']');
const int arrayIndex = path.mid(indexOfSquareBracketOpen + 1,
indexOfSquareBracketClose - indexOfSquareBracketOpen - 1).toInt();
const QString squareBracketPropertyName = path.left(indexOfSquareBracketOpen);
const QString squareBracketSubPath = indexOfSquareBracketClose > 0 ? (path.mid(
indexOfSquareBracketClose + 1)[0] == '.' ? path.mid(indexOfSquareBracketClose + 2) : path.mid(
indexOfSquareBracketClose + 1)) : QString();
// determine what is first in path. dot or bracket
bool useDot = true;
if (indexOfDot >= 0) { // there is a dot in path
if (indexOfSquareBracketOpen >= 0) { // there is squarebracket in path
if (indexOfDot > indexOfSquareBracketOpen)
useDot = false;
else
useDot = true;
} else {
useDot = true;
}
} else {
if (indexOfSquareBracketOpen >= 0)
useDot = false;
else
useDot = true; // actually, id doesn't matter, both dot and square bracket don't exist
}
QString usedPropertyName = useDot ? dotPropertyName : squareBracketPropertyName;
QString usedSubPath = useDot ? dotSubPath : squareBracketSubPath;
QJsonValue subValue;
if (destValue.isArray()) {
subValue = destValue.toArray()[usedPropertyName.toInt()];
} else if (destValue.isObject()) {
subValue = destValue.toObject()[usedPropertyName];
} else {
LOG_WARNING() << "unable to handle" << destValue;
}
if (usedSubPath.isEmpty()) {
subValue = newValue;
} else {
if (subValue.isArray()) {
QJsonArray arr = subValue.toArray();
QJsonValue arrEntry = arr[arrayIndex];
modifyJsonValue(arrEntry, usedSubPath, newValue);
arr[arrayIndex] = arrEntry;
subValue = arr;
} else if (subValue.isObject()) {
modifyJsonValue(subValue, usedSubPath, newValue);
} else {
subValue = newValue;
}
}
if (destValue.isArray()) {
QJsonArray arr = destValue.toArray();
arr[arrayIndex] = subValue;
destValue = arr;
} else if (destValue.isObject()) {
QJsonObject obj = destValue.toObject();
obj[usedPropertyName] = subValue;
destValue = obj;
} else {
destValue = newValue;
}
}
Mlt::Producer *GlaxnimateProducerWidget::newProducer(Mlt::Profile &profile)
{
// Get the file name.
auto filename = QmlApplication::getNextProjectFile("anim.rawr");
if (filename.isEmpty()) {
QString path = Settings.savePath();
path.append("/%1.rawr");
path = path.arg(tr("animation"));
auto nameFilter = tr("Glaxnimate (*.rawr);;All Files (*)");
filename = QFileDialog::getSaveFileName(this, tr("New Animation"), path, nameFilter,
nullptr, Util::getFileDialogOptions());
}
if (filename.isEmpty()) {
return nullptr;
}
if (!filename.endsWith(".rawr")) {
filename += ".rawr";
}
auto info = QFileInfo(filename);
Settings.setSavePath(info.path());
GlaxnimateIpcServer::instance().newFile(filename, ui->durationSpinBox->value());
Mlt::Producer *p = new Mlt::Producer(profile,
QStringLiteral("glaxnimate:").append(filename).toUtf8().constData());
p->set("background", colorStringToResource(ui->colorLabel->text()).toLatin1().constData());
m_title = info.fileName();
p->set(kShotcutCaptionProperty, m_title.toUtf8().constData());
p->set(kShotcutDetailProperty, filename.toUtf8().constData());
m_watcher.reset(new QFileSystemWatcher({filename}));
connect(m_watcher.get(), &QFileSystemWatcher::fileChanged, this,
&GlaxnimateProducerWidget::onFileChanged);
GlaxnimateIpcServer::instance().launch(p);
return p;
}
void GlaxnimateProducerWidget::setProducer(Mlt::Producer *p)
{
AbstractProducerWidget::setProducer(p);
ui->notesLabel->setVisible(true);
ui->notesTextEdit->setVisible(true);
ui->notesTextEdit->setPlainText(QString::fromUtf8(p->get(kCommentProperty)));
ui->editButton->setVisible(true);
ui->reloadButton->setVisible(true);
auto filename = QString::fromUtf8(p->get("resource"));
m_title = QFileInfo(filename).fileName();
if (QString::fromUtf8(p->get(kShotcutCaptionProperty)).isEmpty()) {
p->set(kShotcutCaptionProperty, m_title.toUtf8().constData());
}
ui->lineEdit->setText(QString::fromUtf8(p->get(kShotcutCaptionProperty)));
ui->durationSpinBox->setValue(p->get_length());
m_watcher.reset(new QFileSystemWatcher({filename}));
connect(m_watcher.get(), &QFileSystemWatcher::fileChanged, this,
&GlaxnimateProducerWidget::onFileChanged);
}
Mlt::Properties GlaxnimateProducerWidget::getPreset() const
{
Mlt::Properties p;
QString color = colorStringToResource(ui->colorLabel->text());
p.set("background", color.toLatin1().constData());
return p;
}
void GlaxnimateProducerWidget::loadPreset(Mlt::Properties &p)
{
QColor color(QFileInfo(p.get("background")).baseName());
ui->colorLabel->setText(colorToString(color));
ui->colorLabel->setStyleSheet(QStringLiteral("color: %1; background-color: %2")
.arg(Util::textColor(color), color.name()));
if (m_producer) {
m_producer->set("background", colorStringToResource(ui->colorLabel->text()).toLatin1().constData());
emit producerChanged(m_producer.get());
}
}
void GlaxnimateProducerWidget::rename()
{
ui->lineEdit->setFocus();
ui->lineEdit->selectAll();
}
void GlaxnimateProducerWidget::on_preset_selected(void *p)
{
Mlt::Properties *properties = (Mlt::Properties *) p;
loadPreset(*properties);
delete properties;
}
void GlaxnimateProducerWidget::on_preset_saveClicked()
{
ui->preset->savePreset(getPreset());
}
void GlaxnimateProducerWidget::on_lineEdit_editingFinished()
{
if (m_producer) {
auto caption = ui->lineEdit->text();
if (caption.isEmpty()) {
caption = m_title;
ui->lineEdit->setText(m_title);
}
m_producer->set(kShotcutCaptionProperty, caption.toUtf8().constData());
emit modified();
}
}
void GlaxnimateProducerWidget::on_notesTextEdit_textChanged()
{
if (m_producer && m_producer->is_valid()) {
QString existing = QString::fromUtf8(m_producer->get(kCommentProperty));
if (ui->notesTextEdit->toPlainText() != existing) {
m_producer->set(kCommentProperty, ui->notesTextEdit->toPlainText().toUtf8().constData());
emit modified();
}
}
}
void GlaxnimateProducerWidget::on_editButton_clicked()
{
if (m_producer && m_producer->is_valid()) {
GlaxnimateIpcServer::instance().launch(*producer());
}
}
void GlaxnimateProducerWidget::onFileChanged(const QString &path)
{
if (!m_watcher->files().contains(path)) {
m_watcher->addPath(path);
}
if (m_producer && m_producer->is_valid()) {
m_producer->set("resource", path.toUtf8().constData());
auto caption = QFileInfo(path).fileName();
if (QString::fromUtf8(m_producer->get(kShotcutCaptionProperty)) == m_title) {
m_producer->set(kShotcutCaptionProperty, caption.toUtf8().constData());
}
m_title = caption;
m_producer->set("refresh", 1);
MLT.refreshConsumer();
QTimer::singleShot(1000, [this]() {
if (ui->durationSpinBox->value() != m_producer->get_length()) {
ui->durationSpinBox->setValue(m_producer->get_length());
on_durationSpinBox_editingFinished();
}
});
}
}
void GlaxnimateProducerWidget::on_reloadButton_clicked()
{
if (m_producer && m_producer->is_valid()) {
m_producer->set("refresh", 1);
MLT.refreshConsumer();
QTimer::singleShot(1000, [this]() {
if (ui->durationSpinBox->value() != m_producer->get_length()) {
ui->durationSpinBox->setValue(m_producer->get_length());
on_durationSpinBox_editingFinished();
}
});
}
}
void GlaxnimateProducerWidget::on_durationSpinBox_editingFinished()
{
if (m_producer && m_producer->is_valid()) {
m_producer->set("length", m_producer->frames_to_time(ui->durationSpinBox->value(), mlt_time_clock));
emit producerChanged(m_producer.get());
}
}
void GlaxnimateIpcServer::ParentResources::setProducer(const Mlt::Producer &producer,
bool hideCurrentTrack)
{
m_producer = producer;
if (!m_producer.get(kMultitrackItemProperty) && !m_producer.get(kTrackIndexProperty))
return;
m_profile.reset(new Mlt::Profile(::mlt_profile_clone(MLT.profile().get_profile())));
m_profile->set_progressive(Settings.playerProgressive());
m_glaxnimateProducer.reset(new Mlt::Producer(*m_profile, "xml-string",
MLT.XML().toUtf8().constData()));
if (m_glaxnimateProducer && m_glaxnimateProducer->is_valid()) {
m_frameNum = -1;
// hide this clip's video track and upper ones
int trackIndex = m_producer.get_int(kTrackIndexProperty);
QString s = QString::fromLatin1(m_producer.get(kMultitrackItemProperty));
auto parts = s.split(':');
if (parts.length() == 2) {
trackIndex = parts[1].toInt();
}
if (hideCurrentTrack && trackIndex == MAIN.bottomVideoTrackIndex()) {
// Disable preview in Glaxnimate
m_glaxnimateProducer.reset();
m_profile.reset();
GlaxnimateIpcServer::instance().copyToShared(QImage());
return;
}
auto offset = hideCurrentTrack ? 1 : 0;
Mlt::Tractor tractor(*m_glaxnimateProducer);
// for each upper video track plus this one
for (int i = 0; i < trackIndex + offset; i++) {
// get the MLT track index
auto index = MAIN.mltIndexForTrack(i);
// get the MLT track in this copy
std::unique_ptr<Mlt::Producer> track(tractor.track(index));
if (track && track->is_valid()) {
// hide the track
track->set("hide", 3);
}
}
// Disable the glaxnimate filter and below
if (!hideCurrentTrack) {
std::unique_ptr<Mlt::Producer> track(tractor.track(MAIN.mltIndexForTrack(trackIndex)));
if (track && track->is_valid()) {
auto clipIndex = parts[0].toInt();
Mlt::Playlist playlist(*track);
std::unique_ptr<Mlt::ClipInfo> info(playlist.clip_info(clipIndex));
if (info && info->producer && info->producer->is_valid()) {
auto count = info->producer->filter_count();
bool found = false;
for (int i = 0; i < count; i++) {
std::unique_ptr<Mlt::Filter> filter(info->producer->filter(i));
if (filter && filter->is_valid()) {
if (found || !qstrcmp(filter->get(kShotcutFilterProperty), "maskGlaxnimate")) {
found = true;
filter->set("disable", 1);
}
}
}
}
}
}
}
}
void GlaxnimateIpcServer::onConnect()
{
LOG_DEBUG() << "";
m_socket = m_server->nextPendingConnection();
connect(m_socket.data(), &QLocalSocket::readyRead, this, &GlaxnimateIpcServer::onReadyRead);
connect(m_socket.data(), &QLocalSocket::errorOccurred, this, &GlaxnimateIpcServer::onSocketError);
m_stream.reset(new QDataStream(m_socket.data()));
m_stream->setVersion(QDataStream::Qt_5_15);
*m_stream << QStringLiteral("hello");
m_socket->flush();
m_server->close();
m_isProtocolValid = false;
}
int GlaxnimateIpcServer::toMltFps(float frame) const
{
if (parent->m_producer.get_double("meta.media.frame_rate") > 0) {
return qRound(frame / parent->m_producer.get_double("meta.media.frame_rate") * MLT.profile().fps());
}
return frame;
}
void GlaxnimateIpcServer::onReadyRead()
{
if (!m_isProtocolValid) {
QString message;
*m_stream >> message;
LOG_DEBUG() << message;
if (message.startsWith("version ") && message != "version 1") {
*m_stream << QStringLiteral("bye");
m_socket->flush();
m_server->close();
} else {
m_isProtocolValid = true;
}
}
if (m_isProtocolValid && parent) {
qreal time = -1.0;
for (int i = 0; i < 1000 && !m_stream->atEnd(); i++) {
*m_stream >> time;
}
// Only if the frame number is different
int frameNum = parent->m_producer.get_int(kPlaylistStartProperty) + toMltFps(
time) - parent->m_producer.get_int("first_frame");
if (frameNum != parent->m_frameNum) {
LOG_DEBUG() << "glaxnimate time =" << time << "=> Shotcut frameNum =" << frameNum;
if (!parent || !parent->m_glaxnimateProducer
|| !parent->m_glaxnimateProducer->is_valid()
|| time < 0.0) {
MLT.seek(frameNum);
return;
}
// Get the image from MLT
parent->m_glaxnimateProducer->seek(frameNum);
std::unique_ptr<Mlt::Frame> frame(parent->m_glaxnimateProducer->get_frame());
// Use preview scaling
#ifdef Q_OS_MAC
int scale = Settings.playerPreviewScale() ? Settings.playerPreviewScale() : 720;
#else
int scale = Settings.playerPreviewScale() ? Settings.playerPreviewScale() : 2160;
#endif
auto height = qMin(scale, MLT.profile().height());
auto width = (height == MLT.profile().height()) ? MLT.profile().width() :
Util::coerceMultiple(height * MLT.profile().display_aspect_num() /
MLT.profile().display_aspect_den()
* MLT.profile().sample_aspect_den() / MLT.profile().sample_aspect_num());
frame->set("consumer.deinterlacer", Settings.playerDeinterlacer().toLatin1().constData());
frame->set("consumer.top_field_first", -1);
mlt_image_format format = mlt_image_rgb;
const uchar *image = frame->get_image(format, width, height);
if (image) {
QImage temp(width, height, QImage::Format_RGB888);
for (int i = 0; i < height; i++) {
::memcpy(temp.scanLine(i), &image[i * 3 * width], temp.bytesPerLine());
}
if (MLT.profile().sar() - 1.0 > 0.0001) {
// Use QImage to convert to square pixels
width = qRound(width * MLT.profile().sar());
temp = temp.scaled(width, height, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
}
if (copyToShared(temp)) {
parent->m_frameNum = frameNum;
}
}
}
}
}
void GlaxnimateIpcServer::onSocketError(QLocalSocket::LocalSocketError socketError)
{
switch (socketError) {
case QLocalSocket::PeerClosedError:
LOG_DEBUG() << "Glaxnimate closed the connection";
m_stream.reset();
m_sharedMemory.reset();
break;
default:
LOG_INFO() << "Glaxnimate IPC error:" << m_socket->errorString();
}
}
void GlaxnimateIpcServer::onFrameDisplayed(const SharedFrame &frame)
{
auto image = frame.get_image(mlt_image_rgb);
if (image) {
auto width = frame.get_image_width();
auto height = frame.get_image_height();
QImage temp(width, height, QImage::Format_RGB888);
for (int i = 0; i < height; i++) {
::memcpy(temp.scanLine(i), &image[i * 3 * width], temp.bytesPerLine());
}
if (copyToShared(temp) && parent) {
parent->m_frameNum = frame.get_position();
}
}
}
GlaxnimateIpcServer &GlaxnimateIpcServer::instance()
{
static GlaxnimateIpcServer instance;
return instance;
}
void GlaxnimateIpcServer::newFile(const QString &filename, int duration)
{
QFile rawr(QStringLiteral(":/resources/glaxnimate.rawr"));
rawr.open(QIODevice::ReadOnly);
auto data = rawr.readAll();
auto json = QJsonDocument::fromJson(data).object();
rawr.close();
QJsonValue jsonValue(json);
modifyJsonValue(jsonValue, "animation.name", QFileInfo(filename).completeBaseName());
modifyJsonValue(jsonValue, "animation.width", qRound(MLT.profile().width() * MLT.profile().sar()));
modifyJsonValue(jsonValue, "animation.height", MLT.profile().height());
modifyJsonValue(jsonValue, "animation.fps", MLT.profile().fps());
modifyJsonValue(jsonValue, "animation.animation.last_frame", duration);
modifyJsonValue(jsonValue, "animation.shapes[0].animation.last_frame", duration);
json = jsonValue.toObject();
rawr.setFileName(filename);
rawr.open(QIODevice::WriteOnly);
rawr.write(QJsonDocument(json).toJson());
rawr.close();
}
void GlaxnimateIpcServer::reset()
{
if (m_stream && m_socket && m_stream && QLocalSocket::ConnectedState == m_socket->state()) {
*m_stream << QStringLiteral("clear");
m_socket->flush();
}
parent.reset();
}
void GlaxnimateIpcServer::launch(const Mlt::Producer &producer, QString filename,
bool hideCurrentTrack)
{
parent.reset(new ParentResources);
if (Settings.playerGPU()) {
parent->m_producer = producer;
connect(qobject_cast<Mlt::VideoWidget *>(MLT.videoWidget()), &Mlt::VideoWidget::frameDisplayed,
this, &GlaxnimateIpcServer::onFrameDisplayed);
} else {
LongUiTask longTask(QObject::tr("Edit With Glaxnimate"));
auto future = QtConcurrent::run([this, &producer, &hideCurrentTrack]() {
parent->setProducer(producer, hideCurrentTrack);
return true;
});
longTask.wait<bool>(tr("Preparing Glaxnimate preview...."), future);
}
if (filename.isEmpty()) {
filename = QString::fromUtf8(parent->m_producer.get("resource"));
}
if (m_server && m_socket && m_stream && QLocalSocket::ConnectedState == m_socket->state()) {
auto s = QStringLiteral("open ").append(filename);
LOG_DEBUG() << s;
*m_stream << s;
m_socket->flush();
parent->m_frameNum = -1;
return;
}
m_server.reset(new QLocalServer);
connect(m_server.get(), &QLocalServer::newConnection, this, &GlaxnimateIpcServer::onConnect);
QString name = "shotcut-%1";
name = name.arg(QCoreApplication::applicationPid());
QStringList args = {"--ipc", name, filename};
QProcess childProcess;
QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
env.remove("LC_ALL");
childProcess.setProcessEnvironment(env);
childProcess.setProgram(Settings.glaxnimatePath());
if (!m_server->listen(name)) {
LOG_ERROR() << "failed to start the IPC server:" << m_server->errorString();
m_server.reset();
args.clear();
args << filename;
// Run without --ipc
} else {
childProcess.setArguments(args);
if (childProcess.startDetached()) {
LOG_DEBUG() << Settings.glaxnimatePath() << args.join(' ');
m_sharedMemory.reset(new QSharedMemory(name));
return;
} else {
// This glaxnimate executable may not support --ipc
//XXX startDetached is not failing in this case, need something better
m_server.reset();
args.clear();
args << filename;
// Try without --ipc
}
}
LOG_DEBUG() << Settings.glaxnimatePath() << args.join(' ');
childProcess.setArguments(args);
if (!childProcess.startDetached()) {
LOG_DEBUG() << "failed to launch Glaxnimate with" << Settings.glaxnimatePath();
QMessageBox dialog(QMessageBox::Information,
qApp->applicationName(),
tr("The Glaxnimate program was not found.\n\n"
"Click OK to open a file dialog to choose its location.\n"
"Click Cancel if you do not have Glaxnimate."),
QMessageBox::Ok | QMessageBox::Cancel,
MAIN.window());
dialog.setDefaultButton(QMessageBox::Ok);
dialog.setEscapeButton(QMessageBox::Cancel);
dialog.setWindowModality(QmlApplication::dialogModality());
if (dialog.exec() == QMessageBox::Ok) {
auto path = QFileDialog::getOpenFileName(MAIN.window(), tr("Find Glaxnimate"), QString(), QString(),
nullptr, Util::getFileDialogOptions());
if (!path.isEmpty()) {
args.clear();
args << "--ipc" << name << filename;
childProcess.setProgram(path);
childProcess.setArguments(args);
if (childProcess.startDetached()) {
LOG_DEBUG() << Settings.glaxnimatePath() << args.join(' ');
Settings.setGlaxnimatePath(path);
LOG_INFO() << "changed Glaxnimate path to" << path;
m_sharedMemory.reset(new QSharedMemory(name));
return;
} else {
// This glaxnimate executable may not support --ipc
m_server.reset();
args.clear();
args << filename;
// Try without --ipc
childProcess.setArguments(args);
if (childProcess.startDetached()) {
LOG_DEBUG() << Settings.glaxnimatePath() << args.join(' ');
} else {
LOG_WARNING() << "failed to launch Glaxnimate with" << path;
}
}
}
}
}
}
bool GlaxnimateIpcServer::copyToShared(const QImage &image)
{
if (!m_sharedMemory) {
return false;
}
qint32 sizeInBytes = image.sizeInBytes() + 4 * sizeof(qint32);
if (sizeInBytes > m_sharedMemory->size()) {
if (m_sharedMemory->isAttached()) {
m_sharedMemory->lock();
m_sharedMemory->detach();
m_sharedMemory->unlock();
}
// over-allocate to avoid recreating
if (!m_sharedMemory->create(sizeInBytes)) {
LOG_WARNING() << m_sharedMemory->errorString();
return false;
}
}
if (m_sharedMemory->isAttached()) {
m_sharedMemory->lock();
uchar *to = (uchar *) m_sharedMemory->data();
// Write the width of the image and move the pointer forward
qint32 width = image.width();
::memcpy(to, &width, sizeof(width));
to += sizeof(width);
// Write the height of the image and move the pointer forward
qint32 height = image.height();
::memcpy(to, &height, sizeof(height));
to += sizeof(height);
// Write the image format of the image and move the pointer forward
qint32 imageFormat = image.format();
::memcpy(to, &imageFormat, sizeof(imageFormat));
to += sizeof(imageFormat);
// Write the bytes per line of the image and move the pointer forward
qint32 bytesPerLine = image.bytesPerLine();
::memcpy(to, &bytesPerLine, sizeof(bytesPerLine));
to += sizeof(bytesPerLine);
// Write the raw data of the image and move the pointer forward
::memcpy(to, image.constBits(), image.sizeInBytes());
m_sharedMemory->unlock();
if (m_stream && m_socket) {
*m_stream << QStringLiteral("redraw");
m_socket->flush();
}
return true;
}
return false;
}
| 29,657
|
C++
|
.cpp
| 687
| 33.007278
| 173
| 0.59292
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,226
|
noisewidget.cpp
|
mltframework_shotcut/src/widgets/noisewidget.cpp
|
/*
* Copyright (c) 2012-2017 Meltytech, LLC
* Author: Dan Dennedy <dan@dennedy.org>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "shotcut_mlt_properties.h"
#include "noisewidget.h"
#include "ui_noisewidget.h"
#include "util.h"
NoiseWidget::NoiseWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::NoiseWidget)
{
ui->setupUi(this);
Util::setColorsToHighlight(ui->nameLabel);
}
NoiseWidget::~NoiseWidget()
{
delete ui;
}
Mlt::Producer *NoiseWidget::newProducer(Mlt::Profile &profile)
{
Mlt::Producer *p = new Mlt::Producer(profile, "noise:");
p->set(kShotcutCaptionProperty, ui->nameLabel->text().toUtf8().constData());
p->set(kShotcutDetailProperty, ui->nameLabel->text().toUtf8().constData());
return p;
}
| 1,367
|
C++
|
.cpp
| 39
| 32.615385
| 80
| 0.737915
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
13,227
|
resourcewidget.cpp
|
mltframework_shotcut/src/widgets/resourcewidget.cpp
|
/*
* Copyright (c) 2023-2024 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "resourcewidget.h"
#include "Logger.h"
#include "models/resourcemodel.h"
#include <QHeaderView>
#include <QTreeView>
#include <QVBoxLayout>
ResourceWidget::ResourceWidget(QWidget *parent)
: QWidget(parent)
{
QVBoxLayout *vlayout = new QVBoxLayout();
m_model = new ResourceModel(this);
m_table = new QTreeView();
m_table->setSelectionMode(QAbstractItemView::ExtendedSelection);
m_table->setSelectionBehavior(QAbstractItemView::SelectRows);
m_table->setItemsExpandable(false);
m_table->setRootIsDecorated(false);
m_table->setUniformRowHeights(true);
m_table->setSortingEnabled(false);
m_table->setModel(m_model);
m_table->setWordWrap(false);
m_table->setAlternatingRowColors(true);
m_table->header()->setStretchLastSection(false);
qreal rowHeight = fontMetrics().height() * devicePixelRatioF();
m_table->header()->setMinimumSectionSize(rowHeight);
m_table->header()->setSectionResizeMode(ResourceModel::COLUMN_INFO, QHeaderView::Fixed);
m_table->setColumnWidth(ResourceModel::COLUMN_INFO, rowHeight);
m_table->header()->setSectionResizeMode(ResourceModel::COLUMN_NAME, QHeaderView::Interactive);
m_table->header()->setSectionResizeMode(ResourceModel::COLUMN_SIZE, QHeaderView::Interactive);
m_table->header()->setSectionResizeMode(ResourceModel::COLUMN_VID_DESCRIPTION,
QHeaderView::Interactive);
m_table->header()->setSectionResizeMode(ResourceModel::COLUMN_AUD_DESCRIPTION,
QHeaderView::Interactive);
connect(m_table->selectionModel(), &QItemSelectionModel::currentChanged, this, [ = ]() {
m_table->selectionModel()->clearCurrentIndex();
});
vlayout->addWidget(m_table);
setLayout(vlayout);
}
ResourceWidget::~ResourceWidget()
{
}
void ResourceWidget::search(Mlt::Producer *producer)
{
m_model->search(producer);
}
void ResourceWidget::add(Mlt::Producer *producer)
{
m_model->add(producer);
}
void ResourceWidget::selectTroubleClips()
{
m_table->selectionModel()->clearSelection();
for (int i = 0; i < m_model->rowCount(QModelIndex()); i++) {
QModelIndex index = m_model->index(i, ResourceModel::COLUMN_INFO);
if (!m_model->data(index, Qt::ToolTipRole).toString().isEmpty()) {
m_table->selectionModel()->select(index, QItemSelectionModel::Select | QItemSelectionModel::Rows);
}
}
}
bool ResourceWidget::hasTroubleClips()
{
auto n = m_model->rowCount(QModelIndex());
for (int i = 0; n > 1 && i < n; i++) {
QModelIndex index = m_model->index(i, ResourceModel::COLUMN_INFO);
if (!m_model->data(index, Qt::ToolTipRole).toString().isEmpty()) {
return true;
}
}
return false;
}
int ResourceWidget::producerCount()
{
return m_model->producerCount();
}
Mlt::Producer ResourceWidget::producer(int index)
{
return m_model->producer(index);
}
QList<Mlt::Producer> ResourceWidget::getSelected()
{
return m_model->getProducers(m_table->selectionModel()->selectedRows());
}
void ResourceWidget::updateSize()
{
static const int MAX_COLUMN_WIDTH = 300;
int tableWidth = 38 + m_table->columnWidth(ResourceModel::COLUMN_INFO);
for (int i = ResourceModel::COLUMN_NAME; i < m_table->model()->columnCount(); i++) {
m_table->resizeColumnToContents(i);
int columnWidth = m_table->columnWidth(i);
if (columnWidth > MAX_COLUMN_WIDTH) {
columnWidth = MAX_COLUMN_WIDTH;
m_table->setColumnWidth(i, columnWidth);
}
tableWidth += columnWidth;
}
resize(tableWidth, 400);
}
| 4,369
|
C++
|
.cpp
| 113
| 33.814159
| 110
| 0.700708
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,228
|
openglvideowidget.cpp
|
mltframework_shotcut/src/widgets/openglvideowidget.cpp
|
/*
* Copyright (c) 2011-2023 Meltytech, LLC
*
* Some GL shader based on BSD licensed code from Peter Bengtsson:
* http://www.fourcc.org/source/YUV420P-OpenGL-GLSLang.c
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "openglvideowidget.h"
#include <Logger.h>
#include <QOpenGLVersionFunctionsFactory>
#include <QOpenGLFunctions_1_1>
#include <QOpenGLFunctions_3_2_Core>
#include <utility>
#ifdef QT_NO_DEBUG
#define check_error(fn) {}
#else
#define check_error(fn) { int err = fn->glGetError(); if (err != GL_NO_ERROR) { LOG_ERROR() << "GL error" << Qt::hex << err << Qt::dec << "at" << __FILE__ << ":" << __LINE__; } }
#endif
OpenGLVideoWidget::OpenGLVideoWidget(QObject *parent)
: VideoWidget{parent}
, m_quickContext(nullptr)
, m_isThreadedOpenGL(false)
{
m_renderTexture[0] = m_renderTexture[1] = m_renderTexture[2] = 0;
m_displayTexture[0] = m_displayTexture[1] = m_displayTexture[2] = 0;
}
OpenGLVideoWidget::~OpenGLVideoWidget()
{
LOG_DEBUG() << "begin";
if (m_renderTexture[0] && m_displayTexture[0] && m_context) {
m_context->makeCurrent(&m_offscreenSurface);
m_context->functions()->glDeleteTextures(3, m_renderTexture);
if (m_displayTexture[0] && m_displayTexture[1] && m_displayTexture[2])
m_context->functions()->glDeleteTextures(3, m_displayTexture);
m_context->doneCurrent();
}
}
void OpenGLVideoWidget::initialize()
{
LOG_DEBUG() << "begin";
auto context = static_cast<QOpenGLContext *>(quickWindow()->rendererInterface()->getResource(
quickWindow(), QSGRendererInterface::OpenGLContextResource));
m_quickContext = context;
if (!m_offscreenSurface.isValid()) {
m_offscreenSurface.setFormat(context->format());
m_offscreenSurface.create();
}
Q_ASSERT(m_offscreenSurface.isValid());
initializeOpenGLFunctions();
LOG_INFO() << "OpenGL vendor" << QString::fromUtf8((const char *) glGetString(GL_VENDOR));
LOG_INFO() << "OpenGL renderer" << QString::fromUtf8((const char *) glGetString(GL_RENDERER));
LOG_INFO() << "OpenGL threaded?" << context->supportsThreadedOpenGL();
LOG_INFO() << "OpenGL ES?" << context->isOpenGLES();
glGetIntegerv(GL_MAX_TEXTURE_SIZE, &m_maxTextureSize);
LOG_INFO() << "OpenGL maximum texture size =" << m_maxTextureSize;
GLint dims[2];
glGetIntegerv(GL_MAX_VIEWPORT_DIMS, &dims[0]);
LOG_INFO() << "OpenGL maximum viewport size =" << dims[0] << "x" << dims[1];
createShader();
LOG_DEBUG() << "end";
Mlt::VideoWidget::initialize();
}
void OpenGLVideoWidget::createShader()
{
m_shader.reset(new QOpenGLShaderProgram);
m_shader->addShaderFromSourceCode(QOpenGLShader::Vertex,
"uniform highp mat4 projection;"
"uniform highp mat4 modelView;"
"attribute highp vec4 vertex;"
"attribute highp vec2 texCoord;"
"varying highp vec2 coordinates;"
"void main(void) {"
" gl_Position = projection * modelView * vertex;"
" coordinates = texCoord;"
"}");
m_shader->addShaderFromSourceCode(QOpenGLShader::Fragment,
"uniform sampler2D Ytex, Utex, Vtex;"
"uniform lowp int colorspace;"
"varying highp vec2 coordinates;"
"void main(void) {"
" mediump vec3 texel;"
" texel.r = texture2D(Ytex, coordinates).r - 16.0/255.0;" // Y
" texel.g = texture2D(Utex, coordinates).r - 128.0/255.0;" // U
" texel.b = texture2D(Vtex, coordinates).r - 128.0/255.0;" // V
" mediump mat3 coefficients;"
" if (colorspace == 601) {"
" coefficients = mat3("
" 1.1643, 1.1643, 1.1643," // column 1
" 0.0, -0.39173, 2.017," // column 2
" 1.5958, -0.8129, 0.0);" // column 3
" } else {" // ITU-R 709
" coefficients = mat3("
" 1.1643, 1.1643, 1.1643," // column 1
" 0.0, -0.213, 2.112," // column 2
" 1.793, -0.533, 0.0);" // column 3
" }"
" gl_FragColor = vec4(coefficients * texel, 1.0);"
"}");
m_shader->link();
m_textureLocation[0] = m_shader->uniformLocation("Ytex");
m_textureLocation[1] = m_shader->uniformLocation("Utex");
m_textureLocation[2] = m_shader->uniformLocation("Vtex");
m_colorspaceLocation = m_shader->uniformLocation("colorspace");
m_projectionLocation = m_shader->uniformLocation("projection");
m_modelViewLocation = m_shader->uniformLocation("modelView");
m_vertexLocation = m_shader->attributeLocation("vertex");
m_texCoordLocation = m_shader->attributeLocation("texCoord");
}
static void uploadTextures(QOpenGLContext *context, const SharedFrame &frame, GLuint texture[])
{
int width = frame.get_image_width();
int height = frame.get_image_height();
const uint8_t *image = frame.get_image(mlt_image_yuv420p);
QOpenGLFunctions *f = context->functions();
// The planes of pixel data may not be a multiple of the default 4 bytes.
f->glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
// Upload each plane of YUV to a texture.
if (texture[0])
f->glDeleteTextures(3, texture);
check_error(f);
f->glGenTextures(3, texture);
check_error(f);
f->glBindTexture (GL_TEXTURE_2D, texture[0]);
check_error(f);
f->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
check_error(f);
f->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
check_error(f);
f->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
check_error(f);
f->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
check_error(f);
f->glTexImage2D (GL_TEXTURE_2D, 0, GL_LUMINANCE, width, height, 0,
GL_LUMINANCE, GL_UNSIGNED_BYTE, image);
check_error(f);
f->glBindTexture (GL_TEXTURE_2D, texture[1]);
check_error(f);
f->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
check_error(f);
f->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
check_error(f);
f->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
check_error(f);
f->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
check_error(f);
f->glTexImage2D (GL_TEXTURE_2D, 0, GL_LUMINANCE, width / 2, height / 2, 0,
GL_LUMINANCE, GL_UNSIGNED_BYTE, image + width * height);
check_error(f);
f->glBindTexture (GL_TEXTURE_2D, texture[2]);
check_error(f);
f->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
check_error(f);
f->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
check_error(f);
f->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
check_error(f);
f->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
check_error(f);
f->glTexImage2D (GL_TEXTURE_2D, 0, GL_LUMINANCE, width / 2, height / 2, 0,
GL_LUMINANCE, GL_UNSIGNED_BYTE, image + width * height + width / 2 * height / 2);
check_error(f);
}
void OpenGLVideoWidget::renderVideo()
{
auto context = static_cast<QOpenGLContext *>(quickWindow()->rendererInterface()->getResource(
quickWindow(), QSGRendererInterface::OpenGLContextResource));
if (!m_quickContext) {
LOG_ERROR() << "No quickContext";
return;
}
if (!context->isValid()) {
LOG_ERROR() << "No QSGRendererInterface::OpenGLContextResource";
return;
}
#ifndef QT_NO_DEBUG
QOpenGLFunctions *f = context->functions();
#endif
float width = this->width() * devicePixelRatioF();
float height = this->height() * devicePixelRatioF();
glDisable(GL_BLEND);
glDisable(GL_DEPTH_TEST);
glDepthMask(GL_FALSE);
glViewport(0, 0, width, height);
check_error(f);
if (!m_isThreadedOpenGL) {
m_mutex.lock();
if (!m_sharedFrame.is_valid()) {
m_mutex.unlock();
return;
}
uploadTextures(context, m_sharedFrame, m_displayTexture);
m_mutex.unlock();
}
if (!m_displayTexture[0]) {
return;
}
quickWindow()->beginExternalCommands();
// Bind textures.
for (int i = 0; i < 3; ++i) {
if (m_displayTexture[i]) {
glActiveTexture(GL_TEXTURE0 + i);
glBindTexture(GL_TEXTURE_2D, m_displayTexture[i]);
check_error(f);
}
}
// Init shader program.
m_shader->bind();
m_shader->setUniformValue(m_textureLocation[0], 0);
m_shader->setUniformValue(m_textureLocation[1], 1);
m_shader->setUniformValue(m_textureLocation[2], 2);
m_shader->setUniformValue(m_colorspaceLocation, MLT.profile().colorspace());
check_error(f);
// Setup an orthographic projection.
QMatrix4x4 projection;
projection.scale(2.0f / width, 2.0f / height);
m_shader->setUniformValue(m_projectionLocation, projection);
check_error(f);
// Set model view.
QMatrix4x4 modelView;
if (rect().width() > 0.0 && zoom() > 0.0) {
if (offset().x() || offset().y())
modelView.translate(-offset().x() * devicePixelRatioF(),
offset().y() * devicePixelRatioF());
modelView.scale(zoom(), zoom());
}
m_shader->setUniformValue(m_modelViewLocation, modelView);
check_error(f);
// Provide vertices of triangle strip.
QVector<QVector2D> vertices;
width = rect().width() * devicePixelRatioF();
height = rect().height() * devicePixelRatioF();
vertices << QVector2D(-width / 2.0f, -height / 2.0f);
vertices << QVector2D(-width / 2.0f, height / 2.0f);
vertices << QVector2D(width / 2.0f, -height / 2.0f);
vertices << QVector2D(width / 2.0f, height / 2.0f);
m_shader->enableAttributeArray(m_vertexLocation);
check_error(f);
m_shader->setAttributeArray(m_vertexLocation, vertices.constData());
check_error(f);
// Provide texture coordinates.
QVector<QVector2D> texCoord;
texCoord << QVector2D(0.0f, 1.0f);
texCoord << QVector2D(0.0f, 0.0f);
texCoord << QVector2D(1.0f, 1.0f);
texCoord << QVector2D(1.0f, 0.0f);
m_shader->enableAttributeArray(m_texCoordLocation);
check_error(f);
m_shader->setAttributeArray(m_texCoordLocation, texCoord.constData());
check_error(f);
// Render
glDrawArrays(GL_TRIANGLE_STRIP, 0, vertices.size());
check_error(f);
// Cleanup
m_shader->disableAttributeArray(m_vertexLocation);
m_shader->disableAttributeArray(m_texCoordLocation);
m_shader->release();
for (int i = 0; i < 3; ++i) {
if (m_displayTexture[i]) {
glActiveTexture(GL_TEXTURE0 + i);
glBindTexture(GL_TEXTURE_2D, 0);
check_error(f);
}
}
glActiveTexture(GL_TEXTURE0);
check_error(f);
quickWindow()->endExternalCommands();
Mlt::VideoWidget::renderVideo();
}
void OpenGLVideoWidget::onFrameDisplayed(const SharedFrame &frame)
{
if (m_isThreadedOpenGL && !m_context) {
m_context.reset(new QOpenGLContext);
if (m_context) {
m_context->setFormat(m_quickContext->format());
m_context->setShareContext(m_quickContext);
m_context->create();
}
}
if (m_context && m_context->isValid()) {
// Using threaded OpenGL to upload textures.
QOpenGLFunctions *f = m_context->functions();
m_context->makeCurrent(&m_offscreenSurface);
uploadTextures(m_context.get(), frame, m_renderTexture);
f->glBindTexture(GL_TEXTURE_2D, 0);
check_error(f);
f->glFinish();
m_context->doneCurrent();
m_mutex.lock();
for (int i = 0; i < 3; ++i)
std::swap(m_renderTexture[i], m_displayTexture[i]);
m_mutex.unlock();
}
Mlt::VideoWidget::onFrameDisplayed(frame);
}
| 13,900
|
C++
|
.cpp
| 306
| 34.944444
| 180
| 0.58236
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,229
|
alsawidget.cpp
|
mltframework_shotcut/src/widgets/alsawidget.cpp
|
/*
* Copyright (c) 2012-2022 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "alsawidget.h"
#include "ui_alsawidget.h"
#include "mltcontroller.h"
#include "util.h"
#include "shotcut_mlt_properties.h"
#include "settings.h"
AlsaWidget::AlsaWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::AlsaWidget)
{
ui->setupUi(this);
Util::setColorsToHighlight(ui->label_2);
ui->applyButton->hide();
ui->preset->saveDefaultPreset(getPreset());
ui->preset->loadPresets();
ui->lineEdit->setText(Settings.audioInput());
}
AlsaWidget::~AlsaWidget()
{
delete ui;
}
Mlt::Producer *AlsaWidget::newProducer(Mlt::Profile &profile)
{
QString s("alsa:%1");
if (ui->lineEdit->text().isEmpty())
s = s.arg("default");
else
s = s.arg(ui->lineEdit->text());
if (ui->alsaChannelsSpinBox->value() > 0)
s += QStringLiteral("?channels=%1").arg(ui->alsaChannelsSpinBox->value());
Mlt::Producer *p = new Mlt::Producer(profile, s.toUtf8().constData());
p->set(kBackgroundCaptureProperty, 1);
p->set(kShotcutCaptionProperty, "ALSA");
Settings.setAudioInput(ui->lineEdit->text());
return p;
}
Mlt::Properties AlsaWidget::getPreset() const
{
Mlt::Properties p;
QString s("alsa:%1");
if (ui->lineEdit->text().isEmpty())
s = s.arg("default");
else
s = s.arg(ui->lineEdit->text());
p.set("resource", s.toUtf8().constData());
p.set("channels", ui->alsaChannelsSpinBox->value());
return p;
}
void AlsaWidget::loadPreset(Mlt::Properties &p)
{
QString s(p.get("resource"));
int i = s.indexOf(':');
if (i > -1)
ui->lineEdit->setText(s.mid(i + 1));
if (p.get("channels"))
ui->alsaChannelsSpinBox->setValue(p.get_int("channels"));
}
void AlsaWidget::on_preset_selected(void *p)
{
Mlt::Properties *properties = (Mlt::Properties *) p;
loadPreset(*properties);
delete properties;
}
void AlsaWidget::on_preset_saveClicked()
{
ui->preset->savePreset(getPreset());
}
void AlsaWidget::setProducer(Mlt::Producer *producer)
{
ui->applyButton->show();
if (producer)
loadPreset(*producer);
}
void AlsaWidget::on_applyButton_clicked()
{
MLT.setProducer(newProducer(MLT.profile()));
MLT.play();
}
| 2,891
|
C++
|
.cpp
| 94
| 27.234043
| 82
| 0.685325
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,230
|
d3dvideowidget.cpp
|
mltframework_shotcut/src/widgets/d3dvideowidget.cpp
|
/*
* Copyright (c) 2023 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "d3dvideowidget.h"
#include <Logger.h>
#include <d3dcompiler.h>
D3DVideoWidget::D3DVideoWidget(QObject *parent)
: Mlt::VideoWidget{parent}
{
m_maxTextureSize = D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION;
::memset(&m_constants, 0, sizeof(m_constants));
}
D3DVideoWidget::~D3DVideoWidget()
{
for (int i = 0; i < 3; i++) {
if (m_texture[i])
m_texture[i]->Release();
}
if (m_vs)
m_vs->Release();
if (m_ps)
m_ps->Release();
if (m_vbuf)
m_vbuf->Release();
if (m_cbuf)
m_cbuf->Release();
if (m_inputLayout)
m_inputLayout->Release();
if (m_rastState)
m_rastState->Release();
if (m_dsState)
m_dsState->Release();
}
void D3DVideoWidget::initialize()
{
m_initialized = true;
QSGRendererInterface *rif = quickWindow()->rendererInterface();
// We are not prepared for anything other than running with the RHI and its D3D11 backend.
Q_ASSERT(rif->graphicsApi() == QSGRendererInterface::Direct3D11);
m_device = reinterpret_cast<ID3D11Device *>(rif->getResource(quickWindow(),
QSGRendererInterface::DeviceResource));
Q_ASSERT(m_device);
m_context = reinterpret_cast<ID3D11DeviceContext *>(rif->getResource(quickWindow(),
QSGRendererInterface::DeviceContextResource));
Q_ASSERT(m_context);
if (m_vert.isEmpty())
prepareShader(VertexStage);
if (m_frag.isEmpty())
prepareShader(FragmentStage);
const QByteArray vs = compileShader(VertexStage, m_vert, m_vertEntryPoint);
const QByteArray fs = compileShader(FragmentStage, m_frag, m_fragEntryPoint);
HRESULT hr = m_device->CreateVertexShader(vs.constData(), vs.size(), nullptr, &m_vs);
if (FAILED(hr))
qFatal("Failed to create vertex shader: 0x%x", uint(hr));
hr = m_device->CreatePixelShader(fs.constData(), fs.size(), nullptr, &m_ps);
if (FAILED(hr))
qFatal("Failed to create pixel shader: 0x%x", uint(hr));
D3D11_BUFFER_DESC bufDesc;
memset(&bufDesc, 0, sizeof(bufDesc));
bufDesc.ByteWidth = sizeof(float) * 16;
bufDesc.Usage = D3D11_USAGE_DEFAULT;
bufDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
hr = m_device->CreateBuffer(&bufDesc, nullptr, &m_vbuf);
if (FAILED(hr))
qFatal("Failed to create buffer: 0x%x", uint(hr));
bufDesc.ByteWidth = sizeof(m_constants) + 0xf & 0xfffffff0; // must be a multiple of 16
bufDesc.Usage = D3D11_USAGE_DYNAMIC;
bufDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
bufDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
hr = m_device->CreateBuffer(&bufDesc, nullptr, &m_cbuf);
if (FAILED(hr))
qFatal("Failed to create buffer: 0x%x", uint(hr));
const D3D11_INPUT_ELEMENT_DESC inputDesc[] = {
{ "VERTEX", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "TEXCOORD", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, sizeof(DirectX::XMFLOAT2), D3D11_INPUT_PER_VERTEX_DATA, 0 },
};
hr = m_device->CreateInputLayout(inputDesc, ARRAYSIZE(inputDesc), vs.constData(), vs.size(),
&m_inputLayout);
if (FAILED(hr))
qFatal("Failed to create input layout: 0x%x", uint(hr));
D3D11_RASTERIZER_DESC rastDesc;
memset(&rastDesc, 0, sizeof(rastDesc));
rastDesc.FillMode = D3D11_FILL_SOLID;
rastDesc.CullMode = D3D11_CULL_NONE;
hr = m_device->CreateRasterizerState(&rastDesc, &m_rastState);
if (FAILED(hr))
qFatal("Failed to create rasterizer state: 0x%x", uint(hr));
D3D11_DEPTH_STENCIL_DESC dsDesc;
memset(&dsDesc, 0, sizeof(dsDesc));
hr = m_device->CreateDepthStencilState(&dsDesc, &m_dsState);
if (FAILED(hr))
qFatal("Failed to create depth/stencil state: 0x%x", uint(hr));
Mlt::VideoWidget::initialize();
}
void D3DVideoWidget::beforeRendering()
{
quickWindow()->beginExternalCommands();
m_context->ClearState();
// Provide vertices of triangle strip
float width = rect().width() * devicePixelRatioF() / 2.0f;
float height = rect().height() * devicePixelRatioF() / 2.0f;
float vertexData[] = { // x,y plus u,v texture coordinates
width, -height, 1.f, 1.f, // bottom left
-width, -height, 0.f, 1.f, // bottom right
width, height, 1.f, 0.f, // top left
-width, height, 0.f, 0.f // top right
};
// Setup an orthographic projection
QMatrix4x4 modelView;
width = this->width() * devicePixelRatioF();
height = this->height() * devicePixelRatioF();
modelView.scale(2.0f / width, 2.0f / height);
// Set model-view
if (rect().width() > 0.0 && zoom() > 0.0) {
if (offset().x() || offset().y())
modelView.translate(-offset().x() * devicePixelRatioF(),
offset().y() * devicePixelRatioF());
modelView.scale(zoom(), zoom());
}
for (int i = 0; i < 4; i++) {
vertexData[4 * i] *= modelView(0, 0);
vertexData[4 * i] += modelView(0, 3);
vertexData[4 * i + 1] *= modelView(1, 1);
vertexData[4 * i + 1] += modelView(1, 3);
}
m_context->UpdateSubresource(m_vbuf, 0, nullptr, vertexData, 0, 0);
// (Re)create the textures
m_mutex.lock();
if (!m_sharedFrame.is_valid()) {
m_mutex.unlock();
quickWindow()->endExternalCommands();
Mlt::VideoWidget::beforeRendering();
return;
}
int iwidth = m_sharedFrame.get_image_width();
int iheight = m_sharedFrame.get_image_height();
const uint8_t *image = m_sharedFrame.get_image(mlt_image_yuv420p);
for (int i = 0; i < 3; i++) {
if (m_texture[i])
m_texture[i]->Release();
}
m_texture[0] = initTexture(image, iwidth, iheight);
m_texture[1] = initTexture(image + iwidth * iheight, iwidth / 2, iheight / 2);
m_texture[2] = initTexture(image + iwidth * iheight + iwidth / 2 * iheight / 2, iwidth / 2,
iheight / 2);
m_mutex.unlock();
// Update the constants
D3D11_MAPPED_SUBRESOURCE mp;
// will copy the entire constant buffer every time -> pass WRITE_DISCARD -> prevent pipeline stalls
HRESULT hr = m_context->Map(m_cbuf, 0, D3D11_MAP_WRITE_DISCARD, 0, &mp);
if (SUCCEEDED(hr)) {
m_constants.colorspace = MLT.profile().colorspace();
::memcpy(mp.pData, &m_constants, sizeof(m_constants));
m_context->Unmap(m_cbuf, 0);
} else {
quickWindow()->endExternalCommands();
qFatal("Failed to map constant buffer: 0x%x", uint(hr));
return;
}
quickWindow()->endExternalCommands();
Mlt::VideoWidget::beforeRendering();
}
void D3DVideoWidget::renderVideo()
{
if (!m_texture[0]) {
Mlt::VideoWidget::renderVideo();
return;
}
quickWindow()->beginExternalCommands();
D3D11_VIEWPORT v;
v.TopLeftX = 0.f;
v.TopLeftY = 0.f;
v.Width = this->width() * devicePixelRatioF();
v.Height = this->height() * devicePixelRatioF();
v.MinDepth = 0.f;
v.MaxDepth = 1.f;
m_context->RSSetViewports(1, &v);
m_context->VSSetShader(m_vs, nullptr, 0);
m_context->PSSetShader(m_ps, nullptr, 0);
m_context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP);
m_context->IASetInputLayout(m_inputLayout);
m_context->OMSetDepthStencilState(m_dsState, 0);
m_context->RSSetState(m_rastState);
const UINT stride = sizeof(float) * 4;
const UINT offset = 0;
m_context->IASetVertexBuffers(0, 1, &m_vbuf, &stride, &offset);
m_context->PSSetConstantBuffers(0, 1, &m_cbuf);
m_context->PSSetShaderResources(0, 3, m_texture);
m_context->Draw(4, 0);
quickWindow()->endExternalCommands();
Mlt::VideoWidget::renderVideo();
}
void D3DVideoWidget::prepareShader(Stage stage)
{
if (stage == VertexStage) {
m_vert = "struct VSInput {"
" float2 vertex : VERTEX;"
" float2 coords : TEXCOORD;"
"};"
"struct VSOutput {"
" float2 coords : TEXCOORD0;"
" float4 position : SV_Position;"
"};"
"VSOutput main(VSInput input) {"
" VSOutput output;"
" output.position = float4(input.vertex, 0.0f, 1.0f);"
" output.coords = input.coords;"
" return output;"
"}";
Q_ASSERT(!m_vert.isEmpty());
m_vertEntryPoint = QByteArrayLiteral("main");
} else {
m_frag = "Texture2D yTex, uTex, vTex;"
"SamplerState yuvSampler;"
"cbuffer buf {"
" int colorspace;"
"};"
"struct PSInput {"
" float2 coords : TEXCOORD0;"
"};"
"struct PSOutput {"
" float4 color : SV_Target0;"
"};"
"PSOutput main(PSInput input) {"
" float3 yuv;"
" yuv.x = yTex.Sample(yuvSampler, input.coords).r - 16.0f/255.0f;"
" yuv.y = uTex.Sample(yuvSampler, input.coords).r - 128.0f/255.0f;"
" yuv.z = vTex.Sample(yuvSampler, input.coords).r - 128.0f/255.0f;"
" float3x3 coefficients;"
" if (colorspace == 601) {"
" coefficients = float3x3("
" 1.1643f, 0.0f, 1.5958f,"
" 1.1643f, -0.39173f, -0.8129f,"
" 1.1643f, 2.017f, 0.0f);"
" } else {" // ITU-R 709
" coefficients = float3x3("
" 1.1643f, 0.0f, 1.793f,"
" 1.1643f, -0.213f, -0.533f,"
" 1.1643f, 2.112f, 0.0f);"
" }"
" PSOutput output;"
" output.color = float4(mul(coefficients, yuv), 1.0f);"
" return output;"
"}";
m_fragEntryPoint = QByteArrayLiteral("main");
}
}
QByteArray D3DVideoWidget::compileShader(Stage stage, const QByteArray &source,
const QByteArray &entryPoint)
{
const char *target;
switch (stage) {
case VertexStage:
target = "vs_5_0";
break;
case FragmentStage:
target = "ps_5_0";
break;
default:
qFatal("Unknown shader stage %d", stage);
return QByteArray();
}
ID3DBlob *bytecode = nullptr;
ID3DBlob *errors = nullptr;
HRESULT hr = D3DCompile(source.constData(), source.size(),
nullptr, nullptr, nullptr,
entryPoint.constData(), target, 0, 0, &bytecode, &errors);
if (FAILED(hr) || !bytecode) {
qWarning("HLSL shader compilation failed: 0x%x", uint(hr));
if (errors) {
const QByteArray msg(static_cast<const char *>(errors->GetBufferPointer()),
errors->GetBufferSize());
errors->Release();
qWarning("%s", msg.constData());
}
return QByteArray();
}
QByteArray result;
result.resize(bytecode->GetBufferSize());
memcpy(result.data(), bytecode->GetBufferPointer(), result.size());
bytecode->Release();
return result;
}
ID3D11ShaderResourceView *D3DVideoWidget::initTexture(const void *p, int width, int height)
{
ID3D11ShaderResourceView *result;
D3D11_TEXTURE2D_DESC desc;
desc.Width = width;
desc.Height = height;
desc.MipLevels = 1;
desc.ArraySize = 1;
desc.Format = DXGI_FORMAT_R8_UNORM;
desc.SampleDesc.Count = 1;
desc.SampleDesc.Quality = 0;
desc.Usage = D3D11_USAGE_DEFAULT;
desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
desc.CPUAccessFlags = 0;
desc.MiscFlags = 0;
D3D11_SUBRESOURCE_DATA subresourceData;
subresourceData.pSysMem = p;
subresourceData.SysMemPitch = width;
subresourceData.SysMemSlicePitch = 0;
ID3D11Texture2D *texture;
m_device->CreateTexture2D(&desc, &subresourceData, &texture);
D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
srvDesc.Format = desc.Format;
srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
srvDesc.Texture2D.MipLevels = 1;
srvDesc.Texture2D.MostDetailedMip = 0;
m_device->CreateShaderResourceView(texture, &srvDesc, &result);
texture->Release();
return result;
}
| 13,245
|
C++
|
.cpp
| 326
| 32.368098
| 119
| 0.600901
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,231
|
avformatproducerwidget.cpp
|
mltframework_shotcut/src/widgets/avformatproducerwidget.cpp
|
/*
* Copyright (c) 2012-2024 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "avformatproducerwidget.h"
#include "ui_avformatproducerwidget.h"
#include "util.h"
#include "mltcontroller.h"
#include "shotcut_mlt_properties.h"
#include "dialogs/filedatedialog.h"
#include "dialogs/listselectiondialog.h"
#include "jobqueue.h"
#include "jobs/ffprobejob.h"
#include "jobs/ffmpegjob.h"
#include "jobs/meltjob.h"
#include "jobs/postjobaction.h"
#include "jobs/gopro2gpxjob.h"
#include "settings.h"
#include "mainwindow.h"
#include "Logger.h"
#include "qmltypes/qmlapplication.h"
#include "proxymanager.h"
#include "dialogs/longuitask.h"
#include "spatialmedia/spatialmedia.h"
#include "transcoder.h"
#include "jobs/bitrateviewerjob.h"
#include <QtWidgets>
#include <limits>
static const auto kHandleSeconds = 15.0;
static const auto kAbsoluteAudioIndex = "audio_index";
AvformatProducerWidget::AvformatProducerWidget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::AvformatProducerWidget)
, m_defaultDuration(-1)
, m_recalcDuration(true)
{
ui->setupUi(this);
ui->timelineDurationText->setFixedWidth(ui->durationSpinBox->width());
ui->filenameLabel->setFrame(true);
Util::setColorsToHighlight(ui->filenameLabel, QPalette::Base);
connect(ui->applySpeedButton, SIGNAL(clicked()), SLOT(on_speedSpinBox_editingFinished()));
connect(this, SIGNAL(producerChanged(Mlt::Producer *)), SLOT(onProducerChanged(Mlt::Producer *)));
}
AvformatProducerWidget::~AvformatProducerWidget()
{
delete ui;
}
Mlt::Producer *AvformatProducerWidget::newProducer(Mlt::Profile &profile)
{
Mlt::Producer *p = 0;
if ( ui->speedSpinBox->value() == 1.0 ) {
p = new Mlt::Chain(profile, Util::GetFilenameFromProducer(producer(), false).toUtf8().constData());
} else {
// If the system language's numeric format and region's numeric format differ, then MLT
// uses the language's numeric format while Qt is using the region's. Thus, to
// supply a proper numeric format in string form to MLT, we must use MLT instead of
// letting Qt convert it.
Mlt::Properties tempProps;
tempProps.set("speed", ui->speedSpinBox->value());
QString warpspeed = QString::fromLatin1(tempProps.get("speed"));
QString filename = Util::GetFilenameFromProducer(producer(), false);
QString s = QStringLiteral("%1:%2:%3").arg("timewarp").arg(warpspeed).arg(filename);
p = new Mlt::Producer(profile, s.toUtf8().constData());
p->set(kShotcutProducerProperty, "avformat");
}
if (p->is_valid()) {
p->set("video_delay", double(ui->syncSlider->value()) / 1000);
if (ui->pitchCheckBox->checkState() == Qt::Checked) {
m_producer->set("warp_pitch", 1);
}
}
return p;
}
void AvformatProducerWidget::setProducer(Mlt::Producer *p)
{
AbstractProducerWidget::setProducer(p);
emit producerChanged(p);
}
void AvformatProducerWidget::updateDuration()
{
if (m_producer->get(kFilterInProperty) && m_producer->get(kFilterOutProperty)) {
auto duration = m_producer->get_int(kFilterOutProperty) - m_producer->get_int(
kFilterInProperty) + 1;
ui->timelineDurationLabel->show();
ui->timelineDurationText->setText(m_producer->frames_to_time(duration, Settings.timeFormat()));
ui->timelineDurationText->show();
} else {
ui->timelineDurationLabel->hide();
ui->timelineDurationLabel->setText(QString());
ui->timelineDurationText->hide();
}
}
void AvformatProducerWidget::rename()
{
ui->filenameLabel->setFocus();
ui->filenameLabel->selectAll();
}
void AvformatProducerWidget::offerConvert(QString message, bool set709Convert, bool setSubClip)
{
m_producer->set(kShotcutSkipConvertProperty, true);
LongUiTask::cancel();
MLT.pause();
TranscodeDialog dialog(message.append(
tr(" Do you want to convert it to an edit-friendly format?\n\n"
"If yes, choose a format below and then click OK to choose a file name. "
"After choosing a file name, a job is created. "
"When it is done, it automatically replaces clips, or you can double-click the job to open it.\n")),
ui->scanComboBox->currentIndex(), this);
dialog.setWindowModality(QmlApplication::dialogModality());
if (!setSubClip) {
dialog.showCheckBox();
}
dialog.set709Convert(set709Convert);
dialog.showSubClipCheckBox();
LOG_DEBUG() << "in" << m_producer->get_in() << "out" << m_producer->get_out() << "length" <<
m_producer->get_length() - 1;
dialog.setSubClipChecked(setSubClip && (m_producer->get_in() > 0
|| m_producer->get_out() < m_producer->get_length() - 1));
auto fps = Util::getAndroidFrameRate(m_producer.get());
if (fps > 0.0)
dialog.setFrameRate(fps);
Transcoder transcoder;
transcoder.addProducer(m_producer.data());
transcoder.convert(dialog);
}
void AvformatProducerWidget::keyPressEvent(QKeyEvent *event)
{
if (ui->speedSpinBox->hasFocus() &&
(event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return)) {
ui->speedSpinBox->clearFocus();
} else {
QWidget::keyPressEvent(event);
}
}
void AvformatProducerWidget::onProducerChanged(Mlt::Producer *producer)
{
if ( producer->get_producer() == m_producer->get_producer() ) {
if (Settings.playerGPU()) {
QTimer::singleShot(50, this, &AvformatProducerWidget::reloadProducerValues);
} else {
auto task = new ProbeTask(producer);
connect(task, &ProbeTask::probeFinished, this, &AvformatProducerWidget::reloadProducerValues,
Qt::QueuedConnection);
QThreadPool::globalInstance()->start(task, 10);
}
}
}
void AvformatProducerWidget::reopen(Mlt::Producer *p)
{
int length = ui->durationSpinBox->value();
int out = m_producer->get_out();
int position = m_producer->position();
double speed = m_producer->get_speed();
if ( m_recalcDuration ) {
double oldSpeed = Util::GetSpeedFromProducer(producer());
double newSpeed = ui->speedSpinBox->value();
double speedRatio = oldSpeed / newSpeed;
int in = m_producer->get_in();
length = qRound(length * speedRatio);
in = qMin(qRound(in * speedRatio), length - 1);
out = qMin(qRound(out * speedRatio), length - 1);
p->set("length", p->frames_to_time(length, mlt_time_clock));
p->set_in_and_out(in, out);
position = qRound(position * speedRatio);
// Adjust filters.
int n = p->filter_count();
for (int j = 0; j < n; j++) {
QScopedPointer<Mlt::Filter> filter(p->filter(j));
if (filter && filter->is_valid() && !filter->get_int("_loader")) {
in = qMin(qRound(filter->get_in() * speedRatio), length - 1);
out = qMin(qRound(filter->get_out() * speedRatio), length - 1);
filter->set_in_and_out(in, out);
//TODO: keyframes
}
}
} else {
p->set("length", p->frames_to_time(length, mlt_time_clock));
if (out + 1 >= m_producer->get_length())
p->set("out", length - 1);
else if (out >= length)
p->set("out", length - 1);
else
p->set("out", out);
if (position > p->get_out())
position = p->get_out();
p->set("in", m_producer->get_in());
}
MLT.stop();
if (MLT.setProducer(p)) {
AbstractProducerWidget::setProducer(0);
return;
}
emit producerReopened(false);
emit producerChanged(p);
MLT.seek(position);
MLT.play(speed);
setProducer(p);
}
void AvformatProducerWidget::recreateProducer(bool getFrame)
{
Mlt::Producer *p = newProducer(MLT.profile());
Util::passProducerProperties(m_producer.data(), p);
Util::updateCaption(p);
Mlt::Controller::copyFilters(*m_producer, *p);
if (m_producer->get(kMultitrackItemProperty)) {
int length = ui->durationSpinBox->value();
int in = m_producer->get_in();
int out = m_producer->get_out();
double oldSpeed = Util::GetSpeedFromProducer(producer());
double newSpeed = ui->speedSpinBox->value();
double speedRatio = oldSpeed / newSpeed;
length = qRound(length * speedRatio);
in = qMin(qRound(in * speedRatio), length - 1);
out = qMin(qRound(out * speedRatio), length - 1);
p->set("length", p->frames_to_time(length, mlt_time_clock));
p->set_in_and_out(in, out);
if (getFrame) {
// Getting a frame updates some properties such as audio_index,
// which is used by AudioLevelsTask.
delete p->get_frame();
}
emit producerChanged(p);
delete p;
} else {
reopen(p);
}
}
void AvformatProducerWidget::reloadProducerValues()
{
if (Settings.playerGPU())
m_producer->probe();
int tabIndex = ui->tabWidget->currentIndex();
ui->tabWidget->setTabEnabled(0, false);
ui->tabWidget->setTabEnabled(1, false);
ui->tabWidget->setTabEnabled(2, false);
if (m_defaultDuration == -1) {
m_defaultDuration = m_producer->get_length();
// Special hack for images
if (m_defaultDuration == std::numeric_limits<int>().max() && fps() == 1.0) {
m_defaultDuration = qRound(MLT.profile().fps() * Settings.imageDuration());
m_producer->set("length", m_defaultDuration);
}
}
double warpSpeed = Util::GetSpeedFromProducer(producer());
QString resource = Util::GetFilenameFromProducer(producer());
QString caption = Util::updateCaption(m_producer.data());
ui->filenameLabel->setText(caption);
ui->filenameLabel->setCursorPosition(caption.length());
ui->filenameLabel->setToolTip(resource);
ui->notesTextEdit->setPlainText(QString::fromUtf8(m_producer->get(kCommentProperty)));
ui->durationSpinBox->setValue(m_defaultDuration);
updateDuration();
m_recalcDuration = false;
ui->speedSpinBox->setValue(warpSpeed);
if (warpSpeed == 1.0) {
ui->pitchCheckBox->setEnabled(false);
} else {
ui->pitchCheckBox->setEnabled(true);
}
if (m_producer->get_int("warp_pitch") == 1) {
ui->pitchCheckBox->setCheckState(Qt::Checked);
} else {
ui->pitchCheckBox->setCheckState(Qt::Unchecked);
}
ui->rangeComboBox->setEnabled(true);
// Disable all actions if the file does not exist
auto exists = QFile::exists(resource);
ui->speedSpinBox->setEnabled(exists);
ui->speedComboBox->setEnabled(exists);
ui->applySpeedButton->setEnabled(exists);
ui->durationSpinBox->setEnabled(exists);
ui->menuButton->setEnabled(exists);
ui->convertButton->setEnabled(exists);
ui->reverseButton->setEnabled(exists);
ui->proxyButton->setEnabled(exists);
// populate the track combos
int n = m_producer->get_int("meta.media.nb_streams");
int videoIndex = 0;
int audioIndex = 0;
int totalAudioChannels = 0;
bool populateTrackCombos = (ui->videoTrackComboBox->count() == 0 &&
ui->audioTrackComboBox->count() == 0);
int color_range = !qstrcmp(m_producer->get("meta.media.color_range"), "full");
for (int i = 0; i < n; i++) {
QString key = QStringLiteral("meta.media.%1.stream.type").arg(i);
QString streamType(m_producer->get(key.toLatin1().constData()));
if (streamType == "video") {
key = QStringLiteral("meta.media.%1.codec.name").arg(i);
QString codec(m_producer->get(key.toLatin1().constData()));
key = QStringLiteral("meta.media.%1.codec.width").arg(i);
QString width(m_producer->get(key.toLatin1().constData()));
key = QStringLiteral("meta.media.%1.codec.height").arg(i);
QString height(m_producer->get(key.toLatin1().constData()));
QString name = QStringLiteral("%1: %2x%3 %4")
.arg(videoIndex + 1)
.arg(width)
.arg(height)
.arg(codec);
if (populateTrackCombos) {
if (ui->videoTrackComboBox->count() == 0)
ui->videoTrackComboBox->addItem(tr("None"), -1);
#if LIBMLT_VERSION_INT >= ((7<<16)+(19<<8))
ui->videoTrackComboBox->addItem(name, videoIndex);
}
if (videoIndex == m_producer->get_int(kVideoIndexProperty)) {
#else
ui->videoTrackComboBox->addItem(name, i);
}
if (i == m_producer->get_int(kVideoIndexProperty)) {
#endif
key = QStringLiteral("meta.media.%1.codec.long_name").arg(i);
QString codec(m_producer->get(key.toLatin1().constData()));
ui->videoTableWidget->setItem(0, 1, new QTableWidgetItem(codec));
key = QStringLiteral("meta.media.%1.codec.pix_fmt").arg(i);
QString pix_fmt = QString::fromLatin1(m_producer->get(key.toLatin1().constData()));
if (pix_fmt.startsWith("yuvj")) {
color_range = 1;
} else if (pix_fmt.contains("gbr") || pix_fmt.contains("rgb")) {
color_range = 1;
ui->rangeComboBox->setEnabled(false);
}
key = QStringLiteral("meta.media.%1.codec.rotate").arg(i);
int rotation = m_producer->property_exists("rotate") ?
m_producer->get_int("rotate") :
m_producer->get_int(key.toLatin1().constData());
ui->rotationComboBox->setCurrentIndex(rotation / 90);
ui->videoTableWidget->setItem(3, 1, new QTableWidgetItem(pix_fmt));
key = QStringLiteral("meta.media.%1.codec.colorspace").arg(i);
int colorspace = m_producer->get_int(key.toLatin1().constData());
QString csString = tr("unknown (%1)").arg(colorspace);
switch (colorspace) {
case 240:
csString = "SMPTE ST240";
break;
case 601:
csString = "ITU-R BT.601";
break;
case 709:
csString = "ITU-R BT.709";
break;
case 9:
case 10:
csString = "ITU-R BT.2020";
break;
}
ui->videoTableWidget->setItem(4, 1, new QTableWidgetItem(csString));
key = QStringLiteral("meta.media.%1.codec.color_trc").arg(i);
int trc = m_producer->get_int(key.toLatin1().constData());
QString trcString = Util::trcString(trc);
QTableWidgetItem *trcItem = new QTableWidgetItem(trcString);
trcItem->setData(Qt::UserRole, QVariant(trc));
ui->videoTableWidget->setItem(5, 1, trcItem);
ui->videoTrackComboBox->setCurrentIndex(videoIndex + 1);
}
ui->tabWidget->setTabEnabled(0, true);
videoIndex++;
} else if (streamType == "audio") {
key = QStringLiteral("meta.media.%1.codec.name").arg(i);
QString codec(m_producer->get(key.toLatin1().constData()));
key = QStringLiteral("meta.media.%1.codec.channels").arg(i);
int channels(m_producer->get_int(key.toLatin1().constData()));
totalAudioChannels += channels;
key = QStringLiteral("meta.media.%1.codec.sample_rate").arg(i);
QString sampleRate(m_producer->get(key.toLatin1().constData()));
QString name = QStringLiteral("%1: %2 ch %3 KHz %4")
.arg(audioIndex + 1)
.arg(channels)
.arg(sampleRate.toDouble() / 1000)
.arg(codec);
if (populateTrackCombos) {
if (ui->audioTrackComboBox->count() == 0)
ui->audioTrackComboBox->addItem(tr("None"), -1);
#if LIBMLT_VERSION_INT >= ((7<<16)+(19<<8))
ui->audioTrackComboBox->addItem(name, audioIndex);
}
if (QString::number(audioIndex) == m_producer->get(kAudioIndexProperty)) {
#else
ui->audioTrackComboBox->addItem(name, i);
}
if (QString::number(i) == m_producer->get(kAudioIndexProperty)) {
#endif
key = QStringLiteral("meta.media.%1.codec.long_name").arg(i);
QString codec(m_producer->get(key.toLatin1().constData()));
ui->audioTableWidget->setItem(0, 1, new QTableWidgetItem(codec));
key = QStringLiteral("meta.media.%1.codec.layout").arg(i);
QString layout(m_producer->get(key.toLatin1().constData()));
if (layout.isEmpty()) {
layout = mlt_audio_channel_layout_name(mlt_audio_channel_layout_default(channels));
}
QString channelsStr = QStringLiteral("%1 (%2)").arg(channels).arg(layout);
ui->audioTableWidget->setItem(1, 1, new QTableWidgetItem(channelsStr));
ui->audioTableWidget->setItem(2, 1, new QTableWidgetItem(sampleRate));
key = QStringLiteral("meta.media.%1.codec.sample_fmt").arg(i);
ui->audioTableWidget->setItem(3, 1, new QTableWidgetItem(
m_producer->get(key.toLatin1().constData())));
ui->audioTrackComboBox->setCurrentIndex(audioIndex + 1);
}
ui->tabWidget->setTabEnabled(1, true);
audioIndex++;
}
}
if (populateTrackCombos && ui->audioTrackComboBox->count() > 2)
ui->audioTrackComboBox->addItem(tr("All"), "all");
if (m_producer->get(kAbsoluteAudioIndex) == QStringLiteral("-1")) {
ui->audioTrackComboBox->setCurrentIndex(0);
ui->audioTableWidget->setItem(0, 1, new QTableWidgetItem(""));
ui->audioTableWidget->setItem(1, 1, new QTableWidgetItem("0"));
ui->audioTableWidget->setItem(2, 1, new QTableWidgetItem(""));
ui->audioTableWidget->setItem(3, 1, new QTableWidgetItem(""));
} else if (m_producer->get(kAbsoluteAudioIndex) == QStringLiteral("all")) {
ui->audioTrackComboBox->setCurrentIndex(ui->audioTrackComboBox->count() - 1);
ui->audioTableWidget->setItem(0, 1, new QTableWidgetItem(""));
ui->audioTableWidget->setItem(1, 1, new QTableWidgetItem(QString::number(totalAudioChannels)));
ui->audioTableWidget->setItem(2, 1, new QTableWidgetItem(""));
ui->audioTableWidget->setItem(3, 1, new QTableWidgetItem(""));
}
if (m_producer->get("video_index") == QStringLiteral("-1")) {
ui->videoTrackComboBox->setCurrentIndex(0);
ui->videoTableWidget->setItem(0, 1, new QTableWidgetItem(""));
ui->videoTableWidget->setItem(1, 1, new QTableWidgetItem(""));
ui->videoTableWidget->setItem(2, 1, new QTableWidgetItem(""));
ui->videoTableWidget->setItem(3, 1, new QTableWidgetItem(""));
ui->videoTableWidget->setItem(4, 1, new QTableWidgetItem(""));
ui->videoTableWidget->setItem(5, 1, new QTableWidgetItem(""));
ui->proxyButton->hide();
}
// Restore the previous tab, or select the first enabled tab.
if (ui->tabWidget->isTabEnabled(tabIndex))
ui->tabWidget->setCurrentIndex(tabIndex);
else if (ui->tabWidget->isTabEnabled(0))
ui->tabWidget->setCurrentIndex(0);
else if (ui->tabWidget->isTabEnabled(1))
ui->tabWidget->setCurrentIndex(1);
int width = m_producer->get_int("meta.media.width");
int height = m_producer->get_int("meta.media.height");
if (width || height) {
bool isProxy = m_producer->get_int(kIsProxyProperty) && m_producer->get(kOriginalResourceProperty);
ui->videoTableWidget->setItem(1, 1,
new QTableWidgetItem(QStringLiteral("%1x%2 %3").arg(width).arg(height)
.arg(isProxy ? tr("(PROXY)") : "")));
}
double sar = m_producer->get_double("meta.media.sample_aspect_num");
if (m_producer->get_double("meta.media.sample_aspect_den") > 0)
sar /= m_producer->get_double("meta.media.sample_aspect_den");
if (m_producer->get("force_aspect_ratio"))
sar = m_producer->get_double("force_aspect_ratio");
int dar_numerator = width * sar;
int dar_denominator = height;
if (height > 0) {
switch (int(sar * width / height * 100)) {
case 133:
dar_numerator = 4;
dar_denominator = 3;
break;
case 177:
dar_numerator = 16;
dar_denominator = 9;
break;
case 56:
dar_numerator = 9;
dar_denominator = 16;
}
}
if (m_producer->get(kAspectRatioNumerator))
dar_numerator = m_producer->get_int(kAspectRatioNumerator);
if (m_producer->get(kAspectRatioDenominator))
dar_denominator = m_producer->get_int(kAspectRatioDenominator);
ui->aspectNumSpinBox->blockSignals(true);
ui->aspectNumSpinBox->setValue(dar_numerator);
ui->aspectNumSpinBox->blockSignals(false);
ui->aspectDenSpinBox->blockSignals(true);
ui->aspectDenSpinBox->setValue(dar_denominator);
ui->aspectDenSpinBox->blockSignals(false);
bool isVariableFrameRate = m_producer->get_int("meta.media.variable_frame_rate");
if (fps() != 0.0 ) {
ui->videoTableWidget->setItem(2, 1, new QTableWidgetItem(QStringLiteral("%L1 %2").arg(fps(), 0, 'f',
6)
.arg(isVariableFrameRate ? tr("(variable)") : "")));
}
int progressive = m_producer->get_int("meta.media.progressive");
if (m_producer->get("force_progressive"))
progressive = m_producer->get_int("force_progressive");
ui->scanComboBox->setCurrentIndex(progressive);
int tff = m_producer->get_int("meta.media.top_field_first");
if (m_producer->get("force_tff"))
tff = m_producer->get_int("force_tff");
ui->fieldOrderComboBox->setCurrentIndex(tff);
ui->fieldOrderComboBox->setEnabled(!progressive);
if (m_producer->get("color_range"))
color_range = m_producer->get_int("color_range") == 2;
else if (m_producer->get("force_full_range"))
color_range = m_producer->get_int("force_full_range");
ui->rangeComboBox->setCurrentIndex(color_range);
if (populateTrackCombos) {
for (int i = 0; i < m_producer->count(); i++) {
QString name(m_producer->get_name(i));
if (name.startsWith("meta.attr.") && name.endsWith(".markup")) {
int row = ui->metadataTable->rowCount();
ui->metadataTable->setRowCount(row + 1);
ui->metadataTable->setItem(row, 0, new QTableWidgetItem(name.section('.', -2, -2)));
ui->metadataTable->setItem(row, 1, new QTableWidgetItem(m_producer->get(i)));
if (ui->metadataTable->item(row, 0)->text() == "handler_name"
&& QString(m_producer->get(i)).contains("GoPro")) {
ui->actionExportGPX->setEnabled(true);
}
ui->tabWidget->setTabEnabled(2, true);
}
}
}
ui->syncSlider->setValue(qRound(m_producer->get_double("video_delay") * 1000.0));
setSyncVisibility();
}
void AvformatProducerWidget::on_videoTrackComboBox_activated(int index)
{
if (m_producer) {
m_producer->set(kVideoIndexProperty, ui->videoTrackComboBox->itemData(index).toInt());
recreateProducer();
}
}
void AvformatProducerWidget::on_audioTrackComboBox_activated(int index)
{
if (m_producer) {
// Save the default audio index for AudioLevelsTask.
if (!m_producer->get(kDefaultAudioIndexProperty)) {
m_producer->set(kDefaultAudioIndexProperty, m_producer->get_int(kAbsoluteAudioIndex));
}
if (!qstrcmp(m_producer->get(kAbsoluteAudioIndex), "all"))
m_producer->Mlt::Properties::clear(kAbsoluteAudioIndex);
m_producer->set(kAudioIndexProperty,
ui->audioTrackComboBox->itemData(index).toString().toUtf8().constData());
recreateProducer(true);
}
}
void AvformatProducerWidget::on_scanComboBox_activated(int index)
{
if (m_producer) {
int progressive = m_producer->get_int("meta.media.progressive");
ui->fieldOrderComboBox->setEnabled(!progressive);
if (m_producer->get("force_progressive") || progressive != index)
// We need to set these force_ properties as a string so they can be properly removed
// by setting them NULL.
m_producer->set("force_progressive", QString::number(index).toLatin1().constData());
emit producerChanged(producer());
}
}
void AvformatProducerWidget::on_fieldOrderComboBox_activated(int index)
{
if (m_producer) {
int tff = m_producer->get_int("meta.media.top_field_first");
if (m_producer->get("force_tff") || tff != index)
m_producer->set("force_tff", QString::number(index).toLatin1().constData());
emit producerChanged(producer());
}
}
void AvformatProducerWidget::on_aspectNumSpinBox_valueChanged(int)
{
if (m_producer) {
double new_sar = double(ui->aspectNumSpinBox->value() * m_producer->get_int("meta.media.height")) /
double(ui->aspectDenSpinBox->value() * m_producer->get_int("meta.media.width"));
double sar = m_producer->get_double("meta.media.sample_aspect_num");
if (m_producer->get_double("meta.media.sample_aspect_den") > 0)
sar /= m_producer->get_double("meta.media.sample_aspect_den");
if (m_producer->get("force_aspect_ratio") || new_sar != sar) {
m_producer->set("force_aspect_ratio", QString::number(new_sar).toLatin1().constData());
m_producer->set(kAspectRatioNumerator, ui->aspectNumSpinBox->text().toLatin1().constData());
m_producer->set(kAspectRatioDenominator, ui->aspectDenSpinBox->text().toLatin1().constData());
}
emit producerChanged(producer());
}
}
void AvformatProducerWidget::on_aspectDenSpinBox_valueChanged(int i)
{
on_aspectNumSpinBox_valueChanged(i);
}
void AvformatProducerWidget::on_durationSpinBox_editingFinished()
{
if (!m_producer)
return;
if (ui->durationSpinBox->value() == m_producer->get_length())
return;
recreateProducer();
}
void AvformatProducerWidget::on_speedSpinBox_editingFinished()
{
if (!m_producer)
return;
if (ui->speedSpinBox->value() == Util::GetSpeedFromProducer(producer()))
return;
if (ui->speedSpinBox->value() == 1.0) {
ui->pitchCheckBox->setEnabled(false);
} else {
ui->pitchCheckBox->setEnabled(true);
}
m_recalcDuration = true;
recreateProducer();
}
void AvformatProducerWidget::on_pitchCheckBox_stateChanged(int state)
{
if (!m_producer)
return;
if (state == Qt::Unchecked) {
m_producer->set("warp_pitch", 0);
} else {
m_producer->set("warp_pitch", 1);
}
emit modified();
}
void AvformatProducerWidget::on_syncSlider_valueChanged(int value)
{
double delay = double(value) / 1000.0;
if (m_producer && m_producer->get_double("video_delay") != delay) {
m_producer->set("video_delay", delay);
emit modified();
}
}
void AvformatProducerWidget::on_actionOpenFolder_triggered()
{
Util::showInFolder(Util::GetFilenameFromProducer(producer()));
}
void AvformatProducerWidget::on_menuButton_clicked()
{
QMenu menu;
menu.addAction(ui->actionReset);
if (!MLT.resource().contains("://")) // not a network stream
menu.addAction(ui->actionOpenFolder);
menu.addAction(ui->actionCopyFullFilePath);
menu.addAction(ui->actionFFmpegInfo);
menu.addAction(ui->actionFFmpegIntegrityCheck);
menu.addAction(ui->actionFFmpegConvert);
menu.addAction(ui->actionExtractSubclip);
menu.addAction(ui->actionExtractSubtitles);
menu.addAction(ui->actionSetFileDate);
if (Util::GetFilenameFromProducer(producer()).toLower().endsWith(".mp4")
|| Util::GetFilenameFromProducer(producer()).toLower().endsWith(".mov")) {
menu.addAction(ui->actionSetEquirectangular);
}
menu.addAction(ui->actionFFmpegVideoQuality);
if (ui->actionExportGPX->isEnabled()) {
menu.addAction(ui->actionExportGPX);
}
menu.addAction(ui->actionBitrateViewer);
menu.exec(ui->menuButton->mapToGlobal(QPoint(0, 0)));
}
void AvformatProducerWidget::on_actionCopyFullFilePath_triggered()
{
auto s = Util::GetFilenameFromProducer(producer());
qApp->clipboard()->setText(QDir::toNativeSeparators(s));
}
void AvformatProducerWidget::on_notesTextEdit_textChanged()
{
QString existing = QString::fromUtf8(m_producer->get(kCommentProperty));
if (ui->notesTextEdit->toPlainText() != existing) {
m_producer->set(kCommentProperty, ui->notesTextEdit->toPlainText().toUtf8().constData());
emit modified();
}
}
void AvformatProducerWidget::on_actionFFmpegInfo_triggered()
{
QStringList args;
args << "-v" << "quiet";
args << "-print_format" << "ini";
args << "-pretty";
args << "-show_format" << "-show_programs" << "-show_streams" << "-find_stream_info";
args << Util::GetFilenameFromProducer(producer());
AbstractJob *job = new FfprobeJob(args.last(), args);
job->start();
}
void AvformatProducerWidget::on_actionFFmpegIntegrityCheck_triggered()
{
QString resource = Util::GetFilenameFromProducer(producer());
QStringList args;
args << "-xerror";
args << "-err_detect" << "+explode";
args << "-v" << "info";
args << "-i" << resource;
args << "-map" << "0";
args << "-f" << "null" << "pipe:";
JOBS.add(new FfmpegJob(resource, args));
}
void AvformatProducerWidget::on_actionFFmpegConvert_triggered()
{
TranscodeDialog dialog(
tr("Choose an edit-friendly format below and then click OK to choose a file name. "
"After choosing a file name, a job is created. "
"When it is done, double-click the job to open it.\n"),
ui->scanComboBox->currentIndex(), this);
dialog.setWindowModality(QmlApplication::dialogModality());
dialog.set709Convert(ui->videoTableWidget->item(5, 1)->data(Qt::UserRole).toInt() > 7);
dialog.showSubClipCheckBox();
auto fps = Util::getAndroidFrameRate(m_producer.get());
if (fps > 0.0)
dialog.setFrameRate(fps);
Transcoder transcoder;
transcoder.addProducer(m_producer.data());
transcoder.convert(dialog);
}
bool AvformatProducerWidget::revertToOriginalResource()
{
QString resource = m_producer->get(kOriginalResourceProperty);
if (!resource.isEmpty() && !m_producer->get_int(kIsProxyProperty)) {
m_producer->Mlt::Properties::clear(kOriginalResourceProperty);
if (m_producer->get(kMultitrackItemProperty)) {
QString s = QString::fromLatin1(m_producer->get(kMultitrackItemProperty));
auto parts = s.split(':');
if (parts.length() == 2) {
int clipIndex = parts[0].toInt();
int trackIndex = parts[1].toInt();
QUuid uuid = MAIN.timelineClipUuid(trackIndex, clipIndex);
if (!uuid.isNull()) {
Mlt::Producer newProducer(MLT.profile(), resource.toUtf8().constData());
if (newProducer.is_valid()) {
Mlt::Producer *producer = MLT.setupNewProducer(&newProducer);
producer->set(kIsProxyProperty, 1);
producer->set(kOriginalResourceProperty, resource.toUtf8().constData());
producer->set_in_and_out(m_producer->get_int(kOriginalInProperty),
m_producer->get_int(kOriginalOutProperty));
MAIN.replaceInTimeline(uuid, *producer);
delete producer;
return true;
}
}
}
} else {
MAIN.open(resource);
return true;
}
}
return false;
}
void AvformatProducerWidget::setSyncVisibility()
{
bool visible = ui->tabWidget->isTabEnabled(0) && ui->tabWidget->isTabEnabled(1) &&
m_producer->get_int("video_index") != -1;
ui->syncSlider->setVisible(visible);
ui->syncLabel->setVisible(visible);
ui->syncSpinBox->setVisible(visible);
}
double AvformatProducerWidget::fps()
{
double fps = m_producer->get_double("meta.media.frame_rate_num");
if (m_producer->get_double("meta.media.frame_rate_den") > 0)
fps /= m_producer->get_double("meta.media.frame_rate_den");
if (m_producer->get("force_fps"))
fps = m_producer->get_double("fps");
return fps;
}
void AvformatProducerWidget::on_reverseButton_clicked()
{
if (revertToOriginalResource())
return;
TranscodeDialog dialog(
tr("Choose an edit-friendly format below and then click OK to choose a file name. "
"After choosing a file name, a job is created. "
"When it is done, double-click the job to open it.\n"),
ui->scanComboBox->currentIndex(), this);
dialog.setWindowTitle(tr("Reverse..."));
dialog.setWindowModality(QmlApplication::dialogModality());
int result = dialog.exec();
if (dialog.isCheckBoxChecked()) {
Settings.setShowConvertClipDialog(false);
}
if (result == QDialog::Accepted) {
QString resource = Util::GetFilenameFromProducer(producer());
QString path = Settings.savePath();
QStringList meltArgs;
QStringList ffmpegArgs;
QString nameFilter;
QString ffmpegSuffix = "mov";
int in = -1;
if (Settings.proxyEnabled()) {
m_producer->Mlt::Properties::clear(kOriginalResourceProperty);
} else {
// Save these properties for revertToOriginalResource()
m_producer->set(kOriginalResourceProperty, resource.toUtf8().constData());
m_producer->set(kOriginalInProperty, m_producer->get(kFilterInProperty) ?
m_producer->get_time(kFilterInProperty, mlt_time_clock) : m_producer->get_time("in",
mlt_time_clock));
m_producer->set(kOriginalOutProperty, m_producer->get(kFilterOutProperty) ?
m_producer->get_time(kFilterOutProperty, mlt_time_clock) : m_producer->get_time("out",
mlt_time_clock));
}
ffmpegArgs << "-loglevel" << "verbose";
ffmpegArgs << "-i" << resource;
ffmpegArgs << "-max_muxing_queue_size" << "9999";
// set trim options
if (m_producer->get(kFilterInProperty)) {
in = m_producer->get_int(kFilterInProperty);
int ss = qMax(0, in - qRound(m_producer->get_fps() * kHandleSeconds));
auto s = QString::fromLatin1(m_producer->frames_to_time(ss, mlt_time_clock));
ffmpegArgs << "-ss" << s.replace(',', '.');
} else {
ffmpegArgs << "-ss" << QString::fromLatin1(m_producer->get_time("in", mlt_time_clock)).replace(',',
'.').replace(',', '.');
}
if (m_producer->get(kFilterOutProperty)) {
int out = m_producer->get_int(kFilterOutProperty);
int to = qMin(m_producer->get_playtime() - 1, out + qRound(m_producer->get_fps() * kHandleSeconds));
in = to - out - 1;
auto s = QString::fromLatin1(m_producer->frames_to_time(to, mlt_time_clock));
ffmpegArgs << "-to" << s.replace(',', '.');
} else {
ffmpegArgs << "-to" << QString::fromLatin1(m_producer->get_time("out", mlt_time_clock)).replace(',',
'.');
}
// transcode all streams except data, subtitles, and attachments
ffmpegArgs << "-map" << "0:V?" << "-map" << "0:a?" << "-map_metadata" << "0" << "-ignore_unknown";
if (ui->rangeComboBox->currentIndex())
ffmpegArgs << "-vf" <<
"scale=flags=accurate_rnd+full_chroma_inp+full_chroma_int:in_range=full:out_range=full" <<
"-color_range" << "jpeg";
else
ffmpegArgs << "-vf" <<
"scale=flags=accurate_rnd+full_chroma_inp+full_chroma_int:in_range=mpeg:out_range=mpeg" <<
"-color_range" << "mpeg";
if (!ui->scanComboBox->currentIndex())
ffmpegArgs << "-flags" << "+ildct+ilme" << "-top" << QString::number(
ui->fieldOrderComboBox->currentIndex());
meltArgs << "-consumer" << "avformat";
if (m_producer->get_int(kAbsoluteAudioIndex) == -1) {
meltArgs << "an=1" << "audio_off=1";
} else if (qstrcmp(m_producer->get(kAbsoluteAudioIndex), "all")) {
int index = m_producer->get_int(kAbsoluteAudioIndex);
QString key = QStringLiteral("meta.media.%1.codec.channels").arg(index);
const char *channels = m_producer->get(key.toLatin1().constData());
meltArgs << QStringLiteral("channels=").append(channels);
}
if (m_producer->get_int("video_index") == -1)
meltArgs << "vn=1" << "video_off=1";
ffmpegArgs << "-f" << "mov" << "-codec:a" << "pcm_f32le";
switch (dialog.format()) {
case 0:
path.append("/%1 - %2.mp4");
nameFilter = tr("MP4 (*.mp4);;All Files (*)");
if (ui->scanComboBox->currentIndex()) { // progressive
ffmpegArgs << "-codec:v" << "dnxhd" << "-profile:v" << "dnxhr_hq" << "-pix_fmt" << "yuv422p";
} else { // interlaced
ffmpegArgs << "-codec:v" << "prores_ks" << "-profile:v" << "standard";
meltArgs << "top_field_first=" + QString::number(ui->fieldOrderComboBox->currentIndex());
}
meltArgs << "acodec=ac3" << "ab=512k" << "vcodec=libx264";
meltArgs << "vpreset=medium" << "g=1" << "crf=11";
break;
case 1:
meltArgs << "acodec=alac";
if (ui->scanComboBox->currentIndex()) { // progressive
ffmpegArgs << "-codec:v" << "dnxhd" << "-profile:v" << "dnxhr_hq" << "-pix_fmt" << "yuv422p";
meltArgs << "vcodec=dnxhd" << "vprofile=dnxhr_hq";
} else { // interlaced
ffmpegArgs << "-codec:v" << "prores_ks" << "-profile:v" << "standard";
meltArgs << "top_field_first=" + QString::number(ui->fieldOrderComboBox->currentIndex());
meltArgs << "vcodec=prores_ks" << "vprofile=standard";
}
path.append("/%1 - %2.mov");
nameFilter = tr("MOV (*.mov);;All Files (*)");
break;
case 2:
ffmpegArgs << "-codec:v" << "utvideo" << "-pix_fmt" << "yuv422p";
if (!ui->scanComboBox->currentIndex()) { // interlaced
meltArgs << "field_order=" + QString::fromLatin1(ui->fieldOrderComboBox->currentIndex() ? "tt" :
"bb");
}
meltArgs << "acodec=pcm_f32le" << "vcodec=utvideo" << "mlt_audio_format=f32le" << "pix_fmt=yuv422p";
path.append("/%1 - %2.mkv");
nameFilter = tr("MKV (*.mkv);;All Files (*)");
break;
}
QFileInfo fi(resource);
path = path.arg(fi.completeBaseName()).arg(tr("Reversed"));
QString filename = QmlApplication::getNextProjectFile(path);
if (filename.isEmpty()) {
filename = QFileDialog::getSaveFileName(this, dialog.windowTitle(), path, nameFilter,
nullptr, Util::getFileDialogOptions());
}
if (!filename.isEmpty()) {
if (filename == QDir::toNativeSeparators(resource)) {
QMessageBox::warning(this, dialog.windowTitle(),
QObject::tr("Unable to write file %1\n"
"Perhaps you do not have permission.\n"
"Try again with a different folder.")
.arg(fi.fileName()));
return;
}
if (Util::warnIfNotWritable(filename, this, dialog.windowTitle()))
return;
if (Util::warnIfLowDiskSpace(filename)) {
MAIN.showStatusMessage(tr("Reverse canceled"));
return;
}
Settings.setSavePath(QFileInfo(filename).path());
// Make a temporary file name for the ffmpeg job.
QFileInfo fi(filename);
QString tmpFileName = QStringLiteral("%1/%2 - XXXXXX.%3").arg(fi.path()).arg(
fi.completeBaseName()).arg(
ffmpegSuffix);
QTemporaryFile tmp(tmpFileName);
tmp.setAutoRemove(false);
tmp.open();
tmp.close();
tmpFileName = tmp.fileName();
// Run the ffmpeg job to convert a portion of the file to something edit-friendly.
ffmpegArgs << "-y" << tmpFileName;
FfmpegJob *ffmpegJob = new FfmpegJob(filename, ffmpegArgs, false);
ffmpegJob->setLabel(tr("Convert %1").arg(Util::baseName(resource)));
JOBS.add(ffmpegJob);
// Run the melt job to convert the intermediate file to the reversed clip.
meltArgs.prepend(QStringLiteral("timewarp:-1.0:").append(tmpFileName));
meltArgs << QStringLiteral("target=").append(filename);
MeltJob *meltJob = new MeltJob(filename, meltArgs,
m_producer->get_int("meta.media.frame_rate_num"), m_producer->get_int("meta.media.frame_rate_den"));
meltJob->setLabel(tr("Reverse %1").arg(Util::baseName(resource)));
if (m_producer->get(kMultitrackItemProperty)) {
QString s = QString::fromLatin1(m_producer->get(kMultitrackItemProperty));
auto parts = s.split(':');
if (parts.length() == 2) {
int clipIndex = parts[0].toInt();
int trackIndex = parts[1].toInt();
QUuid uuid = MAIN.timelineClipUuid(trackIndex, clipIndex);
if (!uuid.isNull()) {
meltJob->setPostJobAction(new ReplaceOnePostJobAction(resource, filename, tmpFileName,
uuid, in));
JOBS.add(meltJob);
return;
}
}
}
meltJob->setPostJobAction(new OpenPostJobAction(resource, filename, tmpFileName));
JOBS.add(meltJob);
}
}
}
void AvformatProducerWidget::on_actionExtractSubclip_triggered()
{
QString resource = Util::GetFilenameFromProducer(producer());
QString path = Settings.savePath();
QFileInfo fi(resource);
path.append("/%1 - %2.%3");
path = path.arg(fi.completeBaseName()).arg(tr("Sub-clip")).arg(fi.suffix());
QString caption = tr("Extract Sub-clip...");
QString nameFilter = tr("%1 (*.%2);;All Files (*)").arg(fi.suffix()).arg(fi.suffix());
QString filename = QFileDialog::getSaveFileName(this, caption, path, nameFilter,
nullptr, Util::getFileDialogOptions());
if (!filename.isEmpty()) {
if (filename == QDir::toNativeSeparators(resource)) {
QMessageBox::warning(this, caption,
QObject::tr("Unable to write file %1\n"
"Perhaps you do not have permission.\n"
"Try again with a different folder.")
.arg(fi.fileName()));
return;
}
if (Util::warnIfNotWritable(filename, this, caption))
return;
Settings.setSavePath(QFileInfo(filename).path());
QStringList ffmpegArgs;
// Build the ffmpeg command line.
ffmpegArgs << "-loglevel" << "verbose";
ffmpegArgs << "-i" << resource;
// set trim options
if (m_producer->get_int(kFilterInProperty) || m_producer->get_int("in")) {
if (m_producer->get(kFilterInProperty))
ffmpegArgs << "-ss" << QString::fromLatin1(m_producer->get_time(kFilterInProperty,
mlt_time_clock)).replace(',', '.');
else
ffmpegArgs << "-ss" << QString::fromLatin1(m_producer->get_time("in", mlt_time_clock)).replace(',',
'.').replace(',', '.');
}
if (m_producer->get(kFilterOutProperty))
ffmpegArgs << "-to" << QString::fromLatin1(m_producer->get_time(kFilterOutProperty,
mlt_time_clock)).replace(',', '.');
else
ffmpegArgs << "-to" << QString::fromLatin1(m_producer->get_time("out", mlt_time_clock)).replace(',',
'.');
ffmpegArgs << "-avoid_negative_ts" << "make_zero"
<< "-map" << "0:V?" << "-map" << "0:a?" << "-map" << "0:s?"
<< "-map_metadata" << "0"
<< "-codec" << "copy" << "-y" << filename;
// Run the ffmpeg job.
FfmpegJob *ffmpegJob = new FfmpegJob(filename, ffmpegArgs, false);
ffmpegJob->setLabel(tr("Extract sub-clip %1").arg(Util::baseName(resource)));
JOBS.add(ffmpegJob);
}
}
void AvformatProducerWidget::on_actionExtractSubtitles_triggered()
{
QStringList subtitles;
int nb_streams = m_producer->get_int("meta.media.nb_streams");
int subtitleCount = 0;
for (int i = 0; i < nb_streams; i++) {
QString key = QStringLiteral("meta.media.%1.codec.name").arg(i);
QString codec(m_producer->get(key.toLatin1().constData()));
if (codec == "srt") {
subtitleCount++;
QString langKey = QStringLiteral("meta.attr.%1.stream.language.markup").arg(i);
QString lang(m_producer->get(langKey.toLatin1().constData()));
if (lang.isEmpty()) {
subtitles << tr("Track %1").arg(subtitleCount);
} else {
subtitles << tr("Track %1 (%2)").arg(subtitleCount).arg(lang);
}
}
}
QString caption = tr("Export Subtitles...");
if (subtitles.size() <= 0) {
QMessageBox::warning(this, caption, tr("No subtitles found"));
return;
}
// Prompt the user to select the subtitle stream
ListSelectionDialog dialog(subtitles, this);
dialog.setWindowModality(QmlApplication::dialogModality());
dialog.setWindowTitle(caption);
dialog.setSelection(QStringList(subtitles[0]));
if (dialog.exec() != QDialog::Accepted || dialog.selection().isEmpty()) {
LOG_WARNING() << "No subtitles selected";
return;
}
QStringList subSelection = dialog.selection();
// Prompt the user for the directory to save the file(s)
QString resource = Util::GetFilenameFromProducer(producer());
QFileInfo fi(resource);
QString pathTemplate = QFileDialog::getExistingDirectory(this, caption, Settings.savePath(),
Util::getFileDialogOptions());
if (pathTemplate.isEmpty()) {
LOG_WARNING() << "No path specified";
return;
}
// Extract the subtitle(s)
pathTemplate = QDir::toNativeSeparators(pathTemplate);
pathTemplate.append("/%1");
pathTemplate = pathTemplate.arg(fi.completeBaseName());
pathTemplate.append(" - %1.srt");
for (int s = 0; s < subSelection.size(); s++) {
int subtitleCount = 0;
for (int i = 0; i < nb_streams; i++) {
QString key = QStringLiteral("meta.media.%1.codec.name").arg(i);
QString codec(m_producer->get(key.toLatin1().constData()));
if (codec == "srt") {
subtitleCount++;
QString subText;
QString langKey = QStringLiteral("meta.attr.%1.stream.language.markup").arg(i);
QString lang(m_producer->get(langKey.toLatin1().constData()));
if (lang.isEmpty()) {
subText = tr("Track %1").arg(subtitleCount);
} else {
subText = tr("Track %1 (%2)").arg(subtitleCount).arg(lang);
}
if (subText == subSelection[s]) {
QString path = pathTemplate.arg(subText);
if (Util::warnIfNotWritable(path, this, caption))
return;
// Make an FFMpeg job
QStringList ffmpegArgs;
QString streamSelect = QStringLiteral("0:s:%1").arg(subtitleCount - 1);
ffmpegArgs << "-loglevel" << "verbose";
ffmpegArgs << "-i" << resource;
ffmpegArgs << "-map" << streamSelect;
ffmpegArgs << "-y" << path;
FfmpegJob *ffmpegJob = new FfmpegJob(path, ffmpegArgs, false);
ffmpegJob->setLabel(tr("Extract subtitles %1").arg(Util::baseName(path)));
JOBS.add(ffmpegJob);
}
}
}
}
}
void AvformatProducerWidget::on_actionSetFileDate_triggered()
{
QString resource = Util::GetFilenameFromProducer(producer());
FileDateDialog dialog(resource, producer(), this);
dialog.setModal(QmlApplication::dialogModality());
dialog.exec();
}
void AvformatProducerWidget::on_rangeComboBox_activated(int index)
{
if (m_producer) {
m_producer->set("color_range", index ? 2 : 1);
recreateProducer();
}
}
void AvformatProducerWidget::on_filenameLabel_editingFinished()
{
if (m_producer) {
const auto caption = ui->filenameLabel->text();
if (caption.isEmpty()) {
double warpSpeed = Util::GetSpeedFromProducer(producer());
QString resource = Util::GetFilenameFromProducer(producer());
QString caption = Util::baseName(resource, true);
if (warpSpeed != 1.0)
caption = QStringLiteral("%1 (%2x)").arg(caption).arg(warpSpeed);
m_producer->set(kShotcutCaptionProperty, caption.toUtf8().constData());
ui->filenameLabel->setText(caption);
} else {
m_producer->set(kShotcutCaptionProperty, caption.toUtf8().constData());
}
emit modified();
}
}
void AvformatProducerWidget::on_convertButton_clicked()
{
on_actionFFmpegConvert_triggered();
}
void AvformatProducerWidget::on_actionDisableProxy_triggered(bool checked)
{
if (checked) {
producer()->set(kDisableProxyProperty, 1);
// Replace with original
if (producer()->get_int(kIsProxyProperty) && producer()->get(kOriginalResourceProperty)) {
Mlt::Producer original(MLT.profile(), producer()->get(kOriginalResourceProperty));
if (original.is_valid()) {
Mlt::Producer *producer = MLT.setupNewProducer(&original);
producer->set(kDisableProxyProperty, 1);
MAIN.replaceAllByHash(Util::getHash(original), *producer, true);
delete producer;
}
}
} else {
producer()->Mlt::Properties::clear(kDisableProxyProperty);
ui->actionMakeProxy->setEnabled(true);
}
}
void AvformatProducerWidget::on_actionMakeProxy_triggered()
{
bool fullRange = ui->rangeComboBox->currentIndex() == 1;
QPoint aspectRatio(ui->aspectNumSpinBox->value(), ui->aspectDenSpinBox->value());
ProxyManager::ScanMode scan = ProxyManager::Progressive;
if (!ui->scanComboBox->currentIndex())
scan = ui->fieldOrderComboBox->currentIndex() ? ProxyManager::InterlacedTopFieldFirst
: ProxyManager::InterlacedBottomFieldFirst;
// If rotation is 90 or 270, swap aspect ratio since auto-rotate is turned off
if (ui->rotationComboBox->currentIndex() % 2 == 1)
aspectRatio = aspectRatio.transposed();
ProxyManager::generateVideoProxy(*producer(), fullRange, scan, aspectRatio);
}
void AvformatProducerWidget::on_actionDeleteProxy_triggered()
{
// Delete the file if it exists
QString hash = Util::getHash(*producer());
QString fileName = hash + ProxyManager::videoFilenameExtension();
QDir dir = ProxyManager::dir();
LOG_DEBUG() << "removing" << dir.filePath(fileName);
dir.remove(dir.filePath(fileName));
// Delete the pending file if it exists));
fileName = hash + ProxyManager::pendingVideoExtension();
dir.remove(dir.filePath(fileName));
// Replace with original
if (producer()->get_int(kIsProxyProperty) && producer()->get(kOriginalResourceProperty)) {
Mlt::Producer original(MLT.profile(), producer()->get(kOriginalResourceProperty));
if (original.is_valid()) {
Mlt::Producer *producer = MLT.setupNewProducer(&original);
MAIN.replaceAllByHash(hash, *producer, true);
delete producer;
}
}
}
void AvformatProducerWidget::on_actionCopyHashCode_triggered()
{
qApp->clipboard()->setText(Util::getHash(*producer()));
QMessageBox::information(this, qApp->applicationName(),
tr("The hash code below is already copied to your clipboard:\n\n") +
Util::getHash(*producer()),
QMessageBox::Ok);
}
void AvformatProducerWidget::on_proxyButton_clicked()
{
if (m_producer->get_int("video_index") >= 0) {
QMenu menu;
if (ProxyManager::isValidVideo(*producer())) {
menu.addAction(ui->actionMakeProxy);
}
#ifndef Q_OS_WIN
menu.addAction(ui->actionDeleteProxy);
#endif
menu.addAction(ui->actionDisableProxy);
menu.addAction(ui->actionCopyHashCode);
if (m_producer->get_int(kDisableProxyProperty)) {
ui->actionMakeProxy->setDisabled(true);
ui->actionDisableProxy->setChecked(true);
}
menu.exec(ui->proxyButton->mapToGlobal(QPoint(0, 0)));
}
}
void AvformatProducerWidget::on_actionReset_triggered()
{
ui->speedSpinBox->setValue(1.0);
ui->pitchCheckBox->setCheckState(Qt::Unchecked);
Mlt::Producer *p = newProducer(MLT.profile());
ui->durationSpinBox->setValue(m_defaultDuration);
ui->syncSlider->setValue(0);
Mlt::Controller::copyFilters(*m_producer, *p);
if (m_producer->get(kMultitrackItemProperty)) {
emit producerChanged(p);
delete p;
} else {
reopen(p);
}
}
void AvformatProducerWidget::on_actionSetEquirectangular_triggered()
{
// Get the location and file name for the report.
QString caption = tr("Set Equirectangular Projection");
QFileInfo info(Util::GetFilenameFromProducer(producer()));
QString directory = QStringLiteral("%1/%2 - ERP.%3")
.arg(info.path())
.arg(info.completeBaseName())
.arg(info.suffix());
QString filePath = QFileDialog::getSaveFileName(&MAIN, caption, directory, QString(),
nullptr, Util::getFileDialogOptions());
if (!filePath.isEmpty()) {
if (SpatialMedia::injectSpherical(info.filePath().toStdString(), filePath.toStdString())) {
MAIN.showStatusMessage(tr("Successfully wrote %1").arg(QFileInfo(filePath).fileName()));
} else {
MAIN.showStatusMessage(tr("An error occurred saving the projection."));
}
}
}
void AvformatProducerWidget::on_actionFFmpegVideoQuality_triggered()
{
QString caption = tr("Choose the Other Video");
QFileInfo info(Util::GetFilenameFromProducer(producer()));
QString directory = QStringLiteral("%1/%2 - ERP.%3").arg(info.path(), info.completeBaseName(),
info.suffix());
QString filePath = QFileDialog::getOpenFileName(&MAIN, caption, directory, QString(),
nullptr, Util::getFileDialogOptions());
if (!filePath.isEmpty()) {
QString resource = Util::GetFilenameFromProducer(producer());
QDir dir = QmlApplication::dataDir();
dir.cd("vmaf");
QStringList args;
args << "-hide_banner";
args << "-i" << resource;
args << "-i" << filePath;
args << "-filter_complex";
int width = m_producer->get_int("meta.media.width");
int height = m_producer->get_int("meta.media.height");
int frameRateNum, frameRateDen;
Util::normalizeFrameRate(fps(), frameRateNum, frameRateDen);
auto colorRange = (ui->rangeComboBox->currentIndex() == 1) ? "full" : "limited";
#ifdef Q_OS_WIN
auto logPath = "con\\:";
auto modelPath = (width < 3840
&& height < 2160) ? "share/vmaf/vmaf_v0.6.1.json" : "share/vmaf/vmaf_4k_v0.6.1.json";
#else
auto logPath = "/dev/stderr";
auto modelPath = (width < 3840
&& height < 2160) ? dir.filePath("vmaf_v0.6.1.json") : dir.filePath("vmaf_4k_v0.6.1.json");
#endif
args << QStringLiteral("[0:v]scale=out_range=%6,fps=%4/%5,setpts=PTS-STARTPTS[reference];[1:v]scale=%1:%2:out_range=%6:flags=bicubic,fps=%4/%5,setpts=PTS-STARTPTS[distorted];[distorted][reference]libvmaf=log_fmt=csv:log_path='%8':feature='name=psnr|name=float_ssim':shortest=true:n_threads=%7:model='path=%3'")
.arg(width).arg(height)
.arg(modelPath)
.arg(frameRateNum).arg(frameRateDen)
.arg(colorRange)
.arg(qRound(QThread::idealThreadCount() / 2.))
.arg(logPath);
args << "-f" << "null" << "pipe:";
FfmpegJob *job = new FfmpegJob(resource, args);
job->setWorkingDirectory(qApp->applicationDirPath());
job->setLabel(tr("Measure %1").arg(Util::baseName(filePath)));
JOBS.add(job);
}
}
void AvformatProducerWidget::on_rotationComboBox_activated(int index)
{
if (m_producer) {
MLT.stop();
m_producer->set("rotate", index * 90);
recreateProducer();
}
}
void AvformatProducerWidget::on_actionExportGPX_triggered()
{
QString resource = Util::GetFilenameFromProducer(producer());
QStringList args;
args << "-s";
args << resource;
JOBS.add(new GoPro2GpxJob(resource, args));
}
void AvformatProducerWidget::on_speedComboBox_textActivated(const QString &arg1)
{
if (arg1.isEmpty()) return;
ui->speedSpinBox->setValue(arg1.toDouble());
on_speedSpinBox_editingFinished();
}
ProbeTask::ProbeTask(Mlt::Producer *producer)
: QObject(0)
, QRunnable()
, m_producer(*producer)
{
}
void ProbeTask::run()
{
m_producer.probe();
emit probeFinished();
}
void AvformatProducerWidget::on_actionBitrateViewer_triggered()
{
QStringList args;
args << "-v" << "quiet";
args << "-print_format" << "json=compact=1";
if (m_producer->get_int("video_index") >= 0)
args << "-select_streams" << QString::fromLatin1("V:%1").arg(m_producer->get_int(
kVideoIndexProperty));
else
args << "-select_streams" << QString::fromLatin1("a:%1").arg(m_producer->get_int(
kAudioIndexProperty));
args << "-show_entries" << "packet=size,duration_time,pts_time,flags";
args << Util::GetFilenameFromProducer(producer());
auto job = new BitrateViewerJob(args.last(), args, fps());
job->setLabel(tr("Bitrate %1").arg(Util::baseName(args.last())));
JOBS.add(job);
}
| 61,821
|
C++
|
.cpp
| 1,321
| 36.390613
| 318
| 0.593553
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,232
|
lissajouswidget.cpp
|
mltframework_shotcut/src/widgets/lissajouswidget.cpp
|
/*
* Copyright (c) 2012-2018 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "shotcut_mlt_properties.h"
#include "lissajouswidget.h"
#include "ui_lissajouswidget.h"
#include "util.h"
static const char *kParamRatioX = "0";
static const char *kParamRatioY = "1";
LissajousWidget::LissajousWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::LissajousWidget)
{
ui->setupUi(this);
Util::setColorsToHighlight(ui->nameLabel);
ui->preset->saveDefaultPreset(getPreset());
ui->preset->loadPresets();
}
LissajousWidget::~LissajousWidget()
{
delete ui;
}
void LissajousWidget::on_xratioDial_valueChanged(int value)
{
if (m_producer) {
m_producer->set(kParamRatioX, value / 100.0);
emit producerChanged(m_producer.data());
}
ui->xratioSpinner->setValue(value / 100.0);
}
void LissajousWidget::on_xratioSpinner_valueChanged(double value)
{
ui->xratioDial->setValue(value * 100);
}
void LissajousWidget::on_yratioDial_valueChanged(int value)
{
if (m_producer) {
m_producer->set(kParamRatioY, value / 100.0);
emit producerChanged(m_producer.data());
}
ui->yratioSpinner->setValue(value / 100.0);
}
void LissajousWidget::on_yratioSpinner_valueChanged(double value)
{
ui->yratioDial->setValue(value * 100);
}
Mlt::Producer *LissajousWidget::newProducer(Mlt::Profile &profile)
{
Mlt::Producer *p = new Mlt::Producer(profile, "frei0r.lissajous0r");
p->set(kParamRatioX, ui->xratioSpinner->text().toLatin1().constData());
p->set(kParamRatioY, ui->yratioSpinner->text().toLatin1().constData());
p->set(kShotcutCaptionProperty, ui->nameLabel->text().toUtf8().constData());
p->set(kShotcutDetailProperty, ui->nameLabel->text().toUtf8().constData());
return p;
}
Mlt::Properties LissajousWidget::getPreset() const
{
Mlt::Properties p;
p.set(kParamRatioX, ui->xratioSpinner->text().toLatin1().constData());
p.set(kParamRatioY, ui->yratioSpinner->text().toLatin1().constData());
return p;
}
void LissajousWidget::loadPreset(Mlt::Properties &p)
{
ui->xratioSpinner->setValue(p.get_double(kParamRatioX));
ui->yratioSpinner->setValue(p.get_double(kParamRatioY));
}
void LissajousWidget::on_preset_selected(void *p)
{
Mlt::Properties *properties = (Mlt::Properties *) p;
loadPreset(*properties);
delete properties;
}
void LissajousWidget::on_preset_saveClicked()
{
ui->preset->savePreset(getPreset());
}
| 3,075
|
C++
|
.cpp
| 90
| 31.122222
| 80
| 0.730485
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
13,233
|
timelinepropertieswidget.cpp
|
mltframework_shotcut/src/widgets/timelinepropertieswidget.cpp
|
/*
* Copyright (c) 2015-2022 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "timelinepropertieswidget.h"
#include "ui_timelinepropertieswidget.h"
#include "mltcontroller.h"
#include "util.h"
TimelinePropertiesWidget::TimelinePropertiesWidget(Mlt::Service &service, QWidget *parent) :
QWidget(parent),
ui(new Ui::TimelinePropertiesWidget),
m_service(service)
{
ui->setupUi(this);
connect(ui->editButton, &QAbstractButton::clicked, this, &TimelinePropertiesWidget::editProfile);
Util::setColorsToHighlight(ui->nameLabel);
if (m_service.is_valid()) {
Mlt::Profile &profile = MLT.profile();
ui->resolutionLabel->setText(QStringLiteral("%1 x %2").arg(profile.width()).arg(profile.height()));
ui->aspectRatioLabel->setText(QStringLiteral("%1 : %2").arg(profile.display_aspect_num()).arg(
profile.display_aspect_den()));
ui->frameRateLabel->setText(tr("%L1 fps").arg(profile.fps(), 0, 'f', 6));
if (profile.progressive())
ui->scanModeLabel->setText(tr("Progressive"));
else
ui->scanModeLabel->setText(tr("Interlaced"));
if (profile.colorspace() == 601)
ui->colorspaceLabel->setText("ITU-R BT.601");
else if (profile.colorspace() == 709)
ui->colorspaceLabel->setText("ITU-R BT.709");
else
ui->colorspaceLabel->setText("");
}
}
TimelinePropertiesWidget::~TimelinePropertiesWidget()
{
delete ui;
}
| 2,133
|
C++
|
.cpp
| 50
| 37.08
| 107
| 0.685907
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,234
|
avfoundationproducerwidget.cpp
|
mltframework_shotcut/src/widgets/avfoundationproducerwidget.cpp
|
/*
* Copyright (c) 2015-2023 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "avfoundationproducerwidget.h"
#include "ui_avfoundationproducerwidget.h"
#include "mltcontroller.h"
#include "util.h"
#include "settings.h"
#include <QMediaDevices>
#include <QCameraDevice>
#include <QCamera>
#include <QString>
#include <QAudioDevice>
#include "shotcut_mlt_properties.h"
#include <Logger.h>
#define ENABLE_SCREEN_CAPTURE (0)
AvfoundationProducerWidget::AvfoundationProducerWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::AvfoundationProducerWidget)
{
ui->setupUi(this);
Util::setColorsToHighlight(ui->label);
#ifdef Q_OS_MAC
auto currentVideo = 1;
for (const auto &cameraInfo : QMediaDevices::videoInputs()) {
if (Settings.videoInput() == cameraInfo.description()) {
currentVideo = ui->videoCombo->count();
}
ui->videoCombo->addItem(cameraInfo.description(), cameraInfo.id());
}
#if ENABLE_SCREEN_CAPTURE
for (int i = 0; i < QGuiApplication::screens().size(); i++)
ui->videoCombo->addItem(QStringLiteral("Capture screen %1").arg(i));
#endif
auto currentAudio = 1;
for (const auto &deviceInfo : QMediaDevices::audioInputs()) {
if (Settings.audioInput() == deviceInfo.description()) {
currentAudio = ui->audioCombo->count();
}
ui->audioCombo->addItem(deviceInfo.description());
}
if (ui->videoCombo->count() > 1)
ui->videoCombo->setCurrentIndex(currentVideo);
if (ui->audioCombo->count() > 1) {
ui->audioCombo->setCurrentIndex(currentAudio);
}
#endif
}
AvfoundationProducerWidget::~AvfoundationProducerWidget()
{
delete ui;
}
Mlt::Producer *AvfoundationProducerWidget::newProducer(Mlt::Profile &profile)
{
QString resource;
qreal frameRate = 30.0;
QSize size {1280, 720};
Util::cameraFrameRateSize(ui->videoCombo->currentData().toByteArray(), frameRate, size);
if (ui->videoCombo->currentIndex()) {
resource = QStringLiteral("avfoundation:%1:%2?pixel_format=yuyv422&framerate=%3&video_size=%4x%5")
.arg(ui->videoCombo->currentText().replace(tr("None"), "none"))
.arg(ui->audioCombo->currentText().replace(tr("None"), "none"))
.arg(frameRate).arg(size.width()).arg(size.height());
} else {
resource = QStringLiteral("avfoundation:none:%1").arg(ui->audioCombo->currentText().replace(
tr("None"),
"none"));
}
LOG_DEBUG() << resource;
Mlt::Producer *p = new Mlt::Producer(profile, resource.toUtf8().constData());
if (!p || !p->is_valid()) {
delete p;
p = new Mlt::Producer(profile, "color:");
p->set("resource", QStringLiteral("avfoundation:%1:%2")
.arg(ui->videoCombo->currentText().replace(tr("None"), "none"))
.arg(ui->audioCombo->currentText())
.toUtf8().constData());
p->set("error", 1);
}
p->set("force_seekable", 0);
p->set(kBackgroundCaptureProperty, 1);
p->set(kShotcutCaptionProperty, tr("Audio/Video Device").toUtf8().constData());
if (ui->audioCombo->currentIndex() > 0) {
Settings.setAudioInput(ui->audioCombo->currentText());
}
if (ui->videoCombo->currentIndex() > 0) {
Settings.setVideoInput(ui->videoCombo->currentText());
}
return p;
}
void AvfoundationProducerWidget::setProducer(Mlt::Producer *producer)
{
QStringList resource = QString(producer->get("resource")).split('?');
resource = resource[0].split(':');
ui->videoCombo->setCurrentIndex(0);
ui->audioCombo->setCurrentIndex(0);
if (resource.size() > 2) {
for (int i = 1; i < ui->videoCombo->count(); i++) {
if (ui->videoCombo->itemText(i) == resource[1]) {
ui->videoCombo->setCurrentIndex(i);
break;
}
}
for (int i = 1; i < ui->audioCombo->count(); i++) {
if (ui->audioCombo->itemText(i) == resource[2]) {
ui->audioCombo->setCurrentIndex(i);
break;
}
}
}
AbstractProducerWidget::setProducer(producer);
}
void AvfoundationProducerWidget::on_videoCombo_activated(int index)
{
Q_UNUSED(index)
if (m_producer) {
MLT.close();
AbstractProducerWidget::setProducer(0);
emit producerChanged(0);
QCoreApplication::processEvents();
Mlt::Producer *p = newProducer(MLT.profile());
AbstractProducerWidget::setProducer(p);
MLT.setProducer(p);
MLT.play();
emit producerChanged(p);
}
}
void AvfoundationProducerWidget::on_audioCombo_activated(int index)
{
on_videoCombo_activated(index);
}
| 5,472
|
C++
|
.cpp
| 144
| 31.340278
| 106
| 0.640842
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,235
|
audiometerwidget.cpp
|
mltframework_shotcut/src/widgets/audiometerwidget.cpp
|
/*
* Copyright (c) 2015-2022 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "audiometerwidget.h"
#include "iecscale.h"
#include <QPainter>
#include <QColor>
#include <QtAlgorithms>
#include <QToolTip>
static const int TEXT_PAD = 2;
AudioMeterWidget::AudioMeterWidget(QWidget *parent): QWidget(parent)
{
const QFont &font = QWidget::font();
const int fontSize = font.pointSize() - (font.pointSize() > 10 ? 2 : (font.pointSize() > 8 ? 1 :
0));
QWidget::setFont(QFont(font.family(), fontSize));
QWidget::setMouseTracking(true);
}
void AudioMeterWidget::setDbLabels(const QVector<int> &labels)
{
m_dbLabels = labels;
if (m_dbLabels.size()) {
std::sort(m_dbLabels.begin(), m_dbLabels.end());
m_maxDb = m_dbLabels[m_dbLabels.size() - 1];
}
calcGraphRect();
}
void AudioMeterWidget::setChannelLabels(const QStringList &labels)
{
m_chanLabels = labels;
calcGraphRect();
}
void AudioMeterWidget::setChannelLabelUnits(const QString &units)
{
m_chanLabelUnits = units;
}
void AudioMeterWidget::setOrientation(Qt::Orientation orientation)
{
m_orient = orientation;
calcGraphRect();
}
void AudioMeterWidget::showAudio(const QVector<double> &dbLevels)
{
m_levels = dbLevels;
if (m_peaks.size() != m_levels.size()) {
m_peaks = m_levels;
calcGraphRect();
} else {
for (int i = 0; i < m_levels.size(); i++) {
m_peaks[i] = m_peaks[i] - 0.2;
if (m_levels[i] >= m_peaks[i]) {
m_peaks[i] = m_levels[i];
}
}
}
update();
updateToolTip();
}
void AudioMeterWidget::calcGraphRect()
{
int chanLabelCount = m_chanLabels.size();
int dbLabelCount = m_dbLabels.size();
int textHeight = fontMetrics().height() + TEXT_PAD;
int chanCount = m_levels.size() ? m_levels.size() : chanLabelCount ? chanLabelCount : 2;
if (m_orient == Qt::Horizontal) {
int dbLabelHeight = dbLabelCount ? textHeight : 0;
// Find the widest channel label
int chanLabelWidth = 0;
for (int i = 0; i < chanLabelCount; i++) {
int width = fontMetrics().horizontalAdvance(m_chanLabels[i]) + TEXT_PAD;
chanLabelWidth = width > chanLabelWidth ? width : chanLabelWidth;
}
int chanHeight = (height() - dbLabelHeight) / chanCount;
m_graphRect.setTop(0);
m_graphRect.setRight(width());
m_graphRect.setBottom(chanHeight * chanCount);
m_graphRect.setLeft(chanLabelWidth);
m_barSize.setWidth(m_graphRect.width());
m_barSize.setHeight(chanHeight);
m_gradient.setStart(m_graphRect.left(), 0);
m_gradient.setFinalStop(m_graphRect.right(), 0);
} else { // Vertical
int chanLabelHeight = chanLabelCount ? textHeight : 0;
// Find the widest db label
int dbLabelWidth = 0;
for (int i = 0; i < dbLabelCount; i++) {
QString label = QString::asprintf("%d", m_dbLabels[i]);
int size = fontMetrics().horizontalAdvance(label) + TEXT_PAD;
dbLabelWidth = size > dbLabelWidth ? size : dbLabelWidth;
}
int chanWidth = (width() - dbLabelWidth) / chanCount;
m_graphRect.setTop(0);
m_graphRect.setRight(dbLabelWidth + chanWidth * chanCount);
m_graphRect.setBottom(height() - chanLabelHeight);
m_graphRect.setLeft(dbLabelWidth);
m_barSize.setWidth(chanWidth);
m_barSize.setHeight(m_graphRect.height());
m_gradient.setStart(0, m_graphRect.bottom());
m_gradient.setFinalStop(0, m_graphRect.top());
}
m_gradient.setColorAt(IEC_ScaleMax(-90.0, m_maxDb), Qt::darkGreen);
m_gradient.setColorAt(IEC_ScaleMax(-12.0, m_maxDb), Qt::green);
m_gradient.setColorAt(IEC_ScaleMax(-6.0, m_maxDb), Qt::yellow);
m_gradient.setColorAt(IEC_ScaleMax(0.0, m_maxDb), Qt::red);
if (m_maxDb > 0.0 ) {
m_gradient.setColorAt(IEC_ScaleMax(m_maxDb, m_maxDb), Qt::darkRed);
}
}
void AudioMeterWidget::drawDbLabels(QPainter &p)
{
int dbLabelCount = m_dbLabels.size();
int textHeight = fontMetrics().height();
int x = 0;
int y = 0;
if (dbLabelCount == 0) return;
p.setPen(palette().text().color().rgb());
if (m_orient == Qt::Horizontal) {
// dB scale is horizontal along the bottom
int prevX = 0;
y = m_graphRect.bottom() + textHeight + TEXT_PAD;
for (int i = 0; i < dbLabelCount; i++) {
int value = m_dbLabels[i];
QString label = QString::asprintf("%d", value);
int labelWidth = fontMetrics().horizontalAdvance(label);
x = m_graphRect.left() + IEC_ScaleMax(value, m_maxDb) * m_graphRect.width() - labelWidth / 2;
if (x + labelWidth > width()) {
x = width() - labelWidth;
}
if (x - prevX >= TEXT_PAD) {
p.drawText(x, y, label);
prevX = x + labelWidth;
}
}
} else {
// dB scale is vertical along the left side
int prevY = height();
for (int i = 0; i < dbLabelCount; i++) {
int value = m_dbLabels[i];
QString label = QString::asprintf("%d", value);
x = m_graphRect.left() - fontMetrics().horizontalAdvance(label) - TEXT_PAD;
y = m_graphRect.bottom() - qRound(IEC_ScaleMax(value,
m_maxDb) * (double)m_graphRect.height() - (double)textHeight / 2.0);
if (y - textHeight < 0) {
y = textHeight;
}
if (prevY - y >= TEXT_PAD) {
p.drawText(x, y, label);
prevY = y - textHeight;
}
}
}
}
void AudioMeterWidget::drawChanLabels(QPainter &p)
{
int chanLabelCount = m_chanLabels.size();
int textHeight = fontMetrics().height();
int stride = 1;
int x = 0;
int y = 0;
if (chanLabelCount == 0) return;
p.setPen(palette().text().color().rgb());
if (m_orient == Qt::Horizontal) {
// Channel labels are vertical along the left side.
while ( textHeight * chanLabelCount / stride > m_graphRect.width() ) {
stride++;
}
int prevY = m_graphRect.top();
for (int i = 0; i < chanLabelCount; i += stride) {
const QString &label = m_chanLabels[i];
y = m_graphRect.bottom() - (chanLabelCount - 1 - i) * m_barSize.height() - m_barSize.height() / 2 +
textHeight / 2;
x = m_graphRect.left() - fontMetrics().horizontalAdvance(label) - TEXT_PAD;
if ( y - prevY >= TEXT_PAD) {
p.drawText(x, y, label);
prevY = y - textHeight;
}
}
} else {
// Channel labels are horizontal along the bottom.
// Find the widest channel label
int chanLabelWidth = 0;
for (int i = 0; i < chanLabelCount; i++) {
int width = fontMetrics().horizontalAdvance(m_chanLabels[i]) + TEXT_PAD;
chanLabelWidth = width > chanLabelWidth ? width : chanLabelWidth;
}
while ( chanLabelWidth * chanLabelCount / stride > m_graphRect.width() ) {
stride++;
}
int prevX = 0;
y = m_graphRect.bottom() + textHeight + TEXT_PAD;
for (int i = 0; i < chanLabelCount; i += stride) {
QString label = m_chanLabels[i];
x = m_graphRect.left() + i * m_barSize.width() + m_barSize.width() / 2 -
fontMetrics().horizontalAdvance(label) / 2;
if (x > prevX) {
p.drawText(x, y, label);
prevX = x + fontMetrics().horizontalAdvance(label);
}
}
}
}
void AudioMeterWidget::drawBars(QPainter &p)
{
int chanCount = m_levels.size();
QRectF bar;
if (m_orient == Qt::Horizontal) {
for (int i = 0; i < chanCount; i++) {
double level = IEC_ScaleMax(m_levels[i], m_maxDb);
bar.setLeft(m_graphRect.left());
bar.setRight(bar.left() + m_barSize.width() * level);
bar.setBottom(m_graphRect.bottom() - (chanCount - 1 - i) * m_barSize.height() - 1);
bar.setTop(bar.bottom() - m_barSize.height() + 1);
p.drawRoundedRect(bar, 3, 3);
}
} else {
for (int i = 0; i < chanCount; i++) {
double level = IEC_ScaleMax(m_levels[i], m_maxDb);
bar.setLeft(m_graphRect.left() + i * m_barSize.width() + 1);
bar.setRight(bar.left() + m_barSize.width() - 1);
bar.setBottom(m_graphRect.bottom());
bar.setTop(bar.bottom() - qRound((double)m_barSize.height() * level));
p.drawRoundedRect(bar, 3, 3);
}
}
}
void AudioMeterWidget::drawPeaks(QPainter &p)
{
int chanCount = m_peaks.size();
QRectF bar;
if (m_orient == Qt::Horizontal) {
for (int i = 0; i < chanCount; i++) {
if (m_peaks[i] == m_levels[i])
continue;
double level = IEC_ScaleMax(m_peaks[i], m_maxDb);
bar.setLeft(m_graphRect.left() + m_barSize.width() * level - 3);
if (bar.left() < m_graphRect.left())
continue;
bar.setRight(bar.left() + 3);
bar.setBottom(m_graphRect.bottom() - (chanCount - 1 - i) * m_barSize.height() - 1);
bar.setTop(bar.bottom() - m_barSize.height() + 1);
p.drawRoundedRect(bar, 3, 3);
}
} else {
for (int i = 0; i < chanCount; i++) {
if (m_peaks[i] == m_levels[i])
continue;
double level = IEC_ScaleMax(m_peaks[i], m_maxDb);
bar.setLeft(m_graphRect.left() + i * m_barSize.width() + 1);
bar.setRight(bar.left() + m_barSize.width() - 2);
bar.setBottom(m_graphRect.bottom() - m_barSize.height() * level + 3);
if (bar.bottom() > m_graphRect.bottom())
continue;
bar.setTop(bar.bottom() - 3);
p.drawRoundedRect(bar, 3, 3);
}
}
}
void AudioMeterWidget::updateToolTip()
{
QString text = "";
int chan = -1;
QPoint mousePos = mapFromGlobal(QCursor::pos());
if (this->rect().contains(mousePos)) {
if (m_orient == Qt::Horizontal) {
if (mousePos.y() <= m_graphRect.bottom() && mousePos.y() >= m_graphRect.top()) {
chan = (int)(m_graphRect.bottom() - mousePos.y()) / (int)m_barSize.height();
chan = m_levels.size() - 1 - chan;
}
} else {
if (mousePos.x() >= m_graphRect.left() && mousePos.x() <= m_graphRect.right()) {
chan = (int)(mousePos.x() - m_graphRect.left()) / (int)m_barSize.width();
}
}
}
if (chan >= 0 && m_levels.size() > chan) {
if (m_levels[chan] < -90) {
text = "-inf dB";
} else {
text = QStringLiteral("%1dBFS").arg(m_levels[chan], 0, 'f', 1);
}
if (m_chanLabels.size() > chan) {
if (!m_chanLabelUnits.isEmpty()) {
text = QStringLiteral("%1%2: %3").arg(m_chanLabels[chan], m_chanLabelUnits, text);
} else {
text = QStringLiteral("%1: %2").arg(m_chanLabels[chan], text);
}
}
}
QToolTip::showText(QCursor::pos(), text);
}
void AudioMeterWidget::paintEvent(QPaintEvent * /*e*/)
{
if (!isVisible())
return;
QPainter p(this);
p.setRenderHints( QPainter::Antialiasing );
drawDbLabels(p);
drawChanLabels(p);
p.setBrush(m_gradient);
QPen pen(Qt::transparent, 1);
p.setPen(pen);
drawBars(p);
drawPeaks(p);
p.end();
}
void AudioMeterWidget::resizeEvent(QResizeEvent *)
{
calcGraphRect();
}
void AudioMeterWidget::mouseMoveEvent(QMouseEvent *)
{
updateToolTip();
}
| 12,575
|
C++
|
.cpp
| 326
| 30.266871
| 127
| 0.573851
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,236
|
timespinbox.cpp
|
mltframework_shotcut/src/widgets/timespinbox.cpp
|
/*
* Copyright (c) 2012-2024 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "timespinbox.h"
#include "mltcontroller.h"
#include "settings.h"
#include <QRegularExpressionValidator>
#include <QKeyEvent>
#include <QFontDatabase>
#include <QGuiApplication>
TimeSpinBox::TimeSpinBox(QWidget *parent)
: QSpinBox(parent)
{
setLineEdit(new TimeSpinBoxLineEdit);
setRange(0, INT_MAX);
setAlignment(Qt::AlignRight);
m_validator = new QRegularExpressionValidator(
QRegularExpression("^\\s*(\\d*:){0,2}(\\d*[.;:])?\\d*\\s*$"), this);
setValue(0);
QFont font = QFontDatabase::systemFont(QFontDatabase::FixedFont);
font.setPointSize(QGuiApplication::font().pointSize());
setFont(font);
setFixedWidth(fontMetrics().boundingRect("_HHH:MM:SS;FFF_").width());
connect(&Settings, &ShotcutSettings::timeFormatChanged, this, [&]() {
setValue(value());
});
}
QValidator::State TimeSpinBox::validate(QString &input, int &pos) const
{
return m_validator->validate(input, pos);
}
int TimeSpinBox::valueFromText(const QString &text) const
{
if (MLT.producer() && MLT.producer()->is_valid()) {
return MLT.producer()->time_to_frames(text.toLatin1().constData());
} else {
return Mlt::Producer(MLT.profile(), "color", "").time_to_frames(text.toLatin1().constData());
}
return 0;
}
QString TimeSpinBox::textFromValue(int val) const
{
if (MLT.producer() && MLT.producer()->is_valid()) {
return MLT.producer()->frames_to_time(val, Settings.timeFormat());
} else {
return Mlt::Producer(MLT.profile(), "color", "").frames_to_time(val, Settings.timeFormat());
}
return QString();
}
void TimeSpinBox::keyPressEvent(QKeyEvent *event)
{
if (event->key() == Qt::Key_PageUp || event->key() == Qt::Key_PageDown) {
// Disable page up & page down (step by 10) since those keys are used for other things in Shotcut.
event->ignore();
return;
}
QSpinBox::keyPressEvent(event);
if (event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return) {
event->accept();
emit accepted();
}
}
TimeSpinBoxLineEdit::TimeSpinBoxLineEdit(QWidget *parent)
: QLineEdit(parent)
, m_selectOnMousePress(false)
{
}
void TimeSpinBoxLineEdit::focusInEvent(QFocusEvent *event)
{
QLineEdit::focusInEvent(event);
selectAll();
m_selectOnMousePress = true;
}
void TimeSpinBoxLineEdit::focusOutEvent(QFocusEvent *event)
{
// QLineEdit::focusOutEvent() calls deselect() on OtherFocusReason,
// which prevents using the clipboard actions with the text.
if (event->reason() != Qt::OtherFocusReason)
QLineEdit::focusOutEvent(event);
}
void TimeSpinBoxLineEdit::mousePressEvent(QMouseEvent *event)
{
QLineEdit::mousePressEvent(event);
if (m_selectOnMousePress) {
selectAll();
m_selectOnMousePress = false;
}
}
| 3,538
|
C++
|
.cpp
| 101
| 31.178218
| 106
| 0.699474
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,237
|
networkproducerwidget.cpp
|
mltframework_shotcut/src/widgets/networkproducerwidget.cpp
|
/*
* Copyright (c) 2012-2018 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "networkproducerwidget.h"
#include "ui_networkproducerwidget.h"
#include "mltcontroller.h"
#include "util.h"
NetworkProducerWidget::NetworkProducerWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::NetworkProducerWidget)
{
ui->setupUi(this);
Util::setColorsToHighlight(ui->label_2);
ui->applyButton->hide();
ui->preset->saveDefaultPreset(getPreset());
ui->preset->loadPresets();
}
NetworkProducerWidget::~NetworkProducerWidget()
{
delete ui;
}
Mlt::Producer *NetworkProducerWidget::newProducer(Mlt::Profile &profile)
{
Mlt::Producer *p = new Mlt::Producer(profile, ui->urlLineEdit->text().toUtf8().constData());
return p;
}
Mlt::Properties NetworkProducerWidget::getPreset() const
{
Mlt::Properties p;
p.set("resource", ui->urlLineEdit->text().toUtf8().constData());
return p;
}
void NetworkProducerWidget::loadPreset(Mlt::Properties &p)
{
const char *resource = p.get("resource");
if (qstrcmp(resource, "<tractor>") && qstrcmp(resource, "<playlist>"))
ui->urlLineEdit->setText(resource);
}
void NetworkProducerWidget::on_preset_selected(void *p)
{
Mlt::Properties *properties = (Mlt::Properties *) p;
loadPreset(*properties);
delete properties;
}
void NetworkProducerWidget::on_preset_saveClicked()
{
ui->preset->savePreset(getPreset());
}
void NetworkProducerWidget::setProducer(Mlt::Producer *producer)
{
ui->applyButton->show();
if (producer)
loadPreset(*producer);
}
void NetworkProducerWidget::on_applyButton_clicked()
{
MLT.setProducer(newProducer(MLT.profile()));
MLT.play();
}
| 2,314
|
C++
|
.cpp
| 72
| 29.291667
| 96
| 0.737007
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
13,238
|
screenselector.cpp
|
mltframework_shotcut/src/widgets/screenselector.cpp
|
/*
* Copyright (c) 2014-2022 Meltytech, LLC
* Inspiration: KDENLIVE colorpickerwidget.cpp by Till Theato (root@ttill.de)
* Inspiration: QColorDialog.cpp
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "screenselector.h"
#include "mainwindow.h"
#include <QApplication>
#include <QMouseEvent>
ScreenSelector::ScreenSelector(QWidget *parent)
: QFrame(parent)
, m_selectionInProgress(false)
, m_selectionRect(-1, -1, -1, -1)
, m_selectionPoint(-1, -1)
, m_fixedSize(-1, -1)
, m_boundingRect(-1, -1, -1, -1)
{
setFrameStyle(QFrame::Box | QFrame::Plain);
setWindowOpacity(0.5);
setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint | Qt::Tool);
hide();
setCursor(Qt::CrossCursor);
}
void ScreenSelector::setFixedSize(const QSize &size)
{
m_fixedSize = size;
}
void ScreenSelector::setBoundingRect(const QRect &rect)
{
m_boundingRect = rect;
}
void ScreenSelector::setSelectedRect(const QRect &rect)
{
m_selectionRect = rect;
lockGeometry(m_selectionRect.normalized());
}
void ScreenSelector::startSelection(QPoint initialPos)
{
m_selectionInProgress = false;
grabMouse();
grabKeyboard();
MAIN.setCursor(Qt::CrossCursor);
if (initialPos.x() > -1) {
m_selectionPoint = initialPos;
} else {
m_selectionPoint = QCursor::pos();
}
QCursor::setPos(m_selectionPoint);
if (m_fixedSize.width() > -1) {
m_selectionRect.setSize(m_fixedSize);
m_selectionInProgress = true;
}
if (m_selectionInProgress) {
lockGeometry(m_selectionRect.normalized());
show();
}
QApplication::instance()->installEventFilter(this);
}
bool ScreenSelector::eventFilter(QObject *, QEvent *event)
{
switch (event->type()) {
case QEvent::MouseButtonPress:
return onMousePressEvent(static_cast<QMouseEvent *>(event));
case QEvent::MouseMove:
return onMouseMoveEvent(static_cast<QMouseEvent *>(event));
case QEvent::MouseButtonRelease:
return onMouseReleaseEvent(static_cast<QMouseEvent *>(event));
case QEvent::KeyPress:
return onKeyPressEvent(static_cast<QKeyEvent *>(event));
default:
break;
}
return false;
}
bool ScreenSelector::onMousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton && !m_selectionInProgress) {
m_selectionInProgress = true;
show();
m_selectionRect = QRect(event->globalPosition().toPoint(), QSize(1, 1));
lockGeometry(m_selectionRect.normalized());
}
return true;
}
bool ScreenSelector::onMouseMoveEvent(QMouseEvent *event)
{
if (m_boundingRect.x() > -1 &&
!m_boundingRect.contains(event->globalPosition().toPoint())) {
int x = qBound(m_boundingRect.left(), qRound(event->globalPosition().x()), m_boundingRect.right());
int y = qBound(m_boundingRect.top(), qRound(event->globalPosition().y()), m_boundingRect.bottom());
QCursor::setPos(x, y);
return true;
}
if (m_selectionInProgress) {
if (m_fixedSize.width() > -1) {
// Center the selection around the cursor
int x = qRound(event->globalPosition().x()) - m_fixedSize.width() / 2;
int y = qRound(event->globalPosition().y()) - m_fixedSize.height() / 2;
if (m_boundingRect.x() > -1) {
x = qBound(m_boundingRect.left(), x, m_boundingRect.right() - m_fixedSize.width());
y = qBound(m_boundingRect.top(), y, m_boundingRect.bottom() - m_fixedSize.height());
}
m_selectionRect = QRect(QPoint(x, y), m_fixedSize);
m_selectionPoint = event->globalPosition().toPoint();
emit screenSelected(m_selectionRect);
emit pointSelected(m_selectionPoint);
} else {
m_selectionRect.setWidth(qRound(event->globalPosition().x()) - m_selectionRect.x());
m_selectionRect.setHeight(qRound(event->globalPosition().y()) - m_selectionRect.y());
if (m_selectionRect.width() == 0) {
m_selectionRect.setWidth(1);
}
if (m_selectionRect.height() == 0) {
m_selectionRect.setHeight(1);
}
}
lockGeometry(m_selectionRect.normalized());
}
return true;
}
bool ScreenSelector::onMouseReleaseEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton && m_selectionInProgress == true ) {
release();
emit screenSelected(m_selectionRect);
}
return true;
}
bool ScreenSelector::onKeyPressEvent(QKeyEvent *event)
{
if (event->key() == Qt::Key_Escape) {
release();
emit cancelled();
}
event->accept();
return true;
}
void ScreenSelector::lockGeometry(const QRect &rect)
{
setGeometry(rect);
setMinimumSize(rect.size());
setMaximumSize(rect.size());
}
void ScreenSelector::release()
{
QApplication::instance()->removeEventFilter(this);
releaseMouse();
releaseKeyboard();
MAIN.setCursor(Qt::ArrowCursor);
m_selectionInProgress = false;
hide();
}
| 5,718
|
C++
|
.cpp
| 165
| 29.109091
| 107
| 0.663955
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,239
|
editmarkerwidget.cpp
|
mltframework_shotcut/src/widgets/editmarkerwidget.cpp
|
/*
* Copyright (c) 2021-2024 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "editmarkerwidget.h"
#include "mltcontroller.h"
#include "qmltypes/qmlapplication.h"
#include "widgets/timespinbox.h"
#include "util.h"
#include "settings.h"
#include <QColorDialog>
#include <QDebug>
#include <QGridLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QSignalBlocker>
EditMarkerWidget::EditMarkerWidget(QWidget *parent, const QString &text, const QColor &color,
int start, int end, int maxEnd)
: QWidget(parent)
{
QGridLayout *grid = new QGridLayout();
setLayout(grid);
grid->setColumnMinimumWidth(0, 125);
grid->setColumnMinimumWidth(1, 125);
m_textField = new QLineEdit(text);
connect(m_textField, SIGNAL(editingFinished()), SIGNAL(valuesChanged()));
m_textField->setToolTip(tr("Set the name for this marker."));
grid->addWidget(m_textField, 0, 0, 1, 2);
m_colorButton = new QPushButton(tr("Color..."));
connect(m_colorButton, SIGNAL(clicked()), SLOT(on_colorButton_clicked()));
grid->addWidget(m_colorButton, 1, 0, Qt::AlignRight);
m_colorLabel = new QLabel(color.name(QColor::HexRgb));
m_colorLabel->setStyleSheet(QStringLiteral("color: %1; background-color: %2")
.arg(Util::textColor(color), color.name()));
grid->addWidget(m_colorLabel, 1, 1);
grid->addWidget(new QLabel(tr("Start")), 2, 0, Qt::AlignRight);
m_startSpinner = new TimeSpinBox();
m_startSpinner->setMinimum(0);
m_startSpinner->setMaximum(end);
m_startSpinner->setValue(start);
m_startSpinner->setToolTip(tr("Set the start time for this marker."));
connect(m_startSpinner, SIGNAL(valueChanged(int)), this, SLOT(on_startSpinner_valueChanged(int)));
grid->addWidget(m_startSpinner, 2, 1);
grid->addWidget(new QLabel(tr("End")), 3, 0, Qt::AlignRight);
m_endSpinner = new TimeSpinBox();
m_endSpinner->setMinimum(start);
m_endSpinner->setMaximum(maxEnd);
m_endSpinner->setValue(end);
m_endSpinner->setToolTip(tr("Set the end time for this marker."));
connect(m_endSpinner, SIGNAL(valueChanged(int)), this, SLOT(on_endSpinner_valueChanged(int)));
grid->addWidget(m_endSpinner, 3, 1);
grid->addWidget(new QLabel(tr("Duration:")), 4, 0, Qt::AlignRight);
m_durationLabel = new QLabel();
updateDuration();
grid->addWidget(m_durationLabel, 4, 1);
}
EditMarkerWidget::~EditMarkerWidget()
{
}
QString EditMarkerWidget::getText()
{
return m_textField->text();
}
QColor EditMarkerWidget::getColor()
{
return QColor(m_colorLabel->text());
}
int EditMarkerWidget::getStart()
{
return m_startSpinner->value();
}
int EditMarkerWidget::getEnd()
{
return m_endSpinner->value();
}
void EditMarkerWidget::setValues(const QString &text, const QColor &color, int start, int end,
int maxEnd)
{
QSignalBlocker textBlocker(m_textField);
QSignalBlocker colorBlocker(m_colorLabel);
QSignalBlocker startBlocker(m_startSpinner);
QSignalBlocker endBlocker(m_endSpinner);
m_textField->setText(text);
m_colorLabel->setText(color.name(QColor::HexRgb));
m_colorLabel->setStyleSheet(QStringLiteral("color: %1; background-color: %2")
.arg(Util::textColor(color), color.name()));
m_startSpinner->setMinimum(0);
m_startSpinner->setMaximum(end);
m_startSpinner->setValue(start);
m_endSpinner->setMinimum(start);
m_endSpinner->setMaximum(maxEnd);
m_endSpinner->setValue(end);
updateDuration();
emit valuesChanged();
}
void EditMarkerWidget::on_colorButton_clicked()
{
QColor color = QColor(m_colorLabel->text());
QColorDialog dialog(color);
#if defined(Q_OS_UNIX) && !defined(Q_OS_MAC)
dialog.setOptions(QColorDialog::DontUseNativeDialog);
#endif
dialog.setModal(QmlApplication::dialogModality());
if (dialog.exec() == QDialog::Accepted) {
auto newColor = dialog.currentColor();
m_colorLabel->setText(newColor.name(QColor::HexRgb));
m_colorLabel->setStyleSheet(QStringLiteral("color: %1; background-color: %2")
.arg(Util::textColor(newColor), newColor.name()));
}
emit valuesChanged();
}
void EditMarkerWidget::on_startSpinner_valueChanged(int value)
{
m_endSpinner->setMinimum(value);
updateDuration();
emit valuesChanged();
}
void EditMarkerWidget::on_endSpinner_valueChanged(int value)
{
m_startSpinner->setMaximum(value);
updateDuration();
emit valuesChanged();
}
void EditMarkerWidget::updateDuration()
{
if (MLT.producer()) {
int duration = m_endSpinner->value() - m_startSpinner->value() + 1;
m_durationLabel->setText(MLT.producer()->frames_to_time(duration, Settings.timeFormat()));
} else {
m_durationLabel->setText("--:--:--:--");
}
}
| 5,559
|
C++
|
.cpp
| 146
| 33.445205
| 102
| 0.700779
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,240
|
trackpropertieswidget.cpp
|
mltframework_shotcut/src/widgets/trackpropertieswidget.cpp
|
/*
* Copyright (c) 2015-2019 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "trackpropertieswidget.h"
#include "ui_trackpropertieswidget.h"
#include "shotcut_mlt_properties.h"
#include "commands/timelinecommands.h"
#include "mainwindow.h"
#include "util.h"
#include <Mlt.h>
#include <QScopedPointer>
static const char *BLEND_PROPERTY_CAIROBLEND = "1";
TrackPropertiesWidget::TrackPropertiesWidget(Mlt::Producer &track, QWidget *parent) :
QWidget(parent),
ui(new Ui::TrackPropertiesWidget),
m_track(track)
{
ui->setupUi(this);
Util::setColorsToHighlight(ui->nameLabel);
ui->nameLabel->setText(tr("Track: %1").arg(track.get(kTrackNameProperty)));
ui->blendModeLabel->hide();
ui->blendModeCombo->hide();
QScopedPointer<Mlt::Transition> transition(getTransition("frei0r.cairoblend"));
if (transition && transition->is_valid()) {
ui->blendModeCombo->blockSignals(true);
ui->blendModeCombo->addItem(tr("None"), "");
ui->blendModeCombo->addItem(tr("Over"), "normal");
ui->blendModeCombo->addItem(tr("Add"), "add");
ui->blendModeCombo->addItem(tr("Saturate"), "saturate");
ui->blendModeCombo->addItem(tr("Multiply"), "multiply");
ui->blendModeCombo->addItem(tr("Screen"), "screen");
ui->blendModeCombo->addItem(tr("Overlay"), "overlay");
ui->blendModeCombo->addItem(tr("Darken"), "darken");
ui->blendModeCombo->addItem(tr("Dodge"), "colordodge");
ui->blendModeCombo->addItem(tr("Burn"), "colorburn");
ui->blendModeCombo->addItem(tr("Hard Light"), "hardlight");
ui->blendModeCombo->addItem(tr("Soft Light"), "softlight");
ui->blendModeCombo->addItem(tr("Difference"), "difference");
ui->blendModeCombo->addItem(tr("Exclusion"), "exclusion");
ui->blendModeCombo->addItem(tr("HSL Hue"), "hslhue");
ui->blendModeCombo->addItem(tr("HSL Saturation"), "hslsaturatation");
ui->blendModeCombo->addItem(tr("HSL Color"), "hslcolor");
ui->blendModeCombo->addItem(tr("HSL Luminosity"), "hslluminocity");
ui->blendModeCombo->blockSignals(false);
ui->blendModeLabel->show();
ui->blendModeCombo->show();
QString blendMode = transition->get(BLEND_PROPERTY_CAIROBLEND);
if (transition->get_int("disable"))
blendMode = QString();
else if (blendMode.isEmpty()) // A newly added track does not set its mode property.
blendMode = "normal";
onModeChanged(blendMode);
} else {
transition.reset(getTransition("movit.overlay"));
if (transition && transition->is_valid()) {
ui->blendModeCombo->blockSignals(true);
ui->blendModeCombo->addItem(tr("None"), "");
ui->blendModeCombo->addItem(tr("Over"), "over");
ui->blendModeCombo->blockSignals(false);
ui->blendModeLabel->show();
ui->blendModeCombo->show();
QString blendMode = transition->get_int("disable") ? QString() : "over";
onModeChanged(blendMode);
}
}
}
TrackPropertiesWidget::~TrackPropertiesWidget()
{
delete ui;
}
Mlt::Transition *TrackPropertiesWidget::getTransition(const QString &name)
{
// track.consumer() is the multitrack
QScopedPointer<Mlt::Service> service(m_track.consumer());
if (service && service->is_valid()) {
Mlt::Multitrack multi(*service);
int trackIndex;
// Get the track index by iterating until multitrack.track() == track.get_producer().
for (trackIndex = 0; trackIndex < multi.count(); ++trackIndex) {
QScopedPointer<Mlt::Producer> producer(multi.track(trackIndex));
if (producer->get_producer() == m_track.get_producer())
break;
}
// Iterate the consumers until found transition by mlt_service and track_b index.
while (service && service->is_valid() && mlt_service_tractor_type != service->type()) {
if (service->type() == mlt_service_transition_type) {
Mlt::Transition t((mlt_transition) service->get_service());
if (name == t.get("mlt_service") && t.get_b_track() == trackIndex)
return new Mlt::Transition(t);
}
service.reset(service->consumer());
};
}
return 0;
}
void TrackPropertiesWidget::on_blendModeCombo_currentIndexChanged(int index)
{
if (index >= 0) {
QScopedPointer<Mlt::Transition> transition(getTransition("frei0r.cairoblend"));
if (!transition)
transition.reset(getTransition("movit.overlay"));
if (transition && transition->is_valid()) {
Timeline::ChangeBlendModeCommand *command = new Timeline::ChangeBlendModeCommand(
*transition, BLEND_PROPERTY_CAIROBLEND, ui->blendModeCombo->itemData(index).toString());
connect(command, SIGNAL(modeChanged(QString &)), SLOT(onModeChanged(QString &)));
MAIN.undoStack()->push(command);
}
}
}
void TrackPropertiesWidget::onModeChanged(QString &mode)
{
for (int i = 0; i < ui->blendModeCombo->count(); ++i) {
if (ui->blendModeCombo->itemData(i).toString() == mode) {
ui->blendModeCombo->blockSignals(true);
ui->blendModeCombo->setCurrentIndex(i);
ui->blendModeCombo->blockSignals(false);
break;
}
}
}
| 6,037
|
C++
|
.cpp
| 133
| 38.240602
| 104
| 0.653827
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
13,241
|
producerpreviewwidget.cpp
|
mltframework_shotcut/src/widgets/producerpreviewwidget.cpp
|
/*
* Copyright (c) 2020-2023 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "widgets/producerpreviewwidget.h"
#include <Logger.h>
#include "scrubbar.h"
#include "mltcontroller.h"
#include "settings.h"
#include <QtConcurrent/QtConcurrent>
#include <QHBoxLayout>
#include <QImage>
#include <QLabel>
#include <QProgressBar>
#include <QVBoxLayout>
ProducerPreviewWidget::ProducerPreviewWidget(double dar, int width)
: QWidget()
, m_previewSize(width, width)
, m_seekTo(-1)
, m_timerId(0)
, m_queue(10, DataQueue<QueueItem>::OverflowModeWait)
, m_generateFrames(false)
, m_isLooping(true)
{
LOG_DEBUG() << "begin";
int height = lrint((double)width / dar);
height -= height % 2;
if (height > width) {
height = width;
width = lrint(height * dar);
width -= width % 2;
m_previewSize.setWidth(width);
}
m_previewSize.setHeight(height);
QVBoxLayout *layout = new QVBoxLayout();
layout->setContentsMargins(0, 0, 0, 0);
layout->setSpacing(0);
setLayout(layout);
m_imageLabel = new QLabel();
m_imageLabel->setFixedSize(m_previewSize);
m_imageLabel->setAlignment(Qt::AlignCenter);
layout->addWidget(m_imageLabel);
m_scrubber = new ScrubBar(this);
m_scrubber->setFocusPolicy(Qt::NoFocus);
m_scrubber->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred);
m_scrubber->setMinimumWidth(m_previewSize.width());
m_scrubber->setMargin(0);
connect(m_scrubber, SIGNAL(seeked(int)), this, SLOT(seeked(int)));
layout->addWidget(m_scrubber);
m_posLabel = new QLabel();
m_posLabel->setAlignment(Qt::AlignCenter);
layout->addWidget(m_posLabel);
connect(m_posLabel, SIGNAL(linkActivated(QString)), this, SLOT(restart()));
LOG_DEBUG() << "end";
}
ProducerPreviewWidget::~ProducerPreviewWidget()
{
stop();
}
void ProducerPreviewWidget::start(const Mlt::Producer &producer)
{
if (Settings.playerGPU())
return;
m_producer = producer;
if (m_producer.is_valid()) {
// Set up the preview display and timer
m_scrubber->setFramerate(MLT.profile().fps());
m_scrubber->setScale(m_producer.get_length());
// Display preview at half frame rate.
int milliseconds = 2 * 1000.0 / MLT.profile().fps();
m_timerId = startTimer(milliseconds);
// Set up the producer frame generator
m_seekTo = 0;
m_generateFrames = true;
m_future = QtConcurrent::run(&ProducerPreviewWidget::frameGeneratorThread, this);
}
}
void ProducerPreviewWidget::ProducerPreviewWidget::stop(bool releaseProducer)
{
if ( m_timerId ) {
killTimer(m_timerId);
m_timerId = 0;
}
m_generateFrames = false;
while ( m_queue.count() > 0 ) {
m_queue.pop();
}
m_future.waitForFinished();
if (releaseProducer) {
m_producer = Mlt::Producer();
m_scrubber->setScale(0);
}
while ( m_queue.count() > 0 ) {
m_queue.pop();
}
m_seekTo = 0;
m_scrubber->onSeek(0);
m_posLabel->setText("");
}
void ProducerPreviewWidget::showText(QString text)
{
m_imageLabel->setText(text);
}
void ProducerPreviewWidget::setLooping(bool enabled)
{
m_isLooping = enabled;
}
void ProducerPreviewWidget::restart()
{
stop(false);
start(m_producer);
}
void ProducerPreviewWidget::seeked(int position)
{
m_seekTo = position;
if (!m_generateFrames && m_producer.is_valid()) {
generateFrame();
QueueItem item;
while (m_queue.count()) {
item = m_queue.pop();
}
m_imageLabel->setPixmap(item.pixmap);
m_scrubber->onSeek(item.position);
}
}
void ProducerPreviewWidget::timerEvent(QTimerEvent *)
{
if ( m_queue.count() > 0 ) {
QueueItem item = m_queue.pop();
m_imageLabel->setPixmap(item.pixmap);
m_scrubber->onSeek(item.position);
m_posLabel->setText(item.positionText);
} else if (!m_generateFrames && m_timerId) {
stop(false);
m_posLabel->setText(QStringLiteral("<p><b><a href=\"restart\">%1</a></b></p>").arg(tr("Play")));
}
}
void ProducerPreviewWidget::frameGeneratorThread()
{
while (m_generateFrames && m_producer.is_valid()) {
generateFrame();
}
}
void ProducerPreviewWidget::generateFrame()
{
// Check for seek
if (m_seekTo != -1) {
m_producer.seek(m_seekTo);
m_seekTo = -1;
while ( m_queue.count() > 1 ) {
m_queue.pop();
}
}
// Get the image
int position = m_producer.position();
int length = m_producer.get_length();
int width = m_previewSize.width();
int height = m_previewSize.height();
mlt_image_format format = mlt_image_rgb;
std::unique_ptr<Mlt::Frame> frame(m_producer.get_frame());
frame->set( "rescale.interp", "bilinear" );
uint8_t *mltImage = frame->get_image( format, width, height, 0 );
QImage image( mltImage, width, height, QImage::Format_RGB888 );
// Send the image and status in the queue
QueueItem item;
item.pixmap.convertFromImage(image);
item.position = position;
item.positionText = QString::fromLatin1(m_producer.frame_time()) + QStringLiteral(" / ") +
QString::fromLatin1(m_producer.get_length_time());
m_queue.push(item);
// Seek to the next frame (every other frame with repeat)
if (position + 2 >= length) {
if (m_isLooping) {
m_producer.seek(0);
} else {
m_generateFrames = false;
}
} else {
m_producer.seek(position + 2);
}
}
| 6,259
|
C++
|
.cpp
| 193
| 27.326425
| 104
| 0.657673
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,242
|
videorgbwaveformscopewidget.cpp
|
mltframework_shotcut/src/widgets/scopes/videorgbwaveformscopewidget.cpp
|
/*
* Copyright (c) 2019-2022 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "videorgbwaveformscopewidget.h"
#include <QMouseEvent>
#include <QPainter>
#include <QToolTip>
static const QColor TEXT_COLOR = {255, 255, 255, 127};
VideoRgbWaveformScopeWidget::VideoRgbWaveformScopeWidget()
: ScopeWidget("RgbWaveform")
, m_frame()
, m_renderImg()
, m_mutex()
, m_displayImg()
{
LOG_DEBUG() << "begin";
setMouseTracking(true);
LOG_DEBUG() << "end";
}
void VideoRgbWaveformScopeWidget::refreshScope(const QSize &size, bool full)
{
Q_UNUSED(size)
Q_UNUSED(full)
while (m_queue.count() > 0) {
m_frame = m_queue.pop();
}
int width = m_frame.get_image_width();
int height = m_frame.get_image_height();
if (m_frame.is_valid() && width && height) {
if (m_renderImg.width() != width) {
m_renderImg = QImage(width, 256, QImage::QImage::Format_RGBX8888);
}
QColor bgColor( 0, 0, 0, 0xff );
m_renderImg.fill(bgColor);
const uint8_t *src = m_frame.get_image(mlt_image_rgb);
uint8_t *dst = m_renderImg.scanLine(0);
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
uint8_t ry = 255 - src[0];
size_t rIndex = (ry * width + x) * 4;
if (dst[rIndex] < 0xff) {
dst[rIndex] += 0x0f;
}
uint8_t gy = 255 - src[1];
size_t gIndex = (gy * width + x) * 4 + 1;
if (dst[gIndex] < 0xff) {
dst[gIndex] += 0x0f;
}
uint8_t by = 255 - src[2];
size_t bIndex = (by * width + x) * 4 + 2;
if (dst[bIndex] < 0xff) {
dst[bIndex] += 0x0f;
}
src += 3;
}
}
QImage scaledImage = m_renderImg.scaled(size, Qt::IgnoreAspectRatio,
Qt::SmoothTransformation).convertToFormat(QImage::Format_RGB32);
m_mutex.lock();
m_displayImg.swap(m_renderImg);
m_mutex.unlock();
}
}
void VideoRgbWaveformScopeWidget::paintEvent(QPaintEvent *)
{
if (!isVisible())
return;
// Create the painter
QPainter p(this);
p.setRenderHint(QPainter::Antialiasing, true);
QFont font = QWidget::font();
int fontSize = font.pointSize() - (font.pointSize() > 10 ? 2 : (font.pointSize() > 8 ? 1 : 0));
font.setPointSize(fontSize);
QFontMetrics fm(font);
QPen pen;
pen.setColor(TEXT_COLOR);
pen.setWidth(qRound(devicePixelRatioF()));
p.setPen(pen);
p.setFont(font);
// draw the waveform data
m_mutex.lock();
if (!m_displayImg.isNull()) {
p.drawImage(rect(), m_displayImg, m_displayImg.rect());
} else {
p.fillRect(rect(), QBrush(Qt::black, Qt::SolidPattern));
}
m_mutex.unlock();
// Draw the graticule
int textpad = 3;
int textheight = fm.tightBoundingRect("0").height();
qreal y = 0;
// 255
y = 0;
p.drawLine(QPointF(0, y), QPointF(width(), y));
p.drawText(textpad, textheight + textpad, tr("255"));
// 191
y = (qreal)height() - 191.0 / 255.0 * (qreal)height();
p.drawLine(0, y, width(), y);
p.drawText(textpad, height() / 4 - textpad, tr("191"));
// 127
y = (qreal)height() - 127.0 / 255.0 * (qreal)height();
p.drawLine(0, y, width(), y);
p.drawText(textpad, height() / 2 - textpad, tr("127"));
// 64
y = (qreal)height() - 64.0 / 255.0 * (qreal)height();
p.drawLine(0, y, width(), y);
p.drawText(textpad, height() * 3 / 4 - textpad, tr("64"));
// 0
y = height();
p.drawLine(0, y, width(), y);
p.drawText(textpad, height() - textpad, tr("0"));
}
void VideoRgbWaveformScopeWidget::mouseMoveEvent(QMouseEvent *event)
{
QString text;
m_mutex.lock();
int frameWidth = m_displayImg.width();
m_mutex.unlock();
int value = 255 - (255 * event->pos().y() / height());
if (frameWidth != 0) {
int pixel = frameWidth * event->pos().x() / width();
text = tr("Pixel: %1\nValue: %2").arg(pixel).arg(value);
} else {
text = tr("Value: %1").arg(value);
}
QToolTip::showText(event->globalPosition().toPoint(), text);
}
QString VideoRgbWaveformScopeWidget::getTitle()
{
return tr("Video RGB Waveform");
}
| 5,055
|
C++
|
.cpp
| 144
| 28.416667
| 112
| 0.58584
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,243
|
videovectorscopewidget.cpp
|
mltframework_shotcut/src/widgets/scopes/videovectorscopewidget.cpp
|
/*
* Copyright (c) 2019-2022 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "videovectorscopewidget.h"
#include "mltcontroller.h"
#include "qmltypes/qmlprofile.h"
#include <Logger.h>
#include <QMouseEvent>
#include <QPainter>
#include <QtMath>
#include <QToolTip>
static const QColor LINE_COLOR = {255, 255, 255, 127};
VideoVectorScopeWidget::VideoVectorScopeWidget()
: ScopeWidget("VideoVector")
, m_frame()
, m_renderImg()
, m_mutex()
, m_displayImg()
, m_profileChanged(false)
{
LOG_DEBUG() << "begin";
setMouseTracking(true);
profileChanged();
connect(&QmlProfile::singleton(), SIGNAL(profileChanged()), this, SLOT(profileChanged()));
LOG_DEBUG() << "end";
}
VideoVectorScopeWidget::~VideoVectorScopeWidget()
{
disconnect(&QmlProfile::singleton(), SIGNAL(profileChanged()), this, SLOT(profileChanged()));
}
QString VideoVectorScopeWidget::getTitle()
{
return tr("Video Vector");
}
void VideoVectorScopeWidget::refreshScope(const QSize &size, bool full)
{
Q_UNUSED(full)
qreal side = qMin(size.width(), size.height());
QSize squareSize = QSize(side, side);
if (m_graticuleImg.size() != size || m_profileChanged) {
m_graticuleImg = QImage(squareSize, QImage::Format_RGB32);
m_graticuleImg.fill(0);
QPainter p(&m_graticuleImg);
p.setRenderHint(QPainter::Antialiasing, true);
// Convert the coordinate system to match the U/V coordinate system
// 256x256 going up from the bottom
p.translate(0, side);
p.scale(side / 256.0, -1.0 * side / 256.0);
m_mutex.lock();
drawGraticuleLines(p, devicePixelRatioF());
drawGraticuleMark(p, m_points[BLUE_100], Qt::blue, devicePixelRatioF() * 2, 8);
drawGraticuleMark(p, m_points[CYAN_100], Qt::cyan, devicePixelRatioF() * 2, 8);
drawGraticuleMark(p, m_points[GREEN_100], Qt::green, devicePixelRatioF() * 2, 8);
drawGraticuleMark(p, m_points[YELLOW_100], Qt::yellow, devicePixelRatioF() * 2, 8);
drawGraticuleMark(p, m_points[RED_100], Qt::red, devicePixelRatioF() * 2, 8);
drawGraticuleMark(p, m_points[MAGENTA_100], Qt::magenta, devicePixelRatioF() * 2, 8);
drawGraticuleMark(p, m_points[BLUE_75], Qt::blue, devicePixelRatioF(), 5);
drawGraticuleMark(p, m_points[CYAN_75], Qt::cyan, devicePixelRatioF(), 5);
drawGraticuleMark(p, m_points[GREEN_75], Qt::green, devicePixelRatioF(), 5);
drawGraticuleMark(p, m_points[YELLOW_75], Qt::yellow, devicePixelRatioF(), 5);
drawGraticuleMark(p, m_points[RED_75], Qt::red, devicePixelRatioF(), 5);
drawGraticuleMark(p, m_points[MAGENTA_75], Qt::magenta, devicePixelRatioF(), 5);
drawSkinToneLine(p, devicePixelRatioF());
m_profileChanged = false;
p.end();
m_mutex.unlock();
}
while (m_queue.count() > 0) {
m_frame = m_queue.pop();
}
int width = m_frame.get_image_width();
int height = m_frame.get_image_height();
if (m_frame.is_valid() && width && height) {
if (m_renderImg.width() != 256) {
m_renderImg = QImage(256, 256, QImage::Format_RGBX8888);
}
m_renderImg.fill(0);
const uint8_t *src = m_frame.get_image(mlt_image_yuv420p);
const uint8_t *uSrc = src + (width * height);
const uint8_t *vSrc = uSrc + (width * height / 4);
uint8_t *dst = m_renderImg.scanLine(0);
int cHeight = height / 2;
int cWidth = width / 2;
for (int y = 0; y < cHeight; y++) {
for (int x = 0; x < cWidth; x++) {
uint8_t dx = *uSrc;
uint8_t dy = 255 - *vSrc;
size_t dIndex = (dy * 256 + dx) * 4;
if (dst[dIndex] < 0xff) {
dst[dIndex] += 0x0f;
dst[dIndex + 1] += 0x0f;
dst[dIndex + 2] += 0x0f;
}
uSrc++;
vSrc++;
}
}
QImage newDisplayImage = m_graticuleImg.copy();
QPainter p(&newDisplayImage);
// Use "plus" composition so that light points will stand out on top of a graticule line.
p.setCompositionMode(QPainter::CompositionMode_Plus);
p.setRenderHint(QPainter::SmoothPixmapTransform, true);
p.setRenderHint(QPainter::Antialiasing, true);
p.drawImage(newDisplayImage.rect(), m_renderImg, m_renderImg.rect());
p.end();
m_mutex.lock();
m_displayImg.swap(newDisplayImage);
m_mutex.unlock();
} else {
m_mutex.lock();
m_displayImg = m_graticuleImg.copy();
m_mutex.unlock();
}
}
void VideoVectorScopeWidget::drawGraticuleLines(QPainter &p, qreal lineWidth)
{
QRadialGradient radialGradient(128.0, 128.0, 128.0);
radialGradient.setColorAt(0.0, Qt::transparent);
radialGradient.setColorAt(0.05, Qt::transparent);
radialGradient.setColorAt(0.06, LINE_COLOR.darker());
radialGradient.setColorAt(0.10, LINE_COLOR.darker());
radialGradient.setColorAt(0.11, Qt::transparent);
radialGradient.setColorAt(0.3, Qt::transparent);
radialGradient.setColorAt(1.0, LINE_COLOR);
QBrush graticuleBrush(radialGradient);
p.setBrush(graticuleBrush);
p.setPen(QPen(graticuleBrush, lineWidth));
p.drawLine(m_points[BLUE_100], m_points[YELLOW_100]);
p.drawLine(m_points[CYAN_100], m_points[RED_100]);
p.drawLine(m_points[GREEN_100], m_points[MAGENTA_100]);
}
void VideoVectorScopeWidget::drawSkinToneLine(QPainter &p, qreal lineWidth)
{
// Draw a skin tone line 33 degrees counter clockwise from the red vector
qreal angle = qRadiansToDegrees(qAtan((qreal)(m_points[RED_100].x() - 128) / (qreal)(
m_points[RED_100].y() - 128)));
angle += 270;
angle -= 33;
QRadialGradient radialGradient(128.0, 128.0, 128.0);
radialGradient.setColorAt(0.0, Qt::transparent);
radialGradient.setColorAt(0.2, Qt::transparent);
radialGradient.setColorAt(1.0, LINE_COLOR);
QBrush graticuleBrush(radialGradient);
p.setBrush(graticuleBrush);
p.setPen(QPen(graticuleBrush, lineWidth, Qt::DotLine));
QLineF skinToneLine;
skinToneLine.setP1(QPoint(128, 128));
skinToneLine.setLength(120);
skinToneLine.setAngle(angle);
p.drawLine(skinToneLine);
}
void VideoVectorScopeWidget::drawGraticuleMark(QPainter &p, const QPoint &point, QColor color,
qreal lineWidth, qreal LineLength)
{
color = color.darker(100);
p.setBrush(color);
p.setPen(QPen(color, lineWidth, Qt::SolidLine, Qt::RoundCap));
QLineF angleline;
qreal angle = qAtan((qreal)(point.x() - 128) / (qreal)(point.y() - 128));
angle = qRadiansToDegrees(angle);
angleline.setP1(point);
angleline.setLength(LineLength / 2);
angleline.setAngle(angle);
p.drawLine(angleline);
angleline.setAngle(angle + 180);
p.drawLine(angleline);
}
void VideoVectorScopeWidget::paintEvent(QPaintEvent *)
{
if (!isVisible())
return;
QRect squareRect = getCenteredSquare();
// Create the painter
QPainter p(this);
p.setRenderHint(QPainter::Antialiasing, true);
p.setRenderHint(QPainter::SmoothPixmapTransform, true);
// draw the vector image
m_mutex.lock();
if (!m_displayImg.isNull()) {
p.drawImage(squareRect, m_displayImg, m_displayImg.rect());
} else {
p.fillRect(squareRect, QBrush(Qt::black, Qt::SolidPattern));
}
m_mutex.unlock();
}
void VideoVectorScopeWidget::mouseMoveEvent(QMouseEvent *event)
{
QRectF squareRect = getCenteredSquare();
if (!squareRect.contains(event->pos())) {
QToolTip::hideText();
return;
}
qreal realX = (qreal)event->pos().x() - ((qreal)width() - squareRect.width()) / 2;
qreal realY = (qreal)event->pos().y() - ((qreal)height() - squareRect.height()) / 2;
qreal u = realX * 255.0 / squareRect.width();
qreal v = (squareRect.height() - realY) * 255.0 / squareRect.height();
QString text = tr("U: %1\nV: %2").arg(qRound(u)).arg(qRound(v));
QToolTip::showText(event->globalPosition().toPoint(), text);
}
QRect VideoVectorScopeWidget::getCenteredSquare()
{
// Calculate the size. Vectorscope is always a square.
QRect squareRect;
if (width() > height()) {
int x = (width() - height()) / 2;
squareRect = QRect(x, 0, height(), height());
} else {
int y = (height() - width()) / 2;
squareRect = QRect(0, y, width(), width());
}
return squareRect;
}
void VideoVectorScopeWidget::profileChanged()
{
LOG_DEBUG() << MLT.profile().colorspace();
m_mutex.lock();
switch (MLT.profile().colorspace()) {
case 601:
m_points[BLUE_75] = QPoint(212, 114);
m_points[CYAN_75] = QPoint(156, 44);
m_points[GREEN_75] = QPoint(72, 58);
m_points[YELLOW_75] = QPoint(44, 142);
m_points[RED_75] = QPoint(100, 212);
m_points[MAGENTA_75] = QPoint(184, 198);
m_points[BLUE_100] = QPoint(240, 110);
m_points[CYAN_100] = QPoint(166, 16);
m_points[GREEN_100] = QPoint(54, 34);
m_points[YELLOW_100] = QPoint(16, 146);
m_points[RED_100] = QPoint(90, 240);
m_points[MAGENTA_100] = QPoint(202, 222);
break;
default:
case 709:
m_points[BLUE_75] = QPoint(212, 120);
m_points[CYAN_75] = QPoint(147, 44);
m_points[GREEN_75] = QPoint(63, 52);
m_points[YELLOW_75] = QPoint(44, 136);
m_points[RED_75] = QPoint(109, 212);
m_points[MAGENTA_75] = QPoint(193, 204);
m_points[BLUE_100] = QPoint(240, 118);
m_points[CYAN_100] = QPoint(154, 16);
m_points[GREEN_100] = QPoint(42, 26);
m_points[YELLOW_100] = QPoint(16, 138);
m_points[RED_100] = QPoint(102, 240);
m_points[MAGENTA_100] = QPoint(214, 230);
break;
}
m_profileChanged = true;
m_mutex.unlock();
requestRefresh();
}
| 10,729
|
C++
|
.cpp
| 264
| 34.094697
| 97
| 0.635536
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,244
|
audiosurroundscopewidget.cpp
|
mltframework_shotcut/src/widgets/scopes/audiosurroundscopewidget.cpp
|
/*
* Copyright (c) 2024 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "audiosurroundscopewidget.h"
#include <Logger.h>
#include "settings.h"
#include "widgets/iecscale.h"
#include <QPen>
#include <QPainter>
#include <math.h>
static const int TEXT_MARGIN = 3;
QPointF vectorToPoint(qreal direction, qreal magnitude)
{
QPointF result;
result.setX(magnitude * cos(direction * M_PI / 180));
result.setY(magnitude * sin(direction * M_PI / 180));
return result;
}
QPointF mapFromCenter(QPointF point, QPointF center)
{
point.setX(center.x() + point.x());
point.setY(center.y() - point.y());
return point;
}
AudioSurroundScopeWidget::AudioSurroundScopeWidget()
: ScopeWidget("AudioSurround")
, m_frame()
, m_renderImg()
, m_mutex()
, m_displayImg()
, m_channelsChanged(true)
, m_channels(Settings.playerAudioChannels())
{
LOG_DEBUG() << "begin";
connect(&Settings, &ShotcutSettings::playerAudioChannelsChanged, this, [&]() {
m_channelsChanged = true;
m_channels = Settings.playerAudioChannels();
requestRefresh();
});
LOG_DEBUG() << "end";
}
AudioSurroundScopeWidget::~AudioSurroundScopeWidget()
{
}
QString AudioSurroundScopeWidget::getTitle()
{
return tr("Audio Surround");
}
void AudioSurroundScopeWidget::refreshScope(const QSize &size, bool full)
{
Q_UNUSED(full)
qreal side = qMin(size.width(), size.height());
QSize squareSize = QSize(side, side);
if (m_graticuleImg.size() != size || m_channelsChanged) {
m_graticuleImg = QImage(squareSize, QImage::Format_ARGB32_Premultiplied);
m_graticuleImg.fill(Qt::transparent);
QPainter p(&m_graticuleImg);
p.setRenderHint(QPainter::Antialiasing, true);
drawGraticule(p, devicePixelRatioF());
p.end();
}
while (m_queue.count() > 0) {
m_frame = m_queue.pop();
}
if (m_frame.is_valid() && m_frame.get_audio_samples() > 0) {
// Calculate the peak level for each channel
int channels = m_frame.get_audio_channels();
int samples = m_frame.get_audio_samples();
QVector<double> levels;
const int16_t *audio = m_frame.get_audio();
for ( int c = 0; c < channels; c++ ) {
int16_t peak = 0;
const int16_t *p = audio + c;
for ( int s = 0; s < samples; s++ ) {
int16_t sample = abs(*p );
if (sample > peak) peak = sample;
p += channels;
}
double levelDb = 0.0;
if (peak == 0) {
levelDb = -100.0;
} else {
levelDb = 20 * log10((double)peak / (double)std::numeric_limits<int16_t>::max());
}
levels << IEC_ScaleMax(levelDb, 0);
}
// Set up a new image and get ready to paint
QImage newDisplayImage = m_graticuleImg.copy();
QPainter p(&newDisplayImage);
p.setRenderHint(QPainter::SmoothPixmapTransform, true);
p.setRenderHint(QPainter::Antialiasing, true);
QPen pen;
QRectF rect = newDisplayImage.rect();
QPointF center = rect.center();
QVector<QPointF> allPoints;
QRectF insideRect;
insideRect.setX(fontMetrics().height() + 2 * TEXT_MARGIN);
insideRect.setY(insideRect.x());
insideRect.setWidth(rect.width() - 2 * insideRect.x());
insideRect.setHeight(insideRect.width());
qreal maxCornerLength = sqrt( 2 * pow(insideRect.width() / 2, 2) );
// Draw the inside lines from center
pen.setColor(palette().color(QPalette::Active, QPalette::Highlight));
pen.setWidth(3);
p.setPen(pen);
// Left
if (channels > 1) {
qreal magnitude = levels[0] * maxCornerLength;
QPointF point = vectorToPoint(135, magnitude);
point = mapFromCenter(point, center);
p.drawLine(center, point);
allPoints << point;
}
// Center
if (channels == 1 || channels > 4) {
qreal magnitude;
if (channels == 1)
magnitude = levels[0];
else
magnitude = levels[2];
magnitude *= insideRect.height() / 2;
QPointF point = vectorToPoint(90, magnitude);
point = mapFromCenter(point, center);
p.drawLine(center, point);
allPoints << point;
}
// Right
if (channels > 1) {
qreal magnitude = levels[1] * maxCornerLength;
QPointF point = vectorToPoint(45, magnitude);
point = mapFromCenter(point, center);
p.drawLine(center, point);
allPoints << point;
}
// Right Surround
if (channels > 3) {
qreal magnitude;
if (channels == 4)
magnitude = levels[3];
else
magnitude = levels[5];
magnitude *= maxCornerLength;
QPointF point = vectorToPoint(315, magnitude);
point = mapFromCenter(point, center);
p.drawLine(center, point);
allPoints << point;
}
// Left Surround
if (channels > 3) {
qreal magnitude;
if (channels == 4)
magnitude = levels[2];
else
magnitude = levels[4];
magnitude *= maxCornerLength;
QPointF point = vectorToPoint(225, magnitude);
point = mapFromCenter(point, center);
p.drawLine(center, point);
allPoints << point;
}
// Get HSV highlight values to calculate complimentary colors
int h, s, v;
palette().color(QPalette::Active, QPalette::Highlight).getHsv(&h, &s, &v);
// Draw the outside lines from point-to-point
// Find a complimentary color
QColor outline = QColor::fromHsv((h + 120) % 360, s, v);
pen.setColor(outline);
p.setPen(pen);
for (int i = 0; i < allPoints.size() - 1; i++) {
p.drawLine(allPoints[i], allPoints[i + 1]);
}
// Connect the last point to the first point
if (allPoints.size() > 1) {
p.drawLine(allPoints[allPoints.size() - 1], allPoints[0]);
}
// Connect the L and R if center exists
if (allPoints.size() > 2 && allPoints.size() != 4) {
p.drawLine(allPoints[0], allPoints[2]);
}
// Draw a circle for the average value
float x = 0;
float y = 0;
for (int i = 0; i < allPoints.size(); i++) {
x += allPoints[i].x();
y += allPoints[i].y();
}
x /= allPoints.size();
y /= allPoints.size();
// Find another complimentary color
QColor circle = QColor::fromHsv((h + 240) % 360, s, v);
pen.setColor(circle);
p.setPen(pen);
p.drawEllipse(QPointF(x, y), 4, 4);
p.drawEllipse(QPointF(x, y), 8, 8);
p.end();
m_mutex.lock();
m_displayImg.swap(newDisplayImage);
m_mutex.unlock();
} else {
m_mutex.lock();
m_displayImg = m_graticuleImg.copy();
m_mutex.unlock();
}
}
void AudioSurroundScopeWidget::drawGraticule(QPainter &p, qreal lineWidth)
{
QPen pen;
QColor color;
QRect rect = p.window();
QPoint labelPosition;
QString labelText;
int labelWidth;
// Left
labelText = tr("L");
labelPosition.setX(TEXT_MARGIN);
labelPosition.setY(fontMetrics().height());
if (m_channels > 1) {
color = palette().color(QPalette::Active, QPalette::Text);
} else {
color = palette().color(QPalette::Disabled, QPalette::Text);
}
pen.setColor(color);
p.setPen(pen);
p.drawText(labelPosition, labelText);
// Center
labelText = tr("C");
labelWidth = fontMetrics().horizontalAdvance(labelText);
labelPosition.setX((rect.width() / 2) - (labelWidth / 2));
labelPosition.setY(fontMetrics().height());
if (m_channels == 1 || m_channels == 3 || m_channels == 5 || m_channels == 6) {
color = palette().color(QPalette::Active, QPalette::Text);
} else {
color = palette().color(QPalette::Disabled, QPalette::Text);
}
pen.setColor(color);
p.setPen(pen);
p.drawText(labelPosition, labelText);
// Right
labelText = tr("R");
labelWidth = fontMetrics().horizontalAdvance(labelText);
labelPosition.setX(rect.width() - labelWidth - TEXT_MARGIN);
labelPosition.setY(fontMetrics().height());
if (m_channels > 1) {
color = palette().color(QPalette::Active, QPalette::Text);
} else {
color = palette().color(QPalette::Disabled, QPalette::Text);
}
pen.setColor(color);
p.setPen(pen);
p.drawText(labelPosition, labelText);
// Left Surround
labelText = tr("LS");
labelPosition.setX(TEXT_MARGIN);
labelPosition.setY(rect.height() - TEXT_MARGIN);
if (m_channels > 3) {
color = palette().color(QPalette::Active, QPalette::Text);
} else {
color = palette().color(QPalette::Disabled, QPalette::Text);
}
pen.setColor(color);
p.setPen(pen);
p.drawText(labelPosition, labelText);
// Right Surround
labelText = tr("RS");
labelWidth = fontMetrics().horizontalAdvance(labelText);
labelPosition.setX(rect.width() - labelWidth - TEXT_MARGIN);
labelPosition.setY(rect.height() - TEXT_MARGIN);
if (m_channels > 3) {
color = palette().color(QPalette::Active, QPalette::Text);
} else {
color = palette().color(QPalette::Disabled, QPalette::Text);
}
pen.setColor(color);
p.setPen(pen);
p.drawText(labelPosition, labelText);
// Draw outside frame
QRectF insideRect;
insideRect.setX(fontMetrics().height() + 2 * TEXT_MARGIN);
insideRect.setY(insideRect.x());
insideRect.setWidth(rect.width() - 2 * insideRect.x());
insideRect.setHeight(insideRect.width());
pen.setColor(palette().color(QPalette::Active, QPalette::Text));
p.setPen(pen);
p.drawRect(insideRect);
}
void AudioSurroundScopeWidget::paintEvent(QPaintEvent *)
{
if (!isVisible())
return;
QRect squareRect;
if (width() > height()) {
int x = (width() - height()) / 2;
squareRect = QRect(x, 0, height(), height());
} else {
int y = (height() - width()) / 2;
squareRect = QRect(0, y, width(), width());
}
// Create the painter
QPainter p(this);
p.setRenderHint(QPainter::Antialiasing, true);
p.setRenderHint(QPainter::SmoothPixmapTransform, true);
// draw the vector image
m_mutex.lock();
if (!m_displayImg.isNull()) {
p.drawImage(squareRect, m_displayImg, m_displayImg.rect());
} else {
p.fillRect(squareRect, QBrush(Qt::transparent, Qt::SolidPattern));
}
m_mutex.unlock();
}
| 11,559
|
C++
|
.cpp
| 323
| 28.340557
| 97
| 0.602803
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,245
|
audiopeakmeterscopewidget.cpp
|
mltframework_shotcut/src/widgets/scopes/audiopeakmeterscopewidget.cpp
|
/*
* Copyright (c) 2015-2022 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "audiopeakmeterscopewidget.h"
#include "settings.h"
#include <Logger.h>
#include <QVBoxLayout>
#include "widgets/audiometerwidget.h"
#include "mltcontroller.h"
#include <cmath> // log10()
AudioPeakMeterScopeWidget::AudioPeakMeterScopeWidget()
: ScopeWidget("AudioPeakMeter")
, m_audioMeter(0)
, m_orientation((Qt::Orientation) - 1)
, m_channels( Settings.playerAudioChannels() )
{
LOG_DEBUG() << "begin";
qRegisterMetaType< QVector<double> >("QVector<double>");
setAutoFillBackground(true);
QVBoxLayout *vlayout = new QVBoxLayout(this);
vlayout->setContentsMargins(4, 4, 4, 4);
m_audioMeter = new AudioMeterWidget(this);
m_audioMeter->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
QVector<int> dbscale;
dbscale << -50 << -40 << -35 << -30 << -25 << -20 << -15 << -10 << -5 << 0;
m_audioMeter->setDbLabels(dbscale);
vlayout->addWidget(m_audioMeter);
LOG_DEBUG() << "end";
}
void AudioPeakMeterScopeWidget::refreshScope(const QSize & /*size*/, bool /*full*/)
{
SharedFrame sFrame;
while (m_queue.count() > 0) {
sFrame = m_queue.pop();
if (sFrame.is_valid() && sFrame.get_audio_samples() > 0) {
int channels = sFrame.get_audio_channels();
int samples = sFrame.get_audio_samples();
QVector<double> levels;
const int16_t *audio = sFrame.get_audio();
for ( int c = 0; c < channels; c++ ) {
int16_t peak = 0;
const int16_t *p = audio + c;
for ( int s = 0; s < samples; s++ ) {
int16_t sample = abs(*p );
if (sample > peak) peak = sample;
p += channels;
}
if (peak == 0) {
levels << -100.0;
} else {
levels << 20 * log10((double)peak / (double)std::numeric_limits<int16_t>::max());
}
}
QMetaObject::invokeMethod(m_audioMeter, "showAudio", Qt::QueuedConnection,
Q_ARG(const QVector<double> &, levels));
if (m_channels != channels) {
m_channels = channels;
QMetaObject::invokeMethod(this, "reconfigureMeter", Qt::QueuedConnection);
}
}
}
}
QString AudioPeakMeterScopeWidget::getTitle()
{
return tr("Audio Peak Meter");
}
void AudioPeakMeterScopeWidget::setOrientation(Qt::Orientation orientation)
{
if (orientation != m_orientation) {
m_orientation = orientation;
m_audioMeter->setOrientation(orientation);
reconfigureMeter();
}
}
void AudioPeakMeterScopeWidget::reconfigureMeter()
{
// Set the bar labels.
QStringList channelLabels;
if (m_channels == 2 )
channelLabels << tr("L") << tr("R");
if (m_channels == 4 )
channelLabels << tr("L") << tr("R") << tr("Ls") << tr("Rs");
else if (m_channels == 6 )
channelLabels << tr("L") << tr("R") << tr("C") << tr("LF") << tr("Ls") << tr("Rs");
m_audioMeter->setChannelLabels(channelLabels);
// Set the size constraints.
int spaceNeeded = ( m_channels * 16 ) + 17;
if (m_orientation == Qt::Vertical) {
m_audioMeter->setMinimumSize(spaceNeeded, 250);
setMinimumSize(spaceNeeded + 8, 258);
setMaximumSize(spaceNeeded + 8, 508);
} else {
m_audioMeter->setMinimumSize(250, spaceNeeded);
setMinimumSize(258, spaceNeeded + 8);
setMaximumSize(508, spaceNeeded + 8);
}
updateGeometry();
}
| 4,290
|
C++
|
.cpp
| 111
| 31.630631
| 101
| 0.613375
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,246
|
audiospectrumscopewidget.cpp
|
mltframework_shotcut/src/widgets/scopes/audiospectrumscopewidget.cpp
|
/*
* Copyright (c) 2015-2016 Meltytech, LLC
* Author: Brian Matherly <code@brianmatherly.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "audiospectrumscopewidget.h"
#include "widgets/audiometerwidget.h"
#include <Logger.h>
#include <QPainter>
#include <QtAlgorithms>
#include <QVBoxLayout>
#include <MltProfile.h>
#include <cmath>
static const int WINDOW_SIZE = 8000; // 6 Hz FFT bins at 48kHz
struct band {
float low; // Low frequency
float center; // Center frequency
float high; // High frequency
const char *label;
};
// Preferred frequencies from ISO R 266-1997 / ANSI S1.6-1984
static const band BAND_TAB[] = {
// Low Preferred High Band
// Freq Center Freq Label Num
{ 1.12, 1.25, 1.41, "1.25" }, // 1
{ 1.41, 1.60, 1.78, "1.6" }, // 2
{ 1.78, 2.00, 2.24, "2.0" }, // 3
{ 2.24, 2.50, 2.82, "2.5" }, // 4
{ 2.82, 3.15, 3.55, "3.15" }, // 5
{ 3.55, 4.00, 4.44, "4.0" }, // 6
{ 4.44, 5.00, 6.00, "5.0" }, // 7
{ 6.00, 6.30, 7.00, "6.3" }, // 8
{ 7.00, 8.00, 9.00, "8.0" }, // 9
{ 9.00, 10.00, 11.00, "10" }, // 10
{ 11.00, 12.50, 14.00, "12.5" }, // 11
{ 14.00, 16.00, 18.00, "16" }, // 12
{ 18.00, 20.00, 22.00, "20" }, // 13 - First in audible range
{ 22.00, 25.00, 28.00, "25" }, // 14
{ 28.00, 31.50, 35.00, "31" }, // 15
{ 35.00, 40.00, 45.00, "40" }, // 16
{ 45.00, 50.00, 56.00, "50" }, // 17
{ 56.00, 63.00, 71.00, "63" }, // 18
{ 71.00, 80.00, 90.00, "80" }, // 19
{ 90.00, 100.00, 112.00, "100" }, // 20
{ 112.00, 125.00, 140.00, "125" }, // 21
{ 140.00, 160.00, 179.00, "160" }, // 22
{ 179.00, 200.00, 224.00, "200" }, // 23
{ 224.00, 250.00, 282.00, "250" }, // 24
{ 282.00, 315.00, 353.00, "315" }, // 25
{ 353.00, 400.00, 484.00, "400" }, // 26
{ 484.00, 500.00, 560.00, "500" }, // 27
{ 560.00, 630.00, 706.00, "630" }, // 28
{ 706.00, 800.00, 897.00, "800" }, // 29
{ 897.00, 1000.00, 1121.00, "1k" }, // 30
{ 1121.00, 1250.00, 1401.00, "1.3k" }, // 31
{ 1401.00, 1600.00, 1794.00, "1.6k" }, // 32
{ 1794.00, 2000.00, 2242.00, "2k" }, // 33
{ 2242.00, 2500.00, 2803.00, "2.5k" }, // 34
{ 2803.00, 3150.00, 3531.00, "3.2k" }, // 35
{ 3531.00, 4000.00, 4484.00, "4k" }, // 36
{ 4484.00, 5000.00, 5605.00, "5k" }, // 37
{ 5605.00, 6300.00, 7062.00, "6.3k" }, // 38
{ 7062.00, 8000.00, 8908.00, "8k" }, // 39
{ 8908.00, 10000.00, 11210.00, "10k" }, // 40
{ 11210.00, 12500.00, 14012.00, "13k" }, // 41
{ 14012.00, 16000.00, 17936.00, "16k" }, // 42
{ 17936.00, 20000.00, 22421.00, "20k" }, // 43 - Last in audible range
};
static const int FIRST_AUDIBLE_BAND_INDEX = 12;
static const int LAST_AUDIBLE_BAND_INDEX = 42;
static const int AUDIBLE_BAND_COUNT = LAST_AUDIBLE_BAND_INDEX - FIRST_AUDIBLE_BAND_INDEX + 1;
AudioSpectrumScopeWidget::AudioSpectrumScopeWidget()
: ScopeWidget("AudioSpectrum")
, m_audioMeter(0)
{
LOG_DEBUG() << "begin";
// Setup this widget
qRegisterMetaType< QVector<double> >("QVector<double>");
// Create the FFT filter
Mlt::Profile profile;
m_filter = new Mlt::Filter(profile, "fft");
m_filter->set("window_size", WINDOW_SIZE);
// Add the audio signal widget
QVBoxLayout *vlayout = new QVBoxLayout(this);
vlayout->setContentsMargins(4, 4, 4, 4);
m_audioMeter = new AudioMeterWidget(this);
m_audioMeter->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
QVector<int> dbscale;
dbscale << -50 << -40 << -35 << -30 << -25 << -20 << -15 << -10 << -5 << 0;
m_audioMeter->setDbLabels(dbscale);
QStringList freqLabels;
for (int i = FIRST_AUDIBLE_BAND_INDEX; i <= LAST_AUDIBLE_BAND_INDEX; i++) {
freqLabels << BAND_TAB[i].label;
}
m_audioMeter->setChannelLabels(freqLabels);
m_audioMeter->setChannelLabelUnits("Hz");
vlayout->addWidget(m_audioMeter);
// Config the size.
m_audioMeter->setOrientation(Qt::Vertical);
m_audioMeter->setMinimumSize(200, 80);
m_audioMeter->setMaximumSize(600, 600);
setMinimumSize(204, 84);
setMaximumSize(604, 604);
LOG_DEBUG() << "end";
}
AudioSpectrumScopeWidget::~AudioSpectrumScopeWidget()
{
delete m_filter;
}
void AudioSpectrumScopeWidget::processSpectrum()
{
QVector<double> bands(AUDIBLE_BAND_COUNT);
float *bins = (float *)m_filter->get_data("bins");
int bin_count = m_filter->get_int("bin_count");
double bin_width = m_filter->get_double("bin_width");
int band = 0;
bool firstBandFound = false;
for (int bin = 0; bin < bin_count; bin++) {
// Loop through all the FFT bins and align bin frequencies with
// band frequencies.
double F = bin_width * (double)bin;
if (!firstBandFound) {
// Skip bins that come before the first band.
if (BAND_TAB[band + FIRST_AUDIBLE_BAND_INDEX].low > F) {
continue;
} else {
firstBandFound = true;
bands[band] = bins[bin];
}
} else if (BAND_TAB[band + FIRST_AUDIBLE_BAND_INDEX].high < F) {
// This bin is outside of this band - move to the next band.
band++;
if ((band + FIRST_AUDIBLE_BAND_INDEX) > LAST_AUDIBLE_BAND_INDEX) {
// Skip bins that come after the last band.
break;
}
bands[band] = bins[bin];
} else if (bands[band] < bins[bin] ) {
// Pick the highest bin level within this band to represent the
// whole band.
bands[band] = bins[bin];
}
}
// At this point, bands contains the magnitude of the signal for each
// band. Convert to dB.
for (band = 0; band < bands.size(); band++) {
double mag = bands[band];
double dB = mag > 0.0 ? 20 * log10( mag ) : -1000.0;
bands[band] = dB;
}
// Update the audio signal widget
QMetaObject::invokeMethod(m_audioMeter, "showAudio", Qt::QueuedConnection,
Q_ARG(const QVector<double> &, bands));
}
void AudioSpectrumScopeWidget::refreshScope(const QSize & /*size*/, bool /*full*/)
{
bool refresh = false;
SharedFrame sFrame;
while (m_queue.count() > 0) {
sFrame = m_queue.pop();
if (sFrame.is_valid() && sFrame.get_audio_samples() > 0) {
mlt_audio_format format = mlt_audio_s16;
int channels = sFrame.get_audio_channels();
int frequency = sFrame.get_audio_frequency();
int samples = sFrame.get_audio_samples();
Mlt::Frame mFrame = sFrame.clone(true, false, false);
m_filter->process(mFrame);
mFrame.get_audio( format, frequency, channels, samples );
refresh = true;
}
}
if (refresh) {
processSpectrum();
}
}
QString AudioSpectrumScopeWidget::getTitle()
{
return tr("Audio Spectrum");
}
| 7,997
|
C++
|
.cpp
| 191
| 36.141361
| 93
| 0.559666
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
13,247
|
audiowaveformscopewidget.cpp
|
mltframework_shotcut/src/widgets/scopes/audiowaveformscopewidget.cpp
|
/*
* Copyright (c) 2015-2022 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "audiowaveformscopewidget.h"
#include <Logger.h>
#include <QMouseEvent>
#include <QPainter>
#include <QResizeEvent>
#include <QToolTip>
#include <cmath>
static const qreal MAX_AMPLITUDE = 32768.0;
static int graphHeight(const QSize &widgetSize, int maxChan, int padding)
{
int totalPadding = padding + (padding * maxChan);
return (widgetSize.height() - totalPadding) / maxChan;
}
static int graphBottomY(const QSize &widgetSize, int channel, int maxChan, int padding)
{
int gHeight = graphHeight(widgetSize, maxChan, padding);
return padding + (gHeight + padding) * channel;
}
static int graphTopY(const QSize &widgetSize, int channel, int maxChan, int padding)
{
int gHeight = graphHeight(widgetSize, maxChan, padding);
return graphBottomY(widgetSize, channel, maxChan, padding) + gHeight;
}
static int graphCenterY(const QSize &widgetSize, int channel, int maxChan, int padding)
{
int gHeight = graphHeight(widgetSize, maxChan, padding);
return graphBottomY(widgetSize, channel, maxChan, padding) + gHeight / 2;
}
AudioWaveformScopeWidget::AudioWaveformScopeWidget()
: ScopeWidget("AudioWaveform")
, m_renderWave()
, m_graphTopPadding(0)
, m_channels(0)
, m_cursorPos(-1)
, m_mutex()
, m_displayWave()
, m_displayGrid()
{
LOG_DEBUG() << "begin";
setAutoFillBackground(true);
setMinimumSize(100, 100);
setMouseTracking(true);
LOG_DEBUG() << "end";
}
AudioWaveformScopeWidget::~AudioWaveformScopeWidget()
{
}
void AudioWaveformScopeWidget::refreshScope(const QSize &size, bool full)
{
m_mutex.lock();
QSize prevSize = m_displayWave.size();
while (m_queue.count() > 0) {
m_frame = m_queue.pop();
}
m_mutex.unlock();
// Check if a full refresh should be forced.
int channels = 2;
if (m_frame.is_valid() && m_frame.get_audio_channels() > 0) {
channels = m_frame.get_audio_channels();
}
if (prevSize != size || channels != m_channels) {
m_channels = channels;
full = true;
}
if (full) {
createGrid(size);
}
if (m_renderWave.size() != size) {
m_renderWave = QImage(size, QImage::Format_ARGB32_Premultiplied);
}
m_renderWave.fill(Qt::transparent);
QPainter p(&m_renderWave);
p.setRenderHint(QPainter::Antialiasing, true);
QColor penColor(palette().text().color());
penColor.setAlpha(255 / 2);
QPen pen(penColor);
pen.setWidth(0);
p.setPen(pen);
if (m_frame.is_valid() && m_frame.get_audio_samples() > 0) {
int samples = m_frame.get_audio_samples();
int16_t *audio = (int16_t *)m_frame.get_audio();
int waveAmplitude = graphHeight(size, m_channels, m_graphTopPadding) / 2;
qreal scaleFactor = (qreal)waveAmplitude / (qreal)MAX_AMPLITUDE;
for (int c = 0; c < m_channels; c++) {
p.save();
int y = graphCenterY(size, c, m_channels, m_graphTopPadding);
p.translate(0, y);
// For each x position on the waveform, find the min and max sample
// values that apply to that position. Draw a vertical line from the
// min value to the max value.
QPoint high;
QPoint low;
int lastX = 0;
const int16_t *q = audio + c;
// Invert the polarity because QT draws from top to bottom.
int16_t value = *q * -1;
qreal max = value;
qreal min = value;
for (int i = 0; i <= samples; i++) {
int x = ( i * size.width() ) / samples;
if (x != lastX) {
// The min and max have been determined for the previous x
// So draw the line
high.setX(lastX);
high.setY(max * scaleFactor);
low.setX(lastX);
low.setY(min * scaleFactor);
if (high.y() == low.y()) {
p.drawPoint(high);
} else {
p.drawLine(low, high);
}
lastX = x;
// Swap max and min so that the next line picks up where
// this one left off.
int tmp = max;
max = min;
min = tmp;
}
if (value > max) max = value;
if (value < min) min = value;
q += m_channels;
value = *q * -1;
}
p.restore();
}
}
p.end();
m_mutex.lock();
m_displayWave.swap(m_renderWave);
m_mutex.unlock();
}
void AudioWaveformScopeWidget::createGrid(const QSize &size)
{
QFont font = QWidget::font();
int fontSize = font.pointSize() - (font.pointSize() > 10 ? 2 : (font.pointSize() > 8 ? 1 : 0));
font.setPointSize(fontSize);
QFontMetrics fm(font);
QString zeroLabel = tr("0");
QString infinityLabel = tr("-inf");
QRect textRect = fm.tightBoundingRect( infinityLabel );
int labelHeight = textRect.height();
m_graphTopPadding = fm.height();
m_graphLeftPadding = textRect.width() + 6;
m_mutex.lock();
m_displayGrid = QImage(size, QImage::Format_ARGB32_Premultiplied);
m_displayGrid.fill(Qt::transparent);
QPainter p(&m_displayGrid);
p.setPen(palette().text().color().rgb());
p.setFont(font);
for (int c = 0; c < m_channels; c++) {
QPoint textLoc(0, 0);
QPoint lineBegin(m_graphLeftPadding, 0);
QPoint lineEnd(size.width() - 1, 0);
int y = 0;
y = graphBottomY(size, c, m_channels, m_graphTopPadding);
textLoc.setY(y + labelHeight / 2);
textLoc.setX((m_graphLeftPadding - fm.horizontalAdvance(zeroLabel)) / 2);
p.drawText( textLoc, zeroLabel );
lineBegin.setY(y);
lineEnd.setY(y);
p.drawLine(lineBegin, lineEnd);
y = graphCenterY(size, c, m_channels, m_graphTopPadding);
textLoc.setY(y + labelHeight / 2);
textLoc.setX((m_graphLeftPadding - fm.horizontalAdvance(infinityLabel)) / 2);
p.drawText( textLoc, infinityLabel );
lineBegin.setY(y);
lineEnd.setY(y);
p.drawLine(lineBegin, lineEnd);
y = graphTopY(size, c, m_channels, m_graphTopPadding);
textLoc.setY(y + labelHeight / 2);
textLoc.setX((m_graphLeftPadding - fm.horizontalAdvance(zeroLabel)) / 2);
p.drawText( textLoc, zeroLabel );
lineBegin.setY(y);
lineEnd.setY(y);
p.drawLine(lineBegin, lineEnd);
}
p.end();
m_mutex.unlock();
}
void AudioWaveformScopeWidget::paintEvent(QPaintEvent *)
{
if (!isVisible())
return;
QPainter p(this);
m_mutex.lock();
p.drawImage(rect(), m_displayGrid, m_displayGrid.rect());
p.drawImage(rect(), m_displayWave, m_displayWave.rect());
m_mutex.unlock();
if (m_cursorPos > -1) {
p.setPen(palette().text().color().rgb());
p.drawLine(m_cursorPos, 0, m_cursorPos, height());
}
p.end();
}
void AudioWaveformScopeWidget::mouseMoveEvent(QMouseEvent *event)
{
QMutexLocker locker(&m_mutex);
if (!m_frame.is_valid()) return;
int channels = m_frame.get_audio_channels();
int samples = m_frame.get_audio_samples();
int16_t *audio = (int16_t *)m_frame.get_audio();
if (samples < 10 || channels < 1) return;
qreal position = (qreal)event->pos().x() / (qreal)width();
int sample = (qreal)samples * position;
QString text = tr("Sample: %1\n").arg(sample + 1);
for (int c = 0; c < channels; c++) {
const int16_t *q = audio + (channels * sample) + c;
qreal scaledValue = (qreal) * q / MAX_AMPLITUDE;
qreal dbValue = 20 * log(fabs(scaledValue));
if (dbValue < 0.01 && dbValue > -0.01) dbValue = 0.0;
text += tr("Ch: %1: %2 (%3 dBFS)").arg(c + 1).arg(scaledValue, 0, 'f', 2)
.arg(dbValue, 0, 'f', 2);
if ( c != channels - 1 ) {
text += "\n";
}
}
locker.unlock();
m_cursorPos = event->pos().x();
QToolTip::showText(event->globalPosition().toPoint(), text);
update();
}
void AudioWaveformScopeWidget::leaveEvent(QEvent *event)
{
Q_UNUSED(event);
m_cursorPos = -1;
update();
}
QString AudioWaveformScopeWidget::getTitle()
{
return tr("Audio Waveform");
}
| 9,110
|
C++
|
.cpp
| 248
| 29.604839
| 99
| 0.60803
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,248
|
videowaveformscopewidget.cpp
|
mltframework_shotcut/src/widgets/scopes/videowaveformscopewidget.cpp
|
/*
* Copyright (c) 2015-2022 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "videowaveformscopewidget.h"
#include <Logger.h>
#include <QMouseEvent>
#include <QPainter>
#include <QToolTip>
static const qreal IRE0 = 16;
static const qreal IRE100 = 235;
static const QColor TEXT_COLOR = {255, 255, 255, 127};
VideoWaveformScopeWidget::VideoWaveformScopeWidget()
: ScopeWidget("VideoWaveform")
, m_frame()
, m_renderImg()
, m_mutex()
, m_displayImg()
{
LOG_DEBUG() << "begin";
setMouseTracking(true);
LOG_DEBUG() << "end";
}
void VideoWaveformScopeWidget::refreshScope(const QSize &size, bool full)
{
Q_UNUSED(size)
Q_UNUSED(full)
while (m_queue.count() > 0) {
m_frame = m_queue.pop();
}
int width = m_frame.get_image_width();
int height = m_frame.get_image_height();
if (m_frame.is_valid() && width && height) {
if (m_renderImg.width() != width) {
m_renderImg = QImage(width, 256, QImage::Format_RGBX8888);
}
QColor bgColor( 0, 0, 0, 0xff );
m_renderImg.fill(bgColor);
const uint8_t *src = m_frame.get_image(mlt_image_yuv420p);
uint8_t *dst = m_renderImg.scanLine(0);
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
uint8_t dy = 255 - src[0];
size_t dIndex = (dy * width + x) * 4;
if (dst[dIndex] < 0xff) {
dst[dIndex] += 0x0f;
dst[dIndex + 1] += 0x0f;
dst[dIndex + 2] += 0x0f;
}
src ++;
}
}
QImage scaledImage = m_renderImg.scaled(size, Qt::IgnoreAspectRatio,
Qt::SmoothTransformation).convertToFormat(QImage::Format_RGB32);
m_mutex.lock();
m_displayImg.swap(scaledImage);
m_mutex.unlock();
}
}
void VideoWaveformScopeWidget::paintEvent(QPaintEvent *)
{
if (!isVisible())
return;
// Create the painter
QPainter p(this);
p.setRenderHint(QPainter::Antialiasing, true);
QFont font = QWidget::font();
int fontSize = font.pointSize() - (font.pointSize() > 10 ? 2 : (font.pointSize() > 8 ? 1 : 0));
font.setPointSize(fontSize);
QFontMetrics fm(font);
QPen pen;
pen.setColor(TEXT_COLOR);
pen.setWidth(qRound(devicePixelRatioF()));
p.setPen(pen);
p.setFont(font);
// draw the waveform data
m_mutex.lock();
if (!m_displayImg.isNull()) {
p.drawImage(rect(), m_displayImg, m_displayImg.rect());
} else {
p.fillRect(rect(), QBrush(Qt::black, Qt::SolidPattern));
}
m_mutex.unlock();
// Add IRE lines
int textpad = 3;
// 100
qreal ire100y = height() - (height() * IRE100 / 255);
p.drawLine(QPointF(0, ire100y), QPointF(width(), ire100y));
p.drawText(textpad, ire100y - textpad, tr("100"));
// 0
qreal ire0y = height() - (height() * IRE0 / 255);
p.drawLine(QPointF(0, ire0y), QPointF(width(), ire0y));
QRect textRect = fm.tightBoundingRect(tr("0"));
p.drawText(textpad, ire0y + textRect.height() + textpad, tr("0"));
p.end();
}
void VideoWaveformScopeWidget::mouseMoveEvent(QMouseEvent *event)
{
QString text;
qreal ire100y = height() - (height() * IRE100 / 255);
qreal ire0y = height() - (height() * IRE0 / 255);
qreal ireStep = (ire0y - ire100y) / 100.0;
int ire = (ire0y - event->pos().y()) / ireStep;
m_mutex.lock();
int frameWidth = m_displayImg.width();
m_mutex.unlock();
if (frameWidth != 0) {
int pixel = frameWidth * event->pos().x() / width();
text = tr("Pixel: %1\nIRE: %2").arg(pixel).arg(ire);
} else {
text = tr("IRE: %1").arg(ire);
}
QToolTip::showText(event->globalPosition().toPoint(), text);
}
QString VideoWaveformScopeWidget::getTitle()
{
return tr("Video Waveform");
}
| 4,566
|
C++
|
.cpp
| 130
| 29.092308
| 112
| 0.613868
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,249
|
videozoomscopewidget.cpp
|
mltframework_shotcut/src/widgets/scopes/videozoomscopewidget.cpp
|
/*
* Copyright (c) 2019-2023 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "videozoomscopewidget.h"
#include "videowidget.h"
#include "videozoomwidget.h"
#include <QLabel>
#include <QToolButton>
#include <QToolTip>
#include <QGridLayout>
#include <QHBoxLayout>
#include <math.h>
QWidget *getSeparator()
{
// Create a 1 pixel wide line separator with a contrasting color
QWidget *separator = new QWidget();
separator->setGeometry(0, 0, 300, 300);
separator->setMinimumSize(1, 1);
QPalette pal = separator->palette();
// pal.setColor(QPalette::Background, pal.color(QPalette::WindowText));
separator->setAutoFillBackground(true);
separator->setPalette(pal);
return separator;
}
QRect getPlayerBoundingRect(Mlt::VideoWidget *videoWidget)
{
// Get the global rectangle of the player that contains image.
// This function assumes that the player is zoomed to best fit the image
// so that all of the image is available and it fills the widget in one
// direction.
QRect rect;
double widgetAr = (double)videoWidget->width() / (double)videoWidget->height();
double vidAr = MLT.profile().dar();
if (widgetAr > vidAr) {
double width = (double)videoWidget->height() * vidAr;
rect.setX((round((double)videoWidget->width() - width) / 2));
rect.setY(0);
rect.setWidth(round(width));
rect.setHeight(videoWidget->height());
} else {
double height = videoWidget->width() / vidAr;
rect.setX(0);
rect.setY((round((double)videoWidget->height() - height) / 2));
rect.setWidth(videoWidget->width());
rect.setHeight(round(height));
}
return QRect(videoWidget->mapToGlobal(rect.topLeft()), rect.size());
}
QPoint pixelToPlayerPos(const QRect &playerRect, const QPoint &pixel)
{
// Convert a pixel index to the corresponding global screen position of that
// pixel in the player.
double xOffset = (double)playerRect.width() * (double)pixel.x() / (double)MLT.profile().width();
double yOffset = (double)playerRect.height() * (double)pixel.y() / (double)MLT.profile().height();
return playerRect.topLeft() + QPoint(round(xOffset), round(yOffset));
}
QPoint playerPosToPixel(const QRect &playerRect, const QPoint &pos)
{
// Convert the global position of a point in the player to the corresponding
// pixel index.
QPoint offset = pos - playerRect.topLeft();
double xOffset = (double)MLT.profile().width() * (double)offset.x() / (double)playerRect.width();
double yOffset = (double)MLT.profile().height() * (double)offset.y() / (double)playerRect.height();
return QPoint(round(xOffset), round(yOffset));
}
VideoZoomScopeWidget::VideoZoomScopeWidget()
: ScopeWidget("VideoZoom")
, m_zoomWidget(new VideoZoomWidget())
, m_zoomLabel(new QLabel(this))
, m_pixelXLabel(new QLabel(this))
, m_pixelYLabel(new QLabel(this))
, m_rLabel(new QLabel(this))
, m_gLabel(new QLabel(this))
, m_bLabel(new QLabel(this))
, m_yLabel(new QLabel(this))
, m_uLabel(new QLabel(this))
, m_vLabel(new QLabel(this))
, m_lockButton(new QToolButton(this))
{
LOG_DEBUG() << "begin";
QFont font = QWidget::font();
int fontSize = font.pointSize() - (font.pointSize() > 10 ? 2 : (font.pointSize() > 8 ? 1 : 0));
font.setPointSize(fontSize);
QWidget::setFont(font);
QHBoxLayout *hlayout = new QHBoxLayout(this);
hlayout->setContentsMargins(0, 0, 0, 0);
hlayout->setSpacing(0);
QGridLayout *glayout = new QGridLayout();
glayout->setContentsMargins(5, 5, 2, 0);
glayout->setHorizontalSpacing(0);
glayout->setVerticalSpacing(2);
// Add labels
glayout->addWidget(m_zoomLabel, 0, 0, 1, 2);
glayout->addWidget(getSeparator(), 1, 0, 1, 2);
glayout->addWidget(new QLabel(tr("x")), 2, 0, Qt::AlignLeft);
glayout->addWidget(m_pixelXLabel, 2, 1, Qt::AlignRight);
glayout->addWidget(new QLabel(tr("y")), 3, 0, Qt::AlignLeft);
glayout->addWidget(m_pixelYLabel, 3, 1, Qt::AlignRight);
glayout->addWidget(getSeparator(), 4, 0, 1, 2);
glayout->addWidget(new QLabel(tr("R")), 5, 0, Qt::AlignLeft);
glayout->addWidget(m_rLabel, 5, 1, Qt::AlignRight);
glayout->addWidget(new QLabel(tr("G")), 6, 0, Qt::AlignLeft);
glayout->addWidget(m_gLabel, 6, 1, Qt::AlignRight);
glayout->addWidget(new QLabel(tr("B")), 7, 0, Qt::AlignLeft);
glayout->addWidget(m_bLabel, 7, 1, Qt::AlignRight);
glayout->addWidget(getSeparator(), 8, 0, 1, 2);
glayout->addWidget(new QLabel(tr("Y")), 9, 0, Qt::AlignLeft);
glayout->addWidget(m_yLabel, 9, 1, Qt::AlignRight);
glayout->addWidget(new QLabel(tr("U")), 10, 0, Qt::AlignLeft);
glayout->addWidget(m_uLabel, 10, 1, Qt::AlignRight);
glayout->addWidget(new QLabel(tr("V")), 11, 0, Qt::AlignLeft);
glayout->addWidget(m_vLabel, 11, 1, Qt::AlignRight);
glayout->addItem(new QSpacerItem(0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding), 12, 0, 1, 2);
updateLabels();
onZoomChanged(m_zoomWidget->getZoom());
// Add HBoxLayout for tool buttons
QHBoxLayout *toolLayout = new QHBoxLayout();
toolLayout->setContentsMargins(0, 0, 0, 0);
toolLayout->setSpacing(0);
glayout->addLayout(toolLayout, 13, 0, 1, 2);
// Add pixel picker button
QToolButton *pickButton = new QToolButton(this);
pickButton->setToolTip(tr("Pick a pixel from the source player"));
pickButton->setIcon(QIcon::fromTheme("zoom-select",
QIcon(":/icons/oxygen/32x32/actions/zoom-select")));
toolLayout->addWidget(pickButton);
connect(pickButton, SIGNAL(clicked()), this, SLOT(onScreenSelectStarted()));
// Add pixel lock button
m_lockButton->setToolTip(tr("Lock/Unlock the selected pixel"));
m_lockButton->setIcon(QIcon::fromTheme("object-unlocked",
QIcon(":/icons/oxygen/32x32/status/object-unlocked")));
m_lockButton->setCheckable(true);
m_lockButton->setChecked(false);
toolLayout->addWidget(m_lockButton);
connect(m_lockButton, SIGNAL(toggled(bool)), this, SLOT(onLockToggled(bool)));
toolLayout->addStretch();
// Set minimum size for the grid layout.
QRect col1Size = fontMetrics().boundingRect("X ");
glayout->setColumnMinimumWidth(0, col1Size.width());
QRect col2Size = fontMetrics().boundingRect("9999");
glayout->setColumnMinimumWidth(1, col2Size.width());
hlayout->addLayout(glayout);
hlayout->addWidget(m_zoomWidget);
connect(m_zoomWidget, SIGNAL(pixelSelected(const QPoint &)), this,
SLOT(onPixelSelected(const QPoint &)));
connect(m_zoomWidget, SIGNAL(zoomChanged(int)), this, SLOT(onZoomChanged(int)));
connect(&m_selector, SIGNAL(screenSelected(const QRect &)), this,
SLOT(onScreenRectSelected(const QRect &)));
connect(&m_selector, SIGNAL(pointSelected(const QPoint &)), this,
SLOT(onScreenPointSelected(const QPoint &)));
LOG_DEBUG() << "end";
}
void VideoZoomScopeWidget::onScreenSelectStarted()
{
if (!MLT.producer() || !MLT.producer()->is_valid()) {
return;
}
auto *videoWidget = qobject_cast<Mlt::VideoWidget *>(MLT.videoWidget());
// Toggle the zoom off on the player so that the entire image is displayed
// in the player. The user can toggle it back on if they want.
videoWidget->toggleZoom(false);
// Get the global rectangle in the player that has the image in it.
QRect boundingRect = getPlayerBoundingRect(videoWidget);
m_selector.setBoundingRect(boundingRect);
// Calculate the size of the zoom window to show over the image.
QSize selectionSize;
selectionSize.setWidth((double)boundingRect.width() * (((double)m_zoomWidget->width() /
(double)m_zoomWidget->getZoom()) / (double)MLT.profile().width()));
selectionSize.setHeight((double)boundingRect.height() * (((double)m_zoomWidget->height() /
(double)m_zoomWidget->getZoom()) / (double)MLT.profile().height()));
m_selector.setFixedSize(selectionSize);
// Calculate the global position of the zoom window.
QRect zoomRect = m_zoomWidget->getPixelRect();
QRect selectedRect;
selectedRect.setTopLeft(pixelToPlayerPos(boundingRect, zoomRect.topLeft()));
selectedRect.setBottomRight(pixelToPlayerPos(boundingRect, zoomRect.bottomRight()));
m_selector.setSelectedRect(selectedRect);
// Calculate the global position of the selected pixel.
QPoint startPoint = pixelToPlayerPos(boundingRect, m_zoomWidget->getSelectedPixel());
m_selector.startSelection(startPoint);
}
void VideoZoomScopeWidget::onLockToggled(bool enabled)
{
m_zoomWidget->lock(enabled);
if (enabled) {
m_lockButton->setIcon(QIcon::fromTheme("object-locked",
QIcon(":/icons/oxygen/32x32/status/object-locked")));
} else {
m_lockButton->setIcon(QIcon::fromTheme("object-unlocked",
QIcon(":/icons/oxygen/32x32/status/object-unlocked")));
}
}
void VideoZoomScopeWidget::onScreenRectSelected(const QRect &rect)
{
auto *videoWidget = qobject_cast<Mlt::VideoWidget *>(MLT.videoWidget());
QRect boundingRect = getPlayerBoundingRect(videoWidget);
QPoint pixel = playerPosToPixel(boundingRect, rect.topLeft());
m_zoomWidget->setOffset(pixel);
}
void VideoZoomScopeWidget::onScreenPointSelected(const QPoint &point)
{
auto *videoWidget = qobject_cast<Mlt::VideoWidget *>(MLT.videoWidget());
QRect boundingRect = getPlayerBoundingRect(videoWidget);
QPoint pixel = playerPosToPixel(boundingRect, point);
m_zoomWidget->setSelectedPixel(pixel);
}
void VideoZoomScopeWidget::onPixelSelected(const QPoint &pixel)
{
Q_UNUSED(pixel);
updateLabels();
}
void VideoZoomScopeWidget::onZoomChanged(int zoom)
{
m_zoomLabel->setText(tr("%1x").arg(zoom));
}
void VideoZoomScopeWidget::refreshScope(const QSize &size, bool full)
{
Q_UNUSED(size)
Q_UNUSED(full)
SharedFrame frame;
while (m_queue.count() > 0) {
frame = m_queue.pop();
}
if (frame.is_valid()) {
m_zoomWidget->putFrame(frame);
QMetaObject::invokeMethod(this, "updateLabels", Qt::QueuedConnection);
}
}
void VideoZoomScopeWidget::updateLabels()
{
QPoint selectedPixel = m_zoomWidget->getSelectedPixel();
if (selectedPixel.x() >= 0) {
VideoZoomWidget::PixelValues values = m_zoomWidget->getPixelValues(selectedPixel);
m_pixelXLabel->setText(QString::number(selectedPixel.x() + 1));
m_pixelYLabel->setText(QString::number(selectedPixel.y() + 1));
m_rLabel->setText(QString::number(values.r));
m_gLabel->setText(QString::number(values.g));
m_bLabel->setText(QString::number(values.b));
m_yLabel->setText(QString::number(values.y));
m_uLabel->setText(QString::number(values.u));
m_vLabel->setText(QString::number(values.v));
} else {
m_pixelXLabel->setText("");
m_pixelYLabel->setText("");
m_rLabel->setText("---");
m_gLabel->setText("---");
m_bLabel->setText("---");
m_yLabel->setText("---");
m_uLabel->setText("---");
m_vLabel->setText("---");
}
}
QString VideoZoomScopeWidget::getTitle()
{
return tr("Video Zoom");
}
| 12,098
|
C++
|
.cpp
| 269
| 39.189591
| 130
| 0.680658
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,250
|
videozoomwidget.cpp
|
mltframework_shotcut/src/widgets/scopes/videozoomwidget.cpp
|
/*
* Copyright (c) 2019-2023 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "videozoomwidget.h"
#include <Logger.h>
#include <QMouseEvent>
#include <QMutexLocker>
#include <QPainter>
#include <QToolTip>
const int MIN_ZOOM = 2;
const int MAX_ZOOM = 20;
const int DEFAULT_ZOOM = 10;
QColor getHighContrastColor(const QColor &color)
{
if (color.value() > 128 ) {
return QColor(Qt::black);
}
return QColor(Qt::white);
}
VideoZoomWidget::VideoZoomWidget()
: m_locked(false)
, m_zoom(DEFAULT_ZOOM)
, m_imageOffset(0, 0)
, m_mouseGrabPixel(0, 0)
, m_selectedPixel(-1, -1)
, m_mutex()
, m_frame()
{
LOG_DEBUG() << "begin";
setMouseTracking(true);
LOG_DEBUG() << "end";
}
void VideoZoomWidget::putFrame(SharedFrame frame)
{
if (!frame.is_valid()) return;
// Make sure the images are pre-cached for the UI thread
frame.get_image(mlt_image_yuv420p);
frame.get_image(mlt_image_rgb);
m_mutex.lock();
m_frame = frame;
m_mutex.unlock();
update();
}
QPoint VideoZoomWidget::getSelectedPixel()
{
return m_selectedPixel;
}
void VideoZoomWidget::setSelectedPixel(QPoint pixel)
{
QMutexLocker locker(&m_mutex);
if (!m_frame.is_valid()) return;
if (pixel.x() < 0) return;
if (pixel.x() >= m_frame.get_image_width()) return;
if (pixel.y() < 0) return;
if (pixel.y() >= m_frame.get_image_height()) return;
m_selectedPixel = pixel;
update();
locker.unlock();
emit pixelSelected(m_selectedPixel);
}
QRect VideoZoomWidget::getPixelRect()
{
return QRect(m_imageOffset, QSize(width() / m_zoom, height() / m_zoom));
}
int VideoZoomWidget::getZoom()
{
return m_zoom;
}
VideoZoomWidget::PixelValues VideoZoomWidget::getPixelValues(const QPoint &pixel)
{
QMutexLocker locker(&m_mutex);
return pixelToValues(pixel);
}
void VideoZoomWidget::setOffset(QPoint offset)
{
QMutexLocker locker(&m_mutex);
if (!m_frame.is_valid()) return;
if (offset.x() < 0) return;
if (offset.x() >= m_frame.get_image_width()) return;
if (offset.y() < 0) return;
if (offset.y() >= m_frame.get_image_height()) return;
m_imageOffset = offset;
update();
}
void VideoZoomWidget::lock(bool locked)
{
m_locked = locked;
}
QSize VideoZoomWidget::sizeHint() const
{
return QSize(400, 400);
}
void VideoZoomWidget::paintEvent(QPaintEvent *)
{
if (!isVisible()) return;
QMutexLocker locker(&m_mutex);
if (!m_frame.is_valid()) return;
// Create the painter
QPainter p(this);
p.setRenderHint(QPainter::Antialiasing, true);
const uint8_t *pImg = m_frame.get_image(mlt_image_rgb);
int iWidth = m_frame.get_image_width();
int iHeight = m_frame.get_image_height();
int wWidth = width() - (width() % m_zoom);
int wHeight = height() - (height() % m_zoom);
int ix = m_imageOffset.x();
int iy = m_imageOffset.y();
// draw the pixels
for (int y = 0; y < wHeight && iy < iHeight; y += m_zoom) {
const uint8_t *pPixel = pImg + ((iy * iWidth) + ix) * 3;
for (int x = 0; x < wWidth; x += m_zoom) {
p.fillRect(x, y, m_zoom, m_zoom, QColor(pPixel[0], pPixel[1], pPixel[2], 255 ));
pPixel += 3;
}
iy++;
}
// Outline the selected pixel
if (m_selectedPixel.x() >= 0 &&
m_selectedPixel.y() >= 0 &&
m_selectedPixel.x() < iWidth &&
m_selectedPixel.y() < iHeight) {
const uint8_t *pPixel = pImg + ((m_selectedPixel.y() * iWidth) + m_selectedPixel.x()) * 3;
int posX = (m_selectedPixel.x() - m_imageOffset.x()) * m_zoom;
int posY = (m_selectedPixel.y() - m_imageOffset.y()) * m_zoom;
QColor pixelcolor(pPixel[0], pPixel[1], pPixel[2]);
p.setPen(getHighContrastColor(pixelcolor));
p.drawRect(posX, posY, m_zoom, m_zoom);
}
}
void VideoZoomWidget::mouseMoveEvent(QMouseEvent *event)
{
QMutexLocker locker(&m_mutex);
if (!m_frame.is_valid()) return;
int iWidth = m_frame.get_image_width();
int iHeight = m_frame.get_image_height();
QPoint currMousePixel = posToPixel(event->pos());
if (currMousePixel.x() < 0) return;
if (currMousePixel.x() >= iWidth) return;
if (currMousePixel.y() < 0) return;
if (currMousePixel.y() >= iHeight) return;
locker.unlock();
if (event->buttons() & Qt::LeftButton) {
if (currMousePixel != m_mouseGrabPixel) {
int maxOffsetX = iWidth - (width() / m_zoom);
int maxOffsetY = iHeight - (height() / m_zoom);
// Calculate the new image offset
QPoint newImageOffset;
newImageOffset.setX((int)m_mouseGrabPixel.x() - ((int)event->pos().x() / m_zoom));
newImageOffset.setX(qBound(0, newImageOffset.x(), maxOffsetX));
newImageOffset.setY((int)m_mouseGrabPixel.y() - ((int)event->pos().y() / m_zoom));
newImageOffset.setY(qBound(0, newImageOffset.y(), maxOffsetY));
// Apply the offset if it has changed
if (newImageOffset != m_imageOffset) {
m_imageOffset = newImageOffset;
}
}
} else if (!m_locked) {
m_selectedPixel = currMousePixel;
emit pixelSelected(m_selectedPixel);
}
/*
// Create a tool tip to display pixel information
PixelValues values = pixelToValues(currMousePixel);
QString text = tr("Zoom: %1x\nPixel: %2,%3\nRGB: %4 %5 %6\nYUV: %7 %8 %9").arg(
QString::number(m_zoom)).arg(
QString::number(currMousePixel.x() + 1)).arg(
QString::number(currMousePixel.y() + 1)).arg(
QString::number(values.r)).arg(
QString::number(values.g)).arg(
QString::number(values.b)).arg(
QString::number(values.y)).arg(
QString::number(values.u)).arg(
QString::number(values.v));
QToolTip::showText(event->globalPos(), text);
*/
update();
}
void VideoZoomWidget::mousePressEvent(QMouseEvent *event)
{
if (event->buttons() & Qt::LeftButton) {
QMutexLocker locker(&m_mutex);
if (!m_frame.is_valid()) return;
QPoint currMousePixel = posToPixel(event->pos());
m_selectedPixel = currMousePixel;
m_mouseGrabPixel = currMousePixel;
locker.unlock();
emit pixelSelected(m_selectedPixel);
update();
}
}
void VideoZoomWidget::wheelEvent(QWheelEvent *event)
{
QMutexLocker locker(&m_mutex);
if (!m_frame.is_valid()) return;
QPoint steps = event->angleDelta() / 8 / 15;
int newZoom = qBound(MIN_ZOOM, m_zoom + steps.y(), MAX_ZOOM);
if (newZoom != m_zoom) {
// Zoom in on the center pixel.
int iWidth = m_frame.get_image_width();
int iHeight = m_frame.get_image_height();
int maxOffsetX = iWidth - (width() / newZoom);
int maxOffsetY = iHeight - (height() / newZoom);
QPoint centerPixel = posToPixel(rect().center());
m_imageOffset.setX(centerPixel.x() - (width() / newZoom / 2));
m_imageOffset.setX(qBound(0, m_imageOffset.x(), maxOffsetX));
m_imageOffset.setY(centerPixel.y() - (height() / newZoom / 2));
m_imageOffset.setY(qBound(0, m_imageOffset.y(), maxOffsetY));
m_zoom = newZoom;
locker.unlock();
emit zoomChanged(m_zoom);
update();
}
if (locker.isLocked())
locker.unlock();
event->accept();
}
QPoint VideoZoomWidget::pixelToPos(const QPoint &pixel)
{
int x = ((int)pixel.x() - (int)m_imageOffset.x()) * m_zoom;
int y = ((int)pixel.y() - (int)m_imageOffset.y()) * m_zoom;
return QPoint(x, y);
}
QPoint VideoZoomWidget::posToPixel(const QPoint &pos)
{
int x = ((int)pos.x() / m_zoom) + (int)m_imageOffset.x();
int y = ((int)pos.y() / m_zoom) + (int)m_imageOffset.y();
return QPoint(x, y);
}
VideoZoomWidget::PixelValues VideoZoomWidget::pixelToValues(const QPoint &pixel)
{
PixelValues values;
int iWidth = m_frame.get_image_width();
int iHeight = m_frame.get_image_height();
int imageOffset = iWidth * pixel.y() + pixel.x();
const uint8_t *pRgb = m_frame.get_image(mlt_image_rgb) + imageOffset * 3;
const uint8_t *pYuv = m_frame.get_image(mlt_image_yuv420p);
const uint8_t *pY = pYuv + imageOffset;
const uint8_t *pU = pYuv + (iWidth * iHeight) + (iWidth / 2 * (pixel.y() / 2)) + (pixel.x() / 2);
const uint8_t *pV = pYuv + (iWidth * iHeight * 5 / 4) + (iWidth / 2 * (pixel.y() / 2)) +
(pixel.x() / 2);
values.y = *pY;
values.u = *pU;
values.v = *pV;
values.r = pRgb[0];
values.g = pRgb[1];
values.b = pRgb[2];
return values;
}
| 9,478
|
C++
|
.cpp
| 261
| 30.237548
| 101
| 0.617605
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,251
|
audioloudnessscopewidget.cpp
|
mltframework_shotcut/src/widgets/scopes/audioloudnessscopewidget.cpp
|
/*
* Copyright (c) 2016-2023 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "audioloudnessscopewidget.h"
#include <Logger.h>
#include <QVBoxLayout>
#include <QQmlEngine>
#include <QDir>
#include <QQuickWidget>
#include <QQuickItem>
#include <QPushButton>
#include <QToolButton>
#include <QMenu>
#include <QLabel>
#include <QTimer>
#include <MltProfile.h>
#include <math.h>
#include "qmltypes/qmlutilities.h"
#include "mltcontroller.h"
#include "settings.h"
static double onedec( double in )
{
return round( in * 10.0 ) / 10.0;
}
AudioLoudnessScopeWidget::AudioLoudnessScopeWidget()
: ScopeWidget("AudioLoudnessMeter")
, m_loudnessFilter(0)
, m_peak(-100)
, m_true_peak(-100)
, m_newData(false)
, m_orientation((Qt::Orientation) - 1)
, m_qview(new QQuickWidget(QmlUtilities::sharedEngine(), this))
, m_timeLabel(new QLabel(this))
{
LOG_DEBUG() << "begin";
m_loudnessFilter = new Mlt::Filter(MLT.profile(), "loudness_meter");
m_loudnessFilter->set("calc_program", Settings.loudnessScopeShowMeter("integrated"));
m_loudnessFilter->set("calc_shortterm", Settings.loudnessScopeShowMeter("shortterm"));
m_loudnessFilter->set("calc_momentary", Settings.loudnessScopeShowMeter("momentary"));
m_loudnessFilter->set("calc_range", Settings.loudnessScopeShowMeter("range"));
m_loudnessFilter->set("calc_peak", Settings.loudnessScopeShowMeter("peak"));
m_loudnessFilter->set("calc_true_peak", Settings.loudnessScopeShowMeter("truepeak"));
setAutoFillBackground(true);
// Use a timer to update the meters for two reasons:
// 1) The spec requires 10Hz updates
// 2) Minimize QML GUI updates
m_timer = new QTimer(this);
connect(m_timer, SIGNAL(timeout()), this, SLOT(updateMeters()));
m_timer->start(100);
m_qview->setFocusPolicy(Qt::StrongFocus);
QmlUtilities::setCommonProperties(m_qview->rootContext());
QVBoxLayout *vlayout = new QVBoxLayout(this);
vlayout->setContentsMargins(4, 4, 4, 4);
vlayout->addWidget(m_qview);
QHBoxLayout *hlayout = new QHBoxLayout();
vlayout->addLayout(hlayout);
// Create config menu
QMenu *configMenu = new QMenu(this);
QAction *action;
action = configMenu->addAction(tr("Momentary Loudness"), this, SLOT(onMomentaryToggled(bool)));
action->setCheckable(true);
action->setChecked(Settings.loudnessScopeShowMeter("momentary"));
action = configMenu->addAction(tr("Short Term Loudness"), this, SLOT(onShorttermToggled(bool)));
action->setCheckable(true);
action->setChecked(Settings.loudnessScopeShowMeter("shortterm"));
action = configMenu->addAction(tr("Integrated Loudness"), this, SLOT(onIntegratedToggled(bool)));
action->setCheckable(true);
action->setChecked(Settings.loudnessScopeShowMeter("integrated"));
action = configMenu->addAction(tr("Loudness Range"), this, SLOT(onRangeToggled(bool)));
action->setCheckable(true);
action->setChecked(Settings.loudnessScopeShowMeter("range"));
action = configMenu->addAction(tr("Peak"), this, SLOT(onPeakToggled(bool)));
action->setCheckable(true);
action->setChecked(Settings.loudnessScopeShowMeter("peak"));
action = configMenu->addAction(tr("True Peak"), this, SLOT(onTruePeakToggled(bool)));
action->setCheckable(true);
action->setChecked(Settings.loudnessScopeShowMeter("truepeak"));
// Add config button
QToolButton *configButton = new QToolButton(this);
configButton->setToolTip(tr("Configure Graphs"));
configButton->setIcon(QIcon::fromTheme("show-menu",
QIcon(":/icons/oxygen/32x32/actions/show-menu.png")));
configButton->setPopupMode(QToolButton::InstantPopup);
configButton->setMenu(configMenu);
hlayout->addWidget(configButton);
// Add reset button
QPushButton *resetButton = new QPushButton(tr("Reset"), this);
resetButton->setToolTip(tr("Reset the measurement."));
resetButton->setCheckable(false);
resetButton->setMaximumWidth(100);
hlayout->addWidget(resetButton);
connect(resetButton, SIGNAL(clicked()), this, SLOT(onResetButtonClicked()));
// Add time label
m_timeLabel->setToolTip(tr("Time Since Reset"));
m_timeLabel->setText("00:00:00:00");
m_timeLabel->setFixedSize(this->fontMetrics().horizontalAdvance("HH:MM:SS:MM"),
this->fontMetrics().height());
hlayout->addWidget(m_timeLabel);
hlayout->addStretch();
QTimer::singleShot(300, this, &AudioLoudnessScopeWidget::resetQview);
connect(this, &ScopeWidget::moved, this, &AudioLoudnessScopeWidget::resetQview);
LOG_DEBUG() << "end";
}
AudioLoudnessScopeWidget::~AudioLoudnessScopeWidget()
{
m_timer->stop();
delete m_loudnessFilter;
}
void AudioLoudnessScopeWidget::refreshScope(const QSize & /*size*/, bool /*full*/)
{
SharedFrame sFrame;
while (m_queue.count() > 0) {
sFrame = m_queue.pop();
if (sFrame.is_valid() && sFrame.get_audio_samples() > 0) {
mlt_audio_format format = mlt_audio_f32le;
int channels = sFrame.get_audio_channels();
int frequency = sFrame.get_audio_frequency();
int samples = sFrame.get_audio_samples();
if (channels && frequency && samples) {
Mlt::Frame mFrame = sFrame.clone(true, false, false);
m_loudnessFilter->process(mFrame);
mFrame.get_audio(format, frequency, channels, samples);
if ( m_peak < m_loudnessFilter->get_double("peak") ) {
m_peak = m_loudnessFilter->get_double("peak");
}
if ( m_true_peak < m_loudnessFilter->get_double("true_peak") ) {
m_true_peak = m_loudnessFilter->get_double("true_peak");
}
m_newData = true;
}
}
}
// Update the time with every frame.
QString time = m_loudnessFilter->get_time("frames_processed");
QMetaObject::invokeMethod(m_timeLabel, "setText", Qt::QueuedConnection, Q_ARG(const QString &,
time));
}
QString AudioLoudnessScopeWidget::getTitle()
{
return tr("Audio Loudness");
}
void AudioLoudnessScopeWidget::setOrientation(Qt::Orientation orientation)
{
setOrientation(orientation, false);
}
void AudioLoudnessScopeWidget::setOrientation(Qt::Orientation orientation, bool force)
{
if (force || orientation != m_orientation) {
if (orientation == Qt::Vertical) {
// Calculate the minimum width
int x = 0;
const int meterWidth = 54;
if (Settings.loudnessScopeShowMeter("momentary")) x += meterWidth;
if (Settings.loudnessScopeShowMeter("shortterm")) x += meterWidth;
if (Settings.loudnessScopeShowMeter("integrated")) x += meterWidth;
if (Settings.loudnessScopeShowMeter("range")) x += meterWidth;
if (Settings.loudnessScopeShowMeter("peak")) x += meterWidth;
if (Settings.loudnessScopeShowMeter("truepeak")) x += meterWidth;
x = std::max(x, 200);
setMinimumSize(x, 250);
setMaximumSize(x, 600);
} else {
// Calculate the minimum height
int y = 32;
const int meterHeight = 47;
if (Settings.loudnessScopeShowMeter("momentary")) y += meterHeight;
if (Settings.loudnessScopeShowMeter("shortterm")) y += meterHeight;
if (Settings.loudnessScopeShowMeter("integrated")) y += meterHeight;
if (Settings.loudnessScopeShowMeter("range")) y += meterHeight;
if (Settings.loudnessScopeShowMeter("peak")) y += meterHeight;
if (Settings.loudnessScopeShowMeter("truepeak")) y += meterHeight;
y = std::max(y, 80);
setMinimumSize(250, y);
setMaximumSize(600, y);
}
updateGeometry();
m_orientation = orientation;
resetQview();
}
}
void AudioLoudnessScopeWidget::onResetButtonClicked()
{
m_loudnessFilter->set("reset", 1);
m_timeLabel->setText( "00:00:00:00" );
setOrientation(m_orientation, true);
resetQview();
}
void AudioLoudnessScopeWidget::onIntegratedToggled(bool checked)
{
m_loudnessFilter->set("calc_program", checked);
Settings.setLoudnessScopeShowMeter("integrated", checked);
setOrientation(m_orientation, true);
resetQview();
}
void AudioLoudnessScopeWidget::onShorttermToggled(bool checked)
{
m_loudnessFilter->set("calc_shortterm", checked);
Settings.setLoudnessScopeShowMeter("shortterm", checked);
setOrientation(m_orientation, true);
resetQview();
}
void AudioLoudnessScopeWidget::onMomentaryToggled(bool checked)
{
m_loudnessFilter->set("calc_momentary", checked);
Settings.setLoudnessScopeShowMeter("momentary", checked);
setOrientation(m_orientation, true);
resetQview();
}
void AudioLoudnessScopeWidget::onRangeToggled(bool checked)
{
m_loudnessFilter->set("calc_range", checked);
Settings.setLoudnessScopeShowMeter("range", checked);
setOrientation(m_orientation, true);
resetQview();
}
void AudioLoudnessScopeWidget::onPeakToggled(bool checked)
{
m_loudnessFilter->set("calc_peak", checked);
Settings.setLoudnessScopeShowMeter("peak", checked);
setOrientation(m_orientation, true);
resetQview();
}
void AudioLoudnessScopeWidget::onTruePeakToggled(bool checked)
{
m_loudnessFilter->set("calc_true_peak", checked);
Settings.setLoudnessScopeShowMeter("truepeak", checked);
setOrientation(m_orientation, true);
resetQview();
}
void AudioLoudnessScopeWidget::updateMeters(void)
{
if (!m_newData || !m_qview->rootObject()) return;
if (m_loudnessFilter->get_int("calc_program") )
m_qview->rootObject()->setProperty("integrated", onedec(m_loudnessFilter->get_double("program")));
if (m_loudnessFilter->get_int("calc_shortterm") )
m_qview->rootObject()->setProperty("shortterm", onedec(m_loudnessFilter->get_double("shortterm")));
if (m_loudnessFilter->get_int("calc_momentary") )
m_qview->rootObject()->setProperty("momentary", onedec(m_loudnessFilter->get_double("momentary")));
if (m_loudnessFilter->get_int("calc_range") )
m_qview->rootObject()->setProperty("range", onedec(m_loudnessFilter->get_double("range")));
if (m_loudnessFilter->get_int("calc_peak") )
m_qview->rootObject()->setProperty("peak", onedec(m_peak));
if (m_loudnessFilter->get_int("calc_true_peak") )
m_qview->rootObject()->setProperty("truePeak", onedec(m_true_peak));
m_peak = -100;
m_true_peak = -100;
m_newData = false;
}
bool AudioLoudnessScopeWidget::event(QEvent *event)
{
bool result = ScopeWidget::event(event);
if (event->type() == QEvent::PaletteChange || event->type() == QEvent::StyleChange) {
resetQview();
}
return result;
}
void AudioLoudnessScopeWidget::resetQview()
{
LOG_DEBUG() << "begin" << "isSceneGraphInitialized" <<
m_qview->quickWindow()->isSceneGraphInitialized();
if (!m_qview->quickWindow()->isSceneGraphInitialized()) {
return;
}
if (m_qview->status() != QQuickWidget::Null) {
m_qview->setSource(QUrl(""));
}
QDir viewPath = QmlUtilities::qmlDir();
viewPath.cd("scopes");
viewPath.cd("audioloudness");
m_qview->engine()->addImportPath(viewPath.path());
QDir modulePath = QmlUtilities::qmlDir();
modulePath.cd("modules");
m_qview->engine()->addImportPath(modulePath.path());
m_qview->setResizeMode(QQuickWidget::SizeRootObjectToView);
m_qview->quickWindow()->setColor(palette().window().color());
QUrl source = QUrl::fromLocalFile(viewPath.absoluteFilePath("audioloudnessscope.qml"));
m_qview->setSource(source);
if (m_qview->rootObject()) {
m_qview->rootObject()->setProperty("orientation", m_orientation);
m_qview->rootObject()->setProperty("enableIntegrated",
Settings.loudnessScopeShowMeter("integrated"));
m_qview->rootObject()->setProperty("enableShortterm", Settings.loudnessScopeShowMeter("shortterm"));
m_qview->rootObject()->setProperty("enableMomentary", Settings.loudnessScopeShowMeter("momentary"));
m_qview->rootObject()->setProperty("enableRange", Settings.loudnessScopeShowMeter("range"));
m_qview->rootObject()->setProperty("enablePeak", Settings.loudnessScopeShowMeter("peak"));
m_qview->rootObject()->setProperty("enableTruePeak", Settings.loudnessScopeShowMeter("truepeak"));
}
}
| 13,295
|
C++
|
.cpp
| 301
| 37.916944
| 108
| 0.685214
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,252
|
scopewidget.cpp
|
mltframework_shotcut/src/widgets/scopes/scopewidget.cpp
|
/*
* Copyright (c) 2015-2022 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "scopewidget.h"
#include <Logger.h>
#include <QtConcurrent/QtConcurrent>
ScopeWidget::ScopeWidget(const QString &name)
: QWidget()
, m_queue(3, DataQueue<SharedFrame>::OverflowModeDiscardOldest)
, m_future()
, m_refreshPending(false)
, m_mutex()
, m_forceRefresh(false)
, m_size(0, 0)
{
LOG_DEBUG() << "begin" << m_future.isFinished();
setObjectName(name);
LOG_DEBUG() << "end";
}
ScopeWidget::~ScopeWidget()
{
}
void ScopeWidget::onNewFrame(const SharedFrame &frame)
{
m_queue.push(frame);
requestRefresh();
}
void ScopeWidget::requestRefresh()
{
if (m_future.isFinished()) {
m_future = QtConcurrent::run(&ScopeWidget::refreshInThread, this);
} else {
m_refreshPending = true;
}
}
void ScopeWidget::refreshInThread()
{
if (m_size.isEmpty()) {
return;
}
m_mutex.lock();
QSize size = m_size;
bool full = m_forceRefresh;
m_forceRefresh = false;
m_mutex.unlock();
m_refreshPending = false;
refreshScope(size, full);
// Tell the GUI thread that the refresh is complete.
QMetaObject::invokeMethod(this, "onRefreshThreadComplete", Qt::QueuedConnection);
}
void ScopeWidget::onRefreshThreadComplete()
{
update();
if (m_refreshPending) {
requestRefresh();
}
}
void ScopeWidget::resizeEvent(QResizeEvent *)
{
m_mutex.lock();
m_size = size();
m_mutex.unlock();
if (isVisible()) {
requestRefresh();
}
}
void ScopeWidget::changeEvent(QEvent *)
{
m_mutex.lock();
m_forceRefresh = true;
m_mutex.unlock();
if (isVisible()) {
requestRefresh();
}
}
| 2,354
|
C++
|
.cpp
| 88
| 23.136364
| 85
| 0.687805
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,253
|
videohistogramscopewidget.cpp
|
mltframework_shotcut/src/widgets/scopes/videohistogramscopewidget.cpp
|
/*
* Copyright (c) 2018-2022 Meltytech, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "videohistogramscopewidget.h"
#include <Logger.h>
#include <QMouseEvent>
#include <QPainter>
#include <QPainterPath>
#include <QToolTip>
const qreal IRE0 = 16;
const qreal IRE100 = 235;
VideoHistogramScopeWidget::VideoHistogramScopeWidget()
: ScopeWidget("VideoHistogram")
, m_frame()
, m_mutex()
, m_yBins()
, m_rBins()
, m_gBins()
, m_bBins()
{
LOG_DEBUG() << "begin";
setMouseTracking(true);
LOG_DEBUG() << "end";
}
void VideoHistogramScopeWidget::refreshScope(const QSize &size, bool full)
{
Q_UNUSED(size)
Q_UNUSED(full)
while (m_queue.count() > 0) {
m_frame = m_queue.pop();
}
QVector<unsigned int> yBins(256, 0);
QVector<unsigned int> rBins(256, 0);
QVector<unsigned int> gBins(256, 0);
QVector<unsigned int> bBins(256, 0);
if (m_frame.is_valid() && m_frame.get_image_width() && m_frame.get_image_height()) {
const uint8_t *pYUV = m_frame.get_image(mlt_image_yuv420p);
const uint8_t *pRGB = m_frame.get_image(mlt_image_rgb);
size_t count = m_frame.get_image_width() * m_frame.get_image_height();
unsigned int *pYbin = yBins.data();
unsigned int *pRbin = rBins.data();
unsigned int *pGbin = gBins.data();
unsigned int *pBbin = bBins.data();
while (count--) {
pYbin[*pYUV++]++;
pRbin[*pRGB++]++;
pGbin[*pRGB++]++;
pBbin[*pRGB++]++;
}
}
m_mutex.lock();
m_yBins.swap(yBins);
m_rBins.swap(rBins);
m_gBins.swap(gBins);
m_bBins.swap(bBins);
m_mutex.unlock();
}
void VideoHistogramScopeWidget::paintEvent(QPaintEvent *)
{
if (!isVisible())
return;
// Create the painter
QPainter p(this);
p.setRenderHint(QPainter::Antialiasing, true);
QFont font = QWidget::font();
int fontSize = font.pointSize() - (font.pointSize() > 10 ? 2 : (font.pointSize() > 8 ? 1 : 0));
font.setPointSize(fontSize);
p.setFont(font);
// draw the waveform data
int histHeight = rect().height() / 4;
QRect histRect;
m_mutex.lock();
histRect = rect();
histRect.setHeight(histHeight);
drawHistogram(p, tr("Luma"), Qt::white, palette().text().color(), m_yBins, histRect);
histRect = rect();
histRect.setTop(histHeight);
histRect.setHeight(histHeight);
drawHistogram(p, tr("Red"), Qt::red, Qt::red, m_rBins, histRect);
histRect = rect();
histRect.setTop(histHeight * 2);
histRect.setHeight(histHeight);
drawHistogram(p, tr("Green"), Qt::green, Qt::green, m_gBins, histRect);
histRect = rect();
histRect.setTop(histHeight * 3);
histRect.setHeight(histHeight);
drawHistogram(p, tr("Blue"), Qt::blue, Qt::blue, m_bBins, histRect);
m_mutex.unlock();
p.end();
}
void VideoHistogramScopeWidget::drawHistogram(QPainter &p, QString title, QColor color,
QColor outline, QVector<unsigned int> &bins, QRect rect)
{
unsigned int binCount = bins.size();
unsigned int *pBins = bins.data();
QFontMetrics fm(p.font());
int textpad = 3;
qreal histHeight = rect.height() - fm.height() - textpad - textpad;
QPen pen;
// Find the highest value
unsigned int maxLevel = 0;
unsigned int minValue = 255;
unsigned int maxValue = 0;
for (unsigned int i = 0; i < binCount; i++) {
if (pBins[i] > maxLevel)
maxLevel = pBins[i];
if (minValue > i && pBins[i] != 0)
minValue = i;
if (maxValue < i && pBins[i] != 0)
maxValue = i;
}
// Draw the title and max/min values
pen.setColor(palette().text().color().rgb());
p.setPen(pen);
QString text;
if (maxLevel > minValue)
text = QStringLiteral("%1\tMin: %2\tMax: %3").arg(title).arg(minValue).arg(maxValue);
else
text = title;
p.drawText(textpad, rect.y() + fm.height() + textpad, text);
// Nothing to draw.
if (maxLevel < minValue) return;
// Set histogram background gradient.
QLinearGradient gradient = QLinearGradient(rect.left(), rect.top(), rect.right(), rect.top());
gradient.setColorAt(0, color.darker().darker());
gradient.setColorAt(0.2, color.darker().darker());
gradient.setColorAt(0.8, color);
gradient.setColorAt(1, color);
QBrush brush(gradient);
p.setBrush(brush);
// Set histogram outline.
pen.setColor(outline);
pen.setWidth(1);
p.setPen(pen);
QPainterPath histPath;
histPath.moveTo( rect.bottomLeft() );
qreal lineWidth = (qreal)rect.width() / 256.0;
for (unsigned int i = 0; i < binCount; i++) {
qreal xPos = (qreal)rect.width() * i / binCount;
qreal yPos = (qreal)rect.bottom() - (histHeight * pBins[i] / maxLevel);
histPath.lineTo(xPos, yPos);
histPath.lineTo(xPos + lineWidth, yPos);
}
histPath.lineTo( rect.bottomRight() );
histPath.closeSubpath();
p.drawPath( histPath );
}
void VideoHistogramScopeWidget::mouseMoveEvent(QMouseEvent *event)
{
QString text;
int value = 256 * event->pos().x() / width();
if (event->pos().y() < height() / 4) {
// Show value and IRE in the luminance histogram.
qreal ire100x = width() * IRE100 / 256;
qreal ire0x = width() * IRE0 / 256;
qreal ireStep = (ire0x - ire100x) / 100.0;
int ire = (ire0x - event->pos().x()) / ireStep;
text = tr("Value: %1\nIRE: %2").arg(value).arg(ire);
} else {
text = tr("Value: %1").arg(value);
}
QToolTip::showText(event->globalPosition().toPoint(), text);
}
QString VideoHistogramScopeWidget::getTitle()
{
return tr("Video Histogram");
}
| 6,400
|
C++
|
.cpp
| 180
| 30.1
| 102
| 0.635923
|
mltframework/shotcut
| 10,796
| 1,118
| 50
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.