Repository navigation
Expand file tree
/
Copy pathmain.cpp
More file actions
463 lines (389 loc) · 16.6 KB
/
Copy pathmain.cpp
File metadata and controls
463 lines (389 loc) · 16.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QCommandLineParser>
#include <QDir>
#include <QFileInfo>
#include <QProcess>
#include <QProcessEnvironment>
#include <QRegularExpression>
#include <QEventLoop>
#include <QLoggingCategory>
#include <iostream>
#include <thread>
#include <atomic>
#include <memory>
#include "collage.h"
#include "credentialfiltersink.h"
#include "instancemanager.h"
#include "previewimageprovider.h"
#include "logoprovider.h"
#include "probeworker.h"
#include "rtspconnection.h"
#include "streamaddress.h"
#include <spdlog/spdlog.h>
#include <spdlog/sinks/stdout_color_sinks.h>
#ifdef Q_OS_WIN
#include <windows.h>
#endif
std::shared_ptr<spdlog::logger> logger;
// Supported video file extensions for collage creation
static const QStringList SUPPORTED_VIDEO_EXTENSIONS = {
"mp4", "avi", "mkv", "mov", "wmv", "flv", "webm", "m4v", "mpg"
};
// Converts a CLI-supplied collage path to a QUrl. Local filesystem paths (absolute or relative) become file:// URLs;
// only strings carrying a genuine URL scheme are parsed as URLs. This avoids QUrl::fromUserInput() mis-reading a bare
// filename like "video.mp4" as a hostname and prefixing it with "http://".
static QUrl collagePathToUrl(const QString &path) {
QFileInfo info(path);
if (info.isAbsolute()) {
return QUrl::fromLocalFile(path);
}
// Treat as a URL only when the string clearly uses URI syntax (`scheme://...`). A bare scheme check is too loose:
// a local file legitimately named "my:video.mp4" would otherwise be misread as a URL.
static const QRegularExpression urlWithAuthority(R"(^[A-Za-z][A-Za-z0-9+.-]*://)");
if (urlWithAuthority.match(path).hasMatch()) {
return QUrl::fromUserInput(path);
}
// Relative filesystem path - resolve against the working directory.
return QUrl::fromLocalFile(QDir::current().absoluteFilePath(path));
}
static bool hasUrlScheme(const QString &value) {
static const QRegularExpression urlWithAuthority(R"(^[A-Za-z][A-Za-z0-9+.-]*://)");
return urlWithAuthority.match(value).hasMatch();
}
static QUrl sourcePathToUrl(const QString &sourceValue, bool *unsupportedScheme) {
if (hasUrlScheme(sourceValue)) {
const QUrl url(sourceValue);
if (url.isValid() && (StreamAddress::isStream(url) || url.isLocalFile())) {
return url;
}
std::cerr << "Unsupported address (http, https, rtsp and rtsps streams can be opened): " << StreamAddress::withoutCredentials(sourceValue).toStdString() << '\n';
*unsupportedScheme = true;
return {};
}
QFileInfo fileInfo(sourceValue);
if (fileInfo.isRelative()) {
// Convert relative path to absolute
QString absolutePath = QDir::current().absoluteFilePath(sourceValue);
QFileInfo resolvedInfo(absolutePath);
if (!resolvedInfo.exists()) {
logger->warn("File does not exist: '{}'", absolutePath.toStdString());
return {};
}
logger->debug("Converted relative path '{}' to absolute: '{}'",
sourceValue.toStdString(), absolutePath.toStdString());
return QUrl::fromLocalFile(absolutePath);
}
if (fileInfo.isAbsolute()) {
if (!fileInfo.exists()) {
logger->warn("File does not exist: '{}'", sourceValue.toStdString());
return {};
}
logger->debug("Using absolute path: '{}'", sourceValue.toStdString());
return QUrl::fromLocalFile(sourceValue);
}
// Try to parse as URL (e.g., file://, http://, etc.)
QUrl sourceURL = QUrl::fromUserInput(sourceValue);
logger->debug("Parsed as URL: '{}'", sourceURL.toString().toStdString());
return sourceURL;
}
void initLogging() {
// Create a console sink (stdout)
auto console_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
// Create logger with the sink
logger = std::make_shared<spdlog::logger>("gav", std::make_shared<CredentialFilterSink>(console_sink));
// Register as default logger
spdlog::set_default_logger(logger);
// https://github.com/gabime/spdlog/wiki/3.-Custom-formatting
#ifdef QT_DEBUG
logger->set_pattern("[%x %H:%M:%S.%f] [%o ms] [%L] [%t] %v");
logger->set_level(spdlog::level::debug);
#else
logger->set_pattern("[%x %H:%M:%S] [%L] %v");
logger->set_level(spdlog::level::info);
#endif
// https://github.com/gabime/spdlog/wiki/Flush-policy
logger->flush_on(spdlog::level::info);
}
static bool showFFmpegLogs = false;
void logOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg) {
static const QLatin1String openFailureCategory("qt.multimedia.ffmpeg.mediadataholder");
if (context.category && openFailureCategory == QLatin1String(context.category) && msg.contains(QLatin1String("FFmpeg error description"))) {
RtspConnection::noteOpenFailure(msg);
if (!showFFmpegLogs) {
return;
}
}
static const QLatin1String ffmpegPrefix("\"FFmpeg log: ");
if (msg.startsWith(ffmpegPrefix)) {
const bool isError = type == QtCriticalMsg || type == QtFatalMsg;
if (!isError && (!showFFmpegLogs || type == QtDebugMsg)) {
return;
}
QString text = msg.mid(ffmpegPrefix.size());
if (text.endsWith(QLatin1Char('"'))) {
text.chop(1);
}
const std::string line = text.toStdString();
if (isError) {
logger->error("FFmpeg: {}", line);
} else if (type == QtWarningMsg) {
logger->warn("FFmpeg: {}", line);
} else {
logger->info("FFmpeg: {}", line);
}
return;
}
QByteArray localMsg = msg.toLocal8Bit();
const char *file = context.file ? context.file : "";
const char *function = context.function ? context.function : "";
switch (type) {
case QtDebugMsg:
logger->debug("Debug: {} ({}:{}, {})", localMsg.constData(), file, context.line, function);
break;
case QtInfoMsg:
logger->info("Info: {} ({}:{}, {})", localMsg.constData(), file, context.line, function);
break;
case QtWarningMsg:
logger->warn("Warning: {} ({}:{}, {})", localMsg.constData(), file, context.line, function);
break;
case QtCriticalMsg:
case QtFatalMsg:
logger->critical("Critical: {} ({}:{}, {})", localMsg.constData(), file, context.line, function);
break;
}
}
static int runProbe(int argc, char *argv[]) {
logger = std::make_shared<spdlog::logger>("gav-probe", std::make_shared<CredentialFilterSink>(std::make_shared<spdlog::sinks::stderr_color_sink_mt>()));
spdlog::set_default_logger(logger);
logger->set_level(spdlog::level::warn);
qInstallMessageHandler(logOutput);
QCoreApplication app(argc, argv);
return ProbeWorker::runFromArguments(QCoreApplication::arguments());
}
int main(int argc, char *argv[]) {
#ifdef Q_OS_WIN
// Enable UTF-8 output on Windows console
SetConsoleOutputCP(CP_UTF8);
#endif
if (qEnvironmentVariable("GAV_SUBPROCESS") == QLatin1String("probe")) {
return runProbe(argc, argv);
}
#if defined(Q_OS_LINUX)
if (!qEnvironmentVariableIsSet("FONTCONFIG_FILE") && QFileInfo::exists(QStringLiteral("/etc/fonts/fonts.conf"))) {
qputenv("FONTCONFIG_FILE", "/etc/fonts/fonts.conf");
}
#endif
initLogging();
qInstallMessageHandler(logOutput);
if (!qEnvironmentVariableIsSet("QT_FFMPEG_DEBUG")) {
qputenv("QT_FFMPEG_DEBUG", "1");
}
QGuiApplication app(argc, argv);
#ifdef APP_VERSION
QCoreApplication::setApplicationVersion(QString(APP_VERSION));
#else
QCoreApplication::setApplicationVersion(QString("dev"));
#endif
QCoreApplication::setOrganizationName("gav");
QCoreApplication::setApplicationName("gav");
QCommandLineParser parser;
parser.setApplicationDescription("GAV is a simple audio and video player, backed by FFmpeg and Qt6");
parser.addHelpOption();
parser.addVersionOption();
QCommandLineOption sourceOption({"s", "source"}, "Source of the audio or video to play");
parser.addOption(sourceOption);
QCommandLineOption collageOption({"c", "collage"}, "Create a collage from video files", "collage");
parser.addOption(collageOption);
QCommandLineOption verboseOption("verbose", "Enable verbose logging");
parser.addOption(verboseOption);
// Accept bare file paths so OS file-association launches (e.g. `gav %F` from the .desktop entry, or Explorer's
// `"gav.exe" "%1"` on Windows) deliver the selected files to the player.
parser.addPositionalArgument("files", "Audio or video files to play", "[files...]");
parser.process(app);
if (parser.isSet(verboseOption)) {
logger->set_level(spdlog::level::debug);
showFFmpegLogs = true;
logger->debug("Verbose logging enabled");
} else {
QLoggingCategory::setFilterRules(QStringLiteral("qt.multimedia*=false\nqt.multimedia.ffmpeg.mediadataholder.warning=true"));
}
QStringList sourceValues;
if (parser.isSet(sourceOption)) {
sourceValues.append(parser.value(sourceOption));
} else {
// Fall back to the positional arguments so double-clicked files (passed without -s by the OS) play.
sourceValues = parser.positionalArguments();
}
if (parser.isSet(collageOption)) {
QStringList collagePaths = parser.values(collageOption);
if (collagePaths.isEmpty() && !sourceValues.isEmpty()) {
collagePaths.append(sourceValues.first());
} else if (collagePaths.isEmpty()) {
std::cerr << "No input files provided for collage creation." << std::endl;
return 1;
}
// Expand directories to video files
QStringList expandedPaths;
for (const QString &path : collagePaths) {
if (hasUrlScheme(path) && !QUrl(path).isLocalFile()) {
std::cerr << "Collage needs local files; skipping " << StreamAddress::withoutCredentials(path).toStdString() << '\n';
continue;
}
QFileInfo pathInfo(path);
if (pathInfo.isDir()) {
// Get all video files in directory using name filters for efficiency
QDir dir(path);
QStringList nameFilters;
for (const QString &ext : SUPPORTED_VIDEO_EXTENSIONS) {
nameFilters << QString("*.%1").arg(ext);
}
dir.setNameFilters(nameFilters);
QFileInfoList videoFiles = dir.entryInfoList(QDir::Files | QDir::NoDotAndDotDot);
for (const QFileInfo &fileInfo : videoFiles) {
expandedPaths.append(fileInfo.absoluteFilePath());
}
if (parser.isSet(verboseOption)) {
logger->debug("Expanded directory '{}' to {} video file(s)",
path.toStdString(),
videoFiles.size());
}
} else {
// Regular file, add as-is
expandedPaths.append(path);
}
}
if (expandedPaths.isEmpty()) {
std::cerr << "No video files found in provided path(s)." << std::endl;
return 1;
}
// Replace collagePaths with expanded list
collagePaths = expandedPaths;
bool verbose = parser.isSet(verboseOption);
bool isSubprocess = qEnvironmentVariableIsSet("GAV_SUBPROCESS");
// If running as subprocess, process single file directly and output result
// Output format: SUCCESS:<output_path> or FAILED:<input_path>
if (isSubprocess) {
QUrl url = collagePathToUrl(collagePaths.first());
QString result = Collage::createCollageSingle(url);
if (!result.isEmpty()) {
std::cout << "SUCCESS:" << result.toStdString() << std::endl;
return 0;
} else {
std::cerr << "FAILED:" << collagePaths.first().toStdString() << std::endl;
return 1;
}
}
// Convert paths to URLs
QList<QUrl> urls;
for (const QString &path : collagePaths) {
urls.append(collagePathToUrl(path));
}
// Track results
int successCount = 0;
int failCount = 0;
QStringList successPaths;
QStringList failPaths;
const int total = urls.size();
// Spinner thread
auto isRunning = std::make_shared<std::atomic<bool>>(true);
auto completedCount = std::make_shared<std::atomic<int>>(0);
std::thread spinnerThread;
if (!verbose) {
spinnerThread = std::thread([isRunning, completedCount, total]() {
std::vector<std::string> spinner = {"⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"};
int j = 0;
while (*isRunning) {
int done = *completedCount;
std::cout << "\rCreating collages [" << done << "/" << total << "]... "
<< spinner[j % spinner.size()] << " ";
std::cout.flush();
std::this_thread::sleep_for(std::chrono::milliseconds(80));
j++;
}
});
}
// Use Collage::toCollage which handles parallel subprocess spawning
Collage collage;
QEventLoop loop;
QObject::connect(&collage, &Collage::collageCompleted,
[&](int index, const QString &outputPath, bool success) {
(*completedCount)++;
if (success) {
successCount++;
successPaths.append(outputPath);
} else {
failCount++;
failPaths.append(collagePaths[index]);
}
});
QObject::connect(&collage, &Collage::collageFinished, &loop, &QEventLoop::quit);
collage.toCollage(urls);
loop.exec();
// Stop spinner
*isRunning = false;
if (spinnerThread.joinable()) {
spinnerThread.join();
}
if (!verbose) {
std::cout << "\r\033[K";
}
// Display results
std::cout << "\n=== Collage Creation Summary ===\n" << std::endl;
for (int i = 0; i < successPaths.size(); ++i) {
std::cout << "[" << i << "] ✓ Success: "
<< successPaths[i].toStdString() << std::endl;
}
for (int i = 0; i < failPaths.size(); ++i) {
std::cout << "[" << (successPaths.size() + i) << "] ✗ Failed: "
<< failPaths[i].toStdString() << std::endl;
}
std::cout << "\n" << successCount << " collage(s) created successfully";
if (failCount > 0) {
std::cout << ", " << failCount << " failed";
}
std::cout << ".\n" << std::endl;
return failCount > 0 ? 1 : 0;
}
QList<QUrl> sourceUrls;
bool unsupportedScheme = false;
for (const QString &sourceValue : sourceValues) {
const QUrl sourceURL = sourcePathToUrl(sourceValue, &unsupportedScheme);
if (!sourceURL.isEmpty() && sourceURL.isValid()) {
sourceUrls.append(sourceURL);
logger->info("Loading source: '{}'", sourceURL.toString().toStdString());
} else if (!sourceURL.isEmpty()) {
logger->warn("Invalid source URL: '{}'", sourceValue.toStdString());
}
}
if (unsupportedScheme && sourceUrls.isEmpty()) {
return 2;
}
InstanceManager instanceManager(nullptr);
if (!instanceManager.start(sourceUrls)) {
return 0;
}
QQmlApplicationEngine engine;
engine.addImageProvider("preview", new PreviewImageProvider());
engine.addImageProvider("logo", new LogoImageProvider(new LogoProvider(LogoProvider::defaultCacheDirectory(), &app)));
QObject::connect(
&engine,
&QQmlApplicationEngine::objectCreationFailed,
&app,
[]() { QCoreApplication::exit(-1); },
Qt::QueuedConnection);
engine.loadFromModule("gavqml", "Main");
#ifdef Q_OS_WIN
// Free console only if launched without a parent console (GUI double-click)
// This prevents the console window from staying open when launched from Explorer
DWORD procIDs[2];
DWORD maxCount = 2;
DWORD result = GetConsoleProcessList((LPDWORD) procIDs, maxCount);
// If result == 1, only this process is attached to console (launched from Explorer)
// If result > 1, there's a parent console (cmd/powershell) - keep it attached
if (result == 1) {
FreeConsole();
}
#endif
return app.exec();
}