-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclicontroller.cpp
More file actions
443 lines (353 loc) · 12.7 KB
/
clicontroller.cpp
File metadata and controls
443 lines (353 loc) · 12.7 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
/*
Copyright (C) 2009-2014 jakago
Copyright (C) 2018-2026 CSReviser Team
This file is part of CaptureStream2, the recorder to support HLS for
NHK radio language courses.
CaptureStream2 is a modified version of CaptureStream, originally
developed by jakago.
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 2 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 <https://www.gnu.org/licenses/gpl-2.0.html>.
*/
#include "clicontroller.h"
#include "commandlineparser.h"
#include "programrepository.h"
#include "recordingcore.h"
//#include "clioptions.h"
#include "ffmpegcommandbuilder.h"
#include <QDebug>
#include <iostream>
#include <QProcess>
#include <QString>
#include <QHash>
#include <optional>
namespace CliUtil {
static const QHash<QString, QString>& audioExtMap()
{
static const QHash<QString, QString> map = []{
QHash<QString, QString> m;
for (int i = 0; i < Constants::AUDIO_EXT_COUNT; ++i) {
QString ext = QString::fromUtf8(Constants::AUDIO_EXT_LIST[i]);
m.insert(ext.toLower(), ext);
}
return m;
}();
return map;
}
// 無効値はエラーにしない → 未指定扱い(nullopt)
std::optional<QString> normalizeAudioExtension(const QString& input)
{
QString key = input.trimmed().toLower();
if (key.isEmpty()) {
return std::nullopt; // 未指定
}
const auto& map = audioExtMap();
auto it = map.find(key);
if (it != map.end()) {
return it.value(); // 正規化済み値
}
// ★ 無効値 → 未指定扱い(エラーにしない)
return std::nullopt;
}
} // namespace
CLIController::CLIController(const Settings& settings, int argc, char** argv)
: m_settings(settings)
, m_argc(argc)
, m_argv(argv)
{
// 1. Repositoryの開始(appが必要な場合があるためここ)
ProgramRepository::instance().start();
}
int CLIController::run()
{
if (!ProgramRepository::instance().waitUntilReady()) {
qCritical() << "Failed to initialize program repository";
return 1;
}
// testFfmpeg();
// 2. CLI オプション解析(抽象化済みパーサー)
CliOptions opts = CommandLineParser::parse(m_argc, m_argv);
// --- DEBUG: CommandLineParser の解析結果を表示 ---
qDebug() << "--- [DEBUG] CommandLineParser Results ---";
qDebug() << "Program IDs:" << opts.programIds;
for (auto it = opts.valueOptions.constBegin(); it != opts.valueOptions.constEnd(); ++it) {
qDebug() << "Value Option:" << it.key() << "=" << it.value();
}
for (const QString& flag : opts.enabledFlags) {
qDebug() << "Flag detected:" << flag;
}
// -----------------------------------------------
// 3. オプション検証
if (!validateOptions(opts)) {
qWarning() << "CLI option validation failed.";
return 1;
}
// 4. RuntimeConfig 構築
// Settings → RuntimeConfig へ反映
RuntimeConfig config;
config.applySettings(m_settings);
// 5. CLI 上書き適用
config.applyCommandLine(opts);
// --- DEBUG: OPTION_TABLE に基づく RuntimeConfig の最終状態表示 ---
qDebug() << "--- [DEBUG] RuntimeConfig State Check (via OPTION_TABLE) ---";
int tableCount = Constants::getOptionTableCount();
for (int i = 0; i < tableCount; ++i) {
const auto& optEntry = Constants::OPTION_TABLE[i];
QString internalKey = QString::fromUtf8(optEntry.keyOption);
// 値を持つオプションかフラグかによって判定を分ける
if (optEntry.requiresValue) {
// 値オプションの確認(空でない場合のみ表示、または設定値を表示)
QString currentVal = opts.valueOptions.value(internalKey); // RuntimeConfigにvalue()メソッドがある想定
qDebug() << QString("Option [%1] (%2): %3")
.arg(optEntry.name)
.arg(internalKey)
.arg(currentVal.isEmpty() ? "(Not Set)" : currentVal);
} else {
// フラグ(bool)の確認
bool isSet = config.flag(internalKey);
qDebug() << QString("Flag [%1] (%2): %3")
.arg(optEntry.name)
.arg(internalKey)
.arg(isSet ? "ON" : "OFF");
}
}
// 6. 実行(RecordingCore は QThread)
RecordingCore core(config);
if (config.flag( QString::fromUtf8(Constants::KEY_HELP))) {
showHelp();
return 0;
}
//
// ★★★ ここがポイント:-m のときだけメッセージ出力を接続 ★★★
//
if (config.flag( QString::fromUtf8(Constants::KEY_MESSAGE_ON))) {
QObject::connect(&core, &RecordingCore::messageGenerated,
[](const QString &msg){
std::cout << msg.toStdString() << std::endl;
});
QObject::connect(&core, &RecordingCore::errorOccurred,
[](const QString &msg){
std::cerr << msg.toStdString() << std::endl;
});
QObject::connect(&core, &RecordingCore::progressChanged,
[](int percent){
std::cout << "Progress: " << percent << "%" << std::endl;
});
}
// 終了通知は常に受け取ってもよい(任意)
QObject::connect(&core, &RecordingCore::finished,
[](){
// 必要なら終了メッセージ
});
core.start(); // QThread の開始
qDebug() << "core.start()";
core.wait(); // 終了待ち
qDebug() << "core.wait()";
return 0; // とりあえず仮
}
bool CLIController::validateOptions(CliOptions& opts)
{
// 値付きオプションの簡易チェック(空文字など)
for (auto it = opts.valueOptions.constBegin(); it != opts.valueOptions.constEnd(); ++it) {
const QString& key = it.key();
const QString& value = it.value();
if (value.isEmpty()) {
qWarning() << "Empty value for option key:" << key;
return false;
}
// 必要なら key ごとの詳細チェックをここに追加
// 2. -e の検証(大文字小文字無視・正規化・不一致なら削除)
validateAudioExtension(opts);
}
// 3. 番組IDの妥当性
if (!validateProgramIds(opts)) {
return false;
}
return true;
// 番組IDの妥当性確認
if (!validateProgramIds(opts)) {
return false;
}
return true;
}
bool CLIController::validateProgramIds(const CliOptions& opts) const
{
ProgramRepository& repo = ProgramRepository::instance();
// ProgramRepository 側に id_map へのアクセサがある前提
// 例: const QHash<QString, QString>& ProgramRepository::idMap() const;
const QMap<QString, QString>& idMap = repo.id_map;
for (const QString& id : opts.programIds) {
if (!idMap.contains(id)) {
qWarning() << "Unknown program ID:" << id;
return false;
}
}
return true;
}
void CLIController::showHelp()
{
QTextStream out(stdout);
out << QString::fromUtf8(Constants::HELP_USAGE) << "\n\n";
out << QString::fromUtf8(Constants::HELP_HEADER) << "\n\n";
QMap<QString, QStringList> groupOptions;
QMap<QString, QString> groupDesc;
QMap<QString, bool> groupValue;
const int count = Constants::getOptionTableCount();
for (int i = 0; i < count; ++i) {
const auto &opt = Constants::OPTION_TABLE[i];
QString group;
if (opt.group)
group = QString::fromUtf8(opt.group);
else
group = QString::fromUtf8(opt.name);
groupOptions[group].append(QString::fromUtf8(opt.name));
groupDesc[group] = QString::fromUtf8(opt.description);
groupValue[group] = opt.requiresValue;
}
for (auto it = groupOptions.begin(); it != groupOptions.end(); ++it)
{
QString names = it.value().join(" / ");
if (groupValue[it.key()])
names += " <value>";
out << " " << names << "\n";
out << " " << groupDesc[it.key()] << "\n\n";
}
out << QString::fromUtf8(Constants::HELP_PROGRAMID) << "\n";
}
bool CLIController::validateAudioExtension(CliOptions& opts)
{
const QString KEY = QString::fromUtf8(Constants::KEY_AudioExtension);
if (!opts.valueOptions.contains(KEY)) {
return true; // -e 未指定なら何もしない
}
QString userExt = opts.valueOptions.value(KEY).trimmed();
if (userExt.isEmpty()) {
qDebug() << "Empty audio extension for -e option.";
opts.valueOptions.remove(KEY);
return false;
}
// 大文字小文字を無視して比較
QString lowerUser = userExt.toLower();
QString matched;
for (int i = 0; i < Constants::AUDIO_EXT_COUNT; ++i) {
QString tableExt = QString::fromUtf8(Constants::AUDIO_EXT_LIST[i]);
if (tableExt.compare(lowerUser, Qt::CaseInsensitive) == 0) {
matched = tableExt; // 正規値
break;
}
}
if (matched.isEmpty()) {
qDebug() << "Unknown audio extension:" << userExt
<< " → -e オプションは無効化されます。";
opts.valueOptions.remove(KEY);
return false;
}
// 正規化された値に置き換え
opts.valueOptions[KEY] = matched;
return true;
}
// =========================
// 仮の構造体(未実装対策)
// =========================
/*
enum class Container {
MP3,
M4A,
AAC
};
struct AudioFormat {
QString codec;
QString bitrate;
int channels = 2;
QString sampleRate;
bool copyCodec = false;
};
struct Metadata {
QString title;
};
struct InputOptions {
QString inputPath;
};
struct RecordingRequest {
InputOptions input;
AudioFormat format;
Metadata meta;
Container container;
QString outputPath;
};
struct FfmpegCapabilities {
bool httpSeekableSupported = false;
};
// =========================
// 仮Builder(未実装ならこれで代用)
// =========================
QStringList buildTestCommand(const RecordingRequest& req)
{
QStringList args;
args << "-y";
args << "-i" << req.input.inputPath;
args << "-c:a" << "libmp3lame";
args << "-b:a" << req.format.bitrate;
args << "-ac" << QString::number(req.format.channels);
if (!req.meta.title.isEmpty()) {
args << "-metadata" << "title=" + req.meta.title;
}
args << req.outputPath;
return args;
}
*/
// =========================
// テスト実行
// =========================
void CLIController::testFfmpeg()
{
RecordingRequest req;
req.input.inputPath = "input.aac";
req.outputPath = "output.mp3";
req.format.codec = "libmp3lame";
// req.format.copyCodec = true;
req.input.httpSeekable = true;
req.format.bitrate = "128k";
req.format.channels = 2;
req.meta.title = "test";
req.container = Container::MP3;
// req.container = Container::M4A;
// FfmpegCapabilities caps;
FfmpegCapabilities caps =
FfmpegCapabilities::detect("ffmpeg");
// ★ Builder未実装ならこれ
//QStringList args = FfmpegCommandBuilder::build(req);
QString outputPath = "output.tmp";
// ★ Builder実装済ならこれに切り替え
QStringList args = FfmpegCommandBuilder::build(req, caps, outputPath);
if (args.isEmpty()) {
qDebug() << "Command build failed";
return;
}
// コマンド確認
qDebug() << "ffmpeg" << args.join(" ");
qDebug() << "httpSeekable req =" << req.input.httpSeekable;
qDebug() << "httpSeekable caps =" << caps.httpSeekableSupported;
// =========================
// 実行
// =========================
QProcess process;
process.setProgram("ffmpeg"); // フルパスでもOK
process.setArguments(args);
process.start();
if (!process.waitForStarted()) {
qDebug() << "Failed to start ffmpeg";
return;
}
process.waitForFinished(-1);
qDebug() << "Exit code:" << process.exitCode();
qDebug() << "STDOUT:\n" << process.readAllStandardOutput();
qDebug() << "STDERR:\n" << process.readAllStandardError();
}