-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrecordingcore.cpp
More file actions
1306 lines (1114 loc) · 49.4 KB
/
recordingcore.cpp
File metadata and controls
1306 lines (1114 loc) · 49.4 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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
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 <stdlib.h>
#include "recordingcore.h"
//#include "customizedialog.h"
//#include "urldownloader.h"
#include "utility.h"
//#include "qt4qt5.h"
#include "scrambledialog.h"
#include "settings.h"
#include "constants.h"
#include "runtimeconfig.h"
#include "programrepository.h"
#include "presetrepository.h"
#include "legacyformatengine.h"
#include <QRegularExpression>
#include <QCheckBox>
#include <QDir>
#include <QFileInfo>
#include <QMessageBox>
#include <QTemporaryFile>
#include <QDateTime>
#include <QEventLoop>
#include <QTextStream>
#include <QDate>
#include <QLocale>
#include <QDebug>
#include <QNetworkReply>
#include <QApplication>
#include <QUrl>
#include <QUrlQuery>
#include <QtNetwork>
#include <QTemporaryFile>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QByteArray>
#include <QJsonValue>
#include <QMap>
#include <QMultiMap>
#include <tuple>
#include <algorithm>
#ifdef Q_OS_WIN
#define TimeOut " -m 10000 "
#else
#define TimeOut " -m 10 "
#endif
#define FlvMinSize 100 // ストリーミングが存在しなかった場合は13バイトだが少し大きめに設定
#define OriginalFormat "ts"
#define FilterOption "-bsf:a aac_adtstoasc"
#define CancelCheckTimeOut 500 // msec
//#define DebugLog(s) if ( ui->toolButton_detailed_message->isChecked() ) {emit information((s));}
//--------------------------------------------------------------------------------
QString RecordingCore::prefix = "https://www.nhk.or.jp/gogaku/st/xml/";
QString RecordingCore::suffix = "listdataflv.xml";
QString RecordingCore::json_prefix = "https://www.nhk.or.jp/radioondemand/json/";
QString RecordingCore::prefix1 = "https://vod-stream.nhk.jp/gogaku-stream/mp4/";
QString RecordingCore::prefix2 = "https://vod-stream.nhk.jp/gogaku-stream/mp4/";
QString RecordingCore::prefix3 = "https://vod-stream.nhk.jp/gogaku-stream/mp4/";
//QString RecordingCore::prefix1 = "https://vod-stream.nhk.jp/radioondemand/r/";
QString RecordingCore::suffix1 = "/index.m3u8";
QString RecordingCore::suffix2 = ".mp4/index.m3u8";
QString RecordingCore::suffix3 = "/index.m3u8";
QString RecordingCore::flv_host = "flv.nhk.or.jp";
QString RecordingCore::flv_app = "ondemand/";
QString RecordingCore::flv_service_prefix = "mp4:flv/gogaku/streaming/mp4/";
QString RecordingCore::flvstreamer;
QString RecordingCore::ffmpeg;
QString RecordingCore::Xml_koza;
QString RecordingCore::test;
QString RecordingCore::Error_mes;
QStringList RecordingCore::malformed = (QStringList() << "3g2" << "3gp" << "m4a" << "mov");
QString RecordingCore::nendo1 = "2025"; // 今年度
QString RecordingCore::nendo2 = "2026"; // 次年度
QDate RecordingCore::nendo_start_date(2026, 3, 30); // 今年度開始
QDate RecordingCore::zenki_end_date(2026, 9, 28); // 今年度前期末、年度末は次年度前期末
QDate RecordingCore::kouki_start_date(2026, 10, 05); // 今年度後期開始
QDate RecordingCore::nendo_end_date(2027, 3, 28); // 今年度末
QDate RecordingCore::nendo_start_date1(2026, 3, 30); // 年度初めは今年度開始、年度末は次年開始
QDate RecordingCore::nendo_end_date1(2027, 3, 28); // 年度初めは今年度末、年度末は次年度末
QDate RecordingCore::nendo_start_date2(2027, 3, 29); // 次年度開始
QDate RecordingCore::nendo_end_date2(2028, 4, 3); // 次年度末
QHash<QProcess::ProcessError, QString> RecordingCore::processError;
//--------------------------------------------------------------------------------
//RecordingCore::RecordingCore( Settings& settings,const RuntimeConfig& r, Ui::MainWindowClass* ui ) : isCanceled(false), failed1935(false), settings(settings),runtime(r),ui(ui) {
RecordingCore::RecordingCore( const RuntimeConfig& r ) : isCanceled(false), failed1935(false), runtime(r) {
if ( processError.empty() ) {
processError[QProcess::FailedToStart] = "FailedToStart";
processError[QProcess::Crashed] = "Crashed";
processError[QProcess::Timedout] = "Timedout";
processError[QProcess::ReadError] = "ReadError";
processError[QProcess::WriteError] = "WriteError";
processError[QProcess::UnknownError] = "UnknownError";
}
}
std::tuple<QStringList, QStringList, QStringList, QStringList, QStringList>
RecordingCore::getAttribute1(const QString &url)
{
QStringList fileList;
QStringList kouzaList;
QStringList hdateList;
QStringList nendoList;
QStringList dirList;
QEventLoop eventLoop;
QNetworkAccessManager mgr;
// 新しいシグナル/スロット構文(Qt5/Qt6両対応)
QObject::connect(&mgr, &QNetworkAccessManager::finished,
&eventLoop, &QEventLoop::quit);
QUrl url_xml(url);
QNetworkRequest req(url_xml);
QNetworkReply *reply = mgr.get(req);
eventLoop.exec(); // finishedシグナルを待機
// replyから全データを読み出してQByteArrayに格納
QByteArray xmlData = reply->readAll();
reply->deleteLater();
// QByteArrayを元にQXmlStreamReaderを初期化
QXmlStreamReader reader(xmlData);
while (!reader.atEnd() && !reader.hasError()) {
reader.readNext();
if (reader.isStartDocument())
continue;
if (reader.isEndDocument())
break;
// 各属性の値を取得
fileList.append(reader.attributes().value("file").toString());
kouzaList.append(reader.attributes().value("kouza").toString());
hdateList.append(reader.attributes().value("hdate").toString());
nendoList.append(reader.attributes().value("nendo").toString());
dirList.append(reader.attributes().value("dir").toString());
}
return { fileList, kouzaList, hdateList, nendoList, dirList };
}
std::tuple<QStringList, QStringList, QStringList, QStringList, QStringList>
RecordingCore::getJsonData(const QString& urlInput) {
QStringList fileList, kouzaList, file_titleList, hdateList, yearList, contentsIdList;
QString url = urlInput;
const int urlLen = url.length();
int l = (urlLen != 13) ? urlLen - 3 : 10;
int json_ohyo = 0;
if (url.contains("_x1")) { url.replace("_x1", "_01"); json_ohyo = 1; }
else if (url.contains("_y1")) { url.replace("_y1", "_01"); json_ohyo = 2; }
const QString jsonUrl = "https://www.nhk.or.jp/radio-api/app/v1/web/ondemand/series?site_id="
+ url.left(l) + "&corner_site_id=" + url.right(2);
// QString strReply;
// bool success = false;
int timer = 100;
const int timerMax = 5000;
const int retryLimit = 15;
/*
for (int i = 0; i < retryLimit; ++i) {
strReply = Utility::getJsonFile(jsonUrl, timer);
if (strReply != "error") {
success = true;
break;
}
timer = std::min(timer + ((timer < 500) ? 50 : 100), timerMax);
}
*/
QByteArray res;
bool success = false;
for (int i = 0; i < retryLimit; ++i) {
res = m_client.getSync(QUrl(jsonUrl), timer, 1);
if (!res.isEmpty()) {
success = true;
break;
}
timer = std::min(timer + ((timer < 500) ? 50 : 100), timerMax);
}
if (success) {
QString strReply = QString::fromUtf8(res);
std::tie(fileList, kouzaList, file_titleList, hdateList, yearList, contentsIdList) =
Utility::getJsonData1(strReply, json_ohyo);
}
// --- ここから放送時間順ソート処理 ---
const int count = kouzaList.size();
if (count > 1 && contentsIdList.size() == count) {
// 1. 各リストの要素を一つの構造体にまとめる
struct TempItem {
QString file, kouza, title, hdate, year, cid;
};
QList<TempItem> tempPacks;
tempPacks.reserve(count);
for (int i = 0; i < count; ++i) {
tempPacks.append({
fileList.value(i),
kouzaList.value(i),
file_titleList.value(i),
hdateList.value(i),
yearList.value(i),
contentsIdList.value(i)
});
}
// 2. contentsIdList(cid) の末尾にある ISO 8601 日時文字列でソート
std::sort(tempPacks.begin(), tempPacks.end(), [](const TempItem &a, const TempItem &b) {
// 例: "...;2024-02-27T06:45:00+09:00_..." の日時部分を比較
auto getTimePart = [](const QString &id) {
return id.section(';', -1).section('_', 0, 0);
};
return getTimePart(a.cid) < getTimePart(b.cid);
});
// 3. 各リストをクリアして、ソート順に詰め直す
fileList.clear(); kouzaList.clear(); file_titleList.clear(); hdateList.clear(); yearList.clear();
for (const auto &item : tempPacks) {
fileList << item.file;
kouzaList << item.kouza;
file_titleList << item.title;
hdateList << item.hdate;
yearList << item.year;
}
}
// --- ソート処理ここまで ---
// 以前と同様の不足分補完処理
const int finalCount = kouzaList.size();
while (file_titleList.size() < finalCount) file_titleList.append("\0");
while (fileList.size() < finalCount) fileList.append("\0");
while (hdateList.size() < finalCount) hdateList.append("\0");
while (yearList.size() < finalCount) yearList.append("\0");
return { fileList, kouzaList, file_titleList, hdateList, yearList };
}
QString RecordingCore::getAttribute2( QString url, QString attribute ) {
QEventLoop eventLoop;
QNetworkAccessManager mgr;
QObject::connect(&mgr, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));
QUrl url_html( url );
QNetworkRequest req;
req.setUrl( url_html );
QNetworkReply *reply = mgr.get(req);
eventLoop.exec();
QString content = reply->readAll();
QRegularExpression rx("https://vod-stream.nhk.jp/gogaku-stream/.+?/index.m3u8");
QRegularExpressionMatch match = rx.match( content );
attribute = match.captured(0);
return attribute;
}
bool RecordingCore::checkExecutable( QString path ) {
QFileInfo fileInfo( path );
if ( !fileInfo.exists() ) {
emit errorOccurred( path + QString::fromUtf8( "が見つかりません。" ) );
return false;
} else if ( !fileInfo.isExecutable() ) {
emit errorOccurred( path + QString::fromUtf8( "は実行可能ではありません。" ) );
return false;
}
return true;
}
bool RecordingCore::isFfmpegAvailable(QString& path) {
auto fileExists = [](const QString& filePath) {
return QFileInfo(filePath).exists();
};
#ifdef Q_OS_WIN
const QString exeExt = ".exe";
#else
const QString exeExt = "";
#endif
path = runtime.ffmpegFolder() + "ffmpeg" + exeExt;
QStringList baseDirs;
#ifdef Q_OS_MACOS
baseDirs.append(runtime.saveFolder());
baseDirs.append(Utility::appConfigLocationPath());
baseDirs.append(Utility::ConfigLocationPath());
baseDirs.append("/usr/local/bin/");
baseDirs.append("/opt/homebrew/bin/");
baseDirs.append(Utility::applicationBundlePath());
#else
baseDirs.append(Utility::applicationBundlePath());
baseDirs.append(runtime.saveFolder());
#endif
bool found = false;
for (const QString& dir : baseDirs) {
QString candidate = QDir(dir).filePath("ffmpeg" + exeExt);
if (fileExists(candidate)) {
path = candidate;
found = true;
break;
}
}
if (!found)
path = QDir(Utility::applicationBundlePath()).filePath("ffmpeg" + exeExt);
if (!checkExecutable(path))
return false;
return true;
}
//通常ファイルが存在する場合のチェックのために末尾にセパレータはついていないこと
bool RecordingCore::checkOutputDir( QString dirPath ) {
bool result = false;
QFileInfo dirInfo( dirPath );
if ( dirInfo.exists() ) {
if ( !dirInfo.isDir() )
emit errorOccurred( QString::fromUtf8( "「" ) + dirPath + QString::fromUtf8( "」が存在しますが、フォルダではありません。" ) );
else if ( !dirInfo.isWritable() )
emit errorOccurred( QString::fromUtf8( "「" ) + dirPath + QString::fromUtf8( "」フォルダが書き込み可能ではありません。" ) );
else
result = true;
} else {
QDir dir;
if ( !dir.mkpath( dirPath ) )
emit errorOccurred( QString::fromUtf8( "「" ) + dirPath + QString::fromUtf8( "」フォルダの作成に失敗しました。" ) );
else
result = true;
}
return result;
}
//--------------------------------------------------------------------------------
QStringList RecordingCore::one2two(const QStringList &hdateList) {
QStringList result;
QRegularExpression rx("(\\d+)(?:\\D+)(\\d+)");
for (const QString &hdate : hdateList) {
QRegularExpressionMatch match = rx.match(hdate);
if (match.hasMatch()) {
int month = match.captured(1).toInt();
int day = match.captured(2).toInt();
QString formatted = QString::number(month + 100).right(2)
+ QString::fromUtf8("月")
+ QString::number(day + 100).right(2)
+ QString::fromUtf8("日放送分");
result << formatted;
} else {
result << hdate; // マッチしなかった場合は元の文字列をそのまま追加
}
}
return result;
}
QStringList RecordingCore::thisweekfile( QStringList fileList2, QStringList codeList ) {
QStringList result;
for ( int i = 0; i < fileList2.count(); i++ ) {
QString filex = fileList2[i];
int filexxx = codeList[i].toInt() + fileList2.count() ;
filex.replace( codeList[i].right( 3 ) , QString::number( filexxx ).right( 3 ) );
filex.remove( "-re01" );
result << filex;
}
return result;
}
//--------------------------------------------------------------------------------
bool RecordingCore::illegal( char c ) {
bool result = false;
switch ( c ) {
case '/':
case '\\':
case ':':
case '*':
case '?':
case '"':
case '<':
case '>':
case '|':
case '#':
case '{':
case '}':
case '%':
case '&':
case '~':
result = true;
break;
default:
break;
}
return result;
}
QString RecordingCore::formatName( QString format, QString kouza, QString hdate, QString file, QString nendo, QString dupnmb, bool checkIllegal ) {
int month = hdate.left( 2 ).toInt();
int year = nendo.right( 4 ).toInt();
int day = hdate.mid( 3, 2 ).toInt();
// int year1 = QDate::currentDate().year();
QDate on_air_date1(year, month, day);
if ( on_air_date1 <= nendo_end_date1 ) nendo = nendo1;
if ( on_air_date1 >= nendo_start_date1 ) nendo = nendo2;
if ( file.right( 4 ) == ".flv" )
file = file.left( file.length() - 4 );
QString dupnmb1 = dupnmb;
if ( format.contains( "%i", Qt::CaseInsensitive)) dupnmb1 = "";
if ( format.contains( "%_%i", Qt::CaseInsensitive)) { dupnmb.replace( "-", "_" ); format.remove( "%_" ); }
QString result;
bool percent = false;
for ( int i = 0; i < format.length(); i++ ) {
QChar qchar = format[i];
if ( percent ) {
percent = false;
char ascii = qchar.toLatin1();
if ( checkIllegal && illegal( ascii ) )
continue;
switch ( ascii ) {
case 'k': result += kouza; break;
case 'h': result += hdate.left( 6 ) + QString::fromUtf8( "放送分" ) + dupnmb1; break;
case 'f': result += file; break;
//case 'r': result += MainWindow::applicationDirPath(); break;
//case 'p': result += QDir::separator(); break;
case 'Y': result += QString::number( year ); break;
case 'y': result += QString::number( year ).right( 2 ); break;
case 'N': result += nendo + QString::fromUtf8( "年度" ); break;
case 'n': result += nendo.right( 2 ) + QString::fromUtf8( "年度" ); break;
case 'M': result += QString::number( month + 100 ).right( 2 ); break;
case 'm': result += QString::number( month ); break;
case 'D': result += QString::number( day + 100 ).right( 2 ) + dupnmb1; break;
case 'd': result += QString::number( day ) + dupnmb1; break;
case 'i': result += dupnmb; break;
case 'x': break;
case 's': break;
default: result += qchar; break;
}
} else {
if ( qchar == QChar( '%' ) )
percent = true;
else if ( checkIllegal && illegal( qchar.toLatin1() ) )
continue;
else
result += qchar;
}
}
return result;
}
static const QStringList& levelWordsBase()
{
static QStringList list;
if (list.isEmpty()) {
for (int i = 0; i < Constants::LEVEL_WORDS_COUNT; ++i) {
list << QString::fromUtf8(Constants::LEVEL_WORDS[i]);
}
}
return list;
}
static const QStringList& levelWordsWithHen()
{
static QStringList list;
if (list.isEmpty()) {
for (const QString &w : levelWordsBase()) {
list << (w + "編");
}
}
return list;
}
//--------------------------------------------------------------------------------
bool RecordingCore::captureStream( QString kouza, QString hdate, QString file, QString nendo, QString dir, QString this_week, QString json_path ) {
QString titleFormat = runtime.titleFormatAt(1);
QString fileNameFormat = runtime.fileNameFormatAt(1);
QString outputDir = runtime.saveFolder();
QString extension = runtime.audioExtension();
kouza.remove( QString::fromUtf8("中学生の"));
if ( this_week == "R" )
outputDir = outputDir + QString::fromUtf8( "[前週]" )+ "/" + kouza;
else
outputDir = outputDir + kouza;
if ( !checkOutputDir( outputDir ) )
return false;
outputDir += QDir::separator(); //通常ファイルが存在する場合のチェックのために後から追加する
int month = hdate.left( 2 ).toInt();
int year = nendo.right( 4 ).toInt();
int day = hdate.mid( 3, 2 ).toInt();
if ( 2022 > year ) return false;
int year1 = QDate::currentDate().year();
if ( month <= 4 && QDate::currentDate().year() > year )
year = year + (year1 - year);
QDate onair( year, month, day );
QString yyyymmdd = onair.toString( "yyyy_MM_dd" );
QString kon_nendo = nendo1; //QString::number(year1);
QString id3tagTitle = formatName( titleFormat, kouza, hdate, file, yyyymmdd.left(4), "", false );
QString outFileName = formatName( fileNameFormat, kouza, hdate, file, yyyymmdd.left(4), "", true );
QFileInfo fileInfo( outFileName );
QString outBasename = fileInfo.completeBaseName();
if ( m_cancelRequested || isCanceled ) return false;
// 2013/04/05 オーディオフォーマットの変更に伴って拡張子の指定に対応
QString extension1 = normalizeExtension(extension);
if ( extension.left( 3 ) == "mp3" ) extension1 = "mp3";
outFileName = outBasename + "." + extension1;
#ifdef Q_OS_WIN
QString null( "nul" );
#else
QString null( "/dev/null" );
#endif
if ( runtime.flag( QString::fromUtf8( Constants::KEY_SKIP )) && QFile::exists( outputDir + outFileName ) ) {
if ( this_week == "R" ) {
emit messageGenerated( QString::fromUtf8( "スキップ:[前週] " ) + kouza + QString::fromUtf8( " " ) + yyyymmdd );
} else {
emit messageGenerated( QString::fromUtf8( "スキップ: " ) + kouza + QString::fromUtf8( " " ) + yyyymmdd );
}
return true;
}
if ( this_week == "R" ) {
emit messageGenerated( QString::fromUtf8( "レコーディング中:[前週] " ) + kouza + QString::fromUtf8( " " ) + yyyymmdd );
} else {
emit messageGenerated( QString::fromUtf8( "レコーディング中: " ) + kouza + QString::fromUtf8( " " ) + yyyymmdd );
}
QString dstPath;
dstPath = outputDir + outFileName;
QString filem3u8a; QString filem3u8b; QString prefix1a = prefix1; QString prefix2a = prefix2; QString prefix3a = prefix3;
if ( dir == "" ) { prefix1a.remove("/mp4"); prefix2a.remove("/mp4"); prefix3a.remove("/mp4");
} else { prefix1a.replace( "mp4", dir ); prefix2a.replace( "mp4", dir ); prefix3a.replace( "mp4", dir ); };
filem3u8a = prefix1a + file + "/index.m3u8";
filem3u8b = prefix2a + file + "/index.m3u8";
QString filem3u8c = prefix3a + file + "/index.m3u8";
if ( m_cancelRequested || isCanceled ) return false;
QString id3tag_album = LegacyFormatEngine::buildId3TagAlbum(kouza, fileNameFormat);
RecordingRequest req;
int l = (json_path.length() == 13) ? 10 : json_path.length() - 3;
QString corner_site_id = json_path.right(2);
if (corner_site_id == "x1" || corner_site_id == "y1")
corner_site_id = "01";
QString key = json_path.left(l) + "_" + corner_site_id;
auto &repo = ProgramRepository::instance();
if (!repo.thumbnail_map.contains(key)){
req.thumbnail.enabled = false;
} else {
req.thumbnail.enabled = runtime.flag( QString::fromUtf8( Constants::KEY_THUMBNAIL )) && runtime.audioExtension() != "aac";
req.thumbnail.imagePath = repo.thumbnail_map.value(key);
}
req.input.inputPath = filem3u8a;
req.outputPath = dstPath;
req.input.httpSeekable = true;
req.meta.title = id3tagTitle;
req.meta.artist = "NHK";
req.meta.album = id3tag_album;
req.meta.date = QString::number(year);
req.meta.genre = "Speech";
req.presetKey = runtime.audioExtension();
req.extension = normalizeExtension(req.presetKey);
PresetRepository::resolve(req.presetKey, req);
FfmpegCapabilities caps =
FfmpegCapabilities::detect(ffmpeg);
FfmpegRunRequest runReq;
runReq.program = ffmpeg;
runReq.args = FfmpegCommandBuilder::build(req, caps, req.outputPath);
runReq.finalPath = req.outputPath;
runReq.saveFolder = outputDir;
runReq.extension = req.extension;
if ( m_cancelRequested || isCanceled ) return false;
m_runner.run(runReq);
return true;
}
bool RecordingCore::captureStream_json( QString kouza, QString hdate, QString file, QString nendo, QString title, QString dupnmb, QString json_path ) {
QString titleFormat = runtime.titleFormatAt(0);
QString fileNameFormat = runtime.fileNameFormatAt(0);
QString outputDir = runtime.saveFolder();
QString extension = runtime.audioExtension();
QString Xml_koza = "";
Xml_koza = map.value( json_path );
bool ouyou_koza_separation_flag = Xml_koza.contains( "kouza3", Qt::CaseInsensitive) && (fileNameFormat.contains( "%s", Qt::CaseInsensitive) || fileNameFormat.contains( "%x", Qt::CaseInsensitive) || runtime.flag( QString::fromUtf8( Constants::KEY_KOZA_SEPARATION )) ) ;
if (runtime.flag( QString::fromUtf8( Constants::KEY_KOZA_SEPARATION )) ) fileNameFormat.remove( "%s" );
if ( ouyou_koza_separation_flag ) {
QString level = LegacyFormatEngine::extractLevelFromTitle(title, kouza);
if (!level.isEmpty()) {
if (runtime.flag( QString::fromUtf8( Constants::KEY_NAME_SPACE )))
kouza += "【" + level + "】";
else
kouza += " " + level;
}
}
QString id3tagTitle = formatName( titleFormat, kouza, hdate, title, nendo, dupnmb, false );
QString outFileName = formatName( fileNameFormat, kouza, hdate, title, nendo, dupnmb, true );
QFileInfo fileInfo( outFileName );
QString outBasename = fileInfo.completeBaseName();
QString kouza_tmp = kouza;
if( runtime.flag( QString::fromUtf8( Constants::KEY_TAG_SPACE )) ) id3tagTitle = id3tagTitle.replace( " ", "_" );
if( runtime.flag( QString::fromUtf8( Constants::KEY_NAME_SPACE )) ) {
outBasename = outBasename.replace( " ", "_" );
kouza_tmp = kouza.replace( " ", "_" );
}
outputDir = outputDir + kouza_tmp;
if ( !checkOutputDir( outputDir ) )
return false;
outputDir += QDir::separator(); //通常ファイルが存在する場合のチェックのために後から追加する
if ( m_cancelRequested || isCanceled ) return false;
// 2013/04/05 オーディオフォーマットの変更に伴って拡張子の指定に対応
QString extension1 = extension;
if ( extension.left( 3 ) == "mp3" ) extension1 = "mp3";
outFileName = outBasename + "." + extension1;
#ifdef Q_OS_WIN
QString null( "nul" );
#else
QString null( "/dev/null" );
#endif
int month = hdate.left( 2 ).toInt();
int year = nendo.right( 4 ).toInt();
int day = hdate.mid( 3, 2 ).toInt();
QDate onair( year, month, day );
QString yyyymmdd = onair.toString( "yyyy_MM_dd" );
QString kon_nendo = nendo1; //QString::number(year1);
if ( runtime.flag( QString::fromUtf8( Constants::KEY_SKIP )) && QFile::exists( outputDir + outFileName ) ) {
emit messageGenerated( QString::fromUtf8( "スキップ: " ) + kouza + QString::fromUtf8( " " ) + yyyymmdd + dupnmb);
return true;
}
emit messageGenerated( QString::fromUtf8( "レコーディング中: " ) + kouza + QString::fromUtf8( " " ) + yyyymmdd + dupnmb );
QString dstPath;
dstPath = outputDir + outFileName;
QStringList arguments_v = { "-http_seekable", "0", "-version", "0" };
QProcess process_v;
process_v.setProgram( ffmpeg );
process_v.setArguments( arguments_v );
process_v.start();
process_v.waitForFinished();
QString str_v = process_v.readAllStandardError();
process_v.kill();
process_v.close();
QString arguments00 = "-y -http_seekable 0 -i";
if (str_v.contains( "Option not found" )) {
arguments00 = "-y -i";
}
QStringList arguments0 = arguments00.split(" ");
QString arguments01 = "-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 120";
QStringList arguments1 = arguments01.split(" ");
QString filem3u8aA = file;
QString dstPathA = outputDir + outFileName;
QString id3tagTitleA = id3tagTitle;
// QString id3tag_album = kouza;
if ( m_cancelRequested || isCanceled ) return false;
// if ( fileNameFormat.contains( "%x", Qt::CaseInsensitive) )
QString id3tag_album = LegacyFormatEngine::buildId3TagAlbum(kouza, fileNameFormat);
RecordingRequest req;
int l = (json_path.length() == 13) ? 10 : json_path.length() - 3;
QString corner_site_id = json_path.right(2);
if (corner_site_id == "x1" || corner_site_id == "y1")
corner_site_id = "01";
QString key = json_path.left(l) + "_" + corner_site_id;
auto &repo = ProgramRepository::instance();
if (!repo.thumbnail_map.contains(key)){
req.thumbnail.enabled = false;
} else {
req.thumbnail.enabled = runtime.flag( QString::fromUtf8( Constants::KEY_THUMBNAIL )) && runtime.audioExtension() != "aac";
req.thumbnail.imagePath = repo.thumbnail_map.value(key);
}
req.input.inputPath = filem3u8aA;
req.outputPath = dstPathA;
req.includeOutputPath = false;
req.input.httpSeekable = true;
req.meta.title =id3tagTitleA;
req.meta.artist = "NHK";
req.meta.album = id3tag_album;
req.meta.date = nendo;
req.meta.genre = "Speech";
req.presetKey = runtime.audioExtension();
req.extension = normalizeExtension(req.presetKey);
PresetRepository::resolve(req.presetKey, req);
FfmpegCapabilities caps =
FfmpegCapabilities::detect(ffmpeg);
FfmpegRunRequest runReq;
runReq.program = ffmpeg;
runReq.args = FfmpegCommandBuilder::build(req, caps, req.outputPath);
runReq.finalPath = req.outputPath;
runReq.saveFolder = outputDir;
runReq.extension = req.extension;
if ( m_cancelRequested || isCanceled ) return false;
m_runner.run(runReq);
return true;
}
QString RecordingCore::ffmpeg_process( QStringList arguments ) {
Error_mes = "";
QProcess process;
process.setProgram( ffmpeg );
process.setArguments( arguments );
process.start();
if ( !process.waitForStarted( -1 ) ) {
Error_mes = processError[process.error()];
return "1";
}
// ユーザのキャンセルを確認しながらffmpegの終了を待つ
while ( !process.waitForFinished( CancelCheckTimeOut ) ) {
// キャンセルボタンが押されていたらffmpegをkillしてリターン
/*
if ( isCanceled ) {
process.kill();
return "2";
}
*/
// 単なるタイムアウトは継続
if ( process.error() == QProcess::Timedout )
continue;
if ( process.error() != QProcess::Timedout ) {
// エラー発生時はメッセージを表示し、出力ファイルを削除してリターン
Error_mes = processError[process.error()];
return "3";
}
}
QString ffmpeg_Error;
ffmpeg_Error.append(process.readAllStandardError());
// ffmpeg終了ステータスに応じた処理をしてリターン
if ( ffmpeg_Error.contains("HTTP error") || ffmpeg_Error.contains("Unable to open resource:") || ffmpeg_Error.contains("error") ) {
Error_mes = "ffmpeg error";
if ( ffmpeg_Error.contains("HTTP error") ) Error_mes = "HTTP error";
if ( ffmpeg_Error.contains("Unable to open resource:") ) Error_mes = "Unable to open resource";
process.kill();
return "3";
}
if ( process.exitCode() ) {
process.kill();
return "4";
}
process.kill();
process.close();
return "";
}
QMap<QString, QString> RecordingCore::map = {
{ "小学生の基礎英語", "english/basic0" }, // 小学生の基礎英語
{ "中学生の基礎英語 レベル1", "english/basic1" }, // 中学生の基礎英語 レベル1
{ "中学生の基礎英語 レベル2", "english/basic2" }, // 中学生の基礎英語 レベル2
// { "中高生の基礎英語 in English", "english/basic3" }, // 中高生の基礎英語 in English
{ "英会話タイムトライアル", "english/timetrial" }, // 英会話タイムトライアル
{ "ラジオ英会話", "english/kaiwa" }, // ラジオ英会話
{ "ラジオビジネス英語", "english/business1" }, // ラジオビジネス英語
{ "エンジョイ・シンプル・イングリッシュ", "english/enjoy" }, // エンジョイ・シンプル・イングリッシュ
{ "GGQY3M1929_01", "english/basic0" }, // 小学生の基礎英語
{ "148W8XX226_01", "english/basic1" }, // 中学生の基礎英語 レベル1
{ "83RW6PK3GG_01", "english/basic2" }, // 中学生の基礎英語 レベル2
// { "B2J88K328M_01", "english/basic3" }, // 中高生の基礎英語 in English
{ "8Z6XJ6J415_01", "english/timetrial" }, // 英会話タイムトライアル
{ "PMMJ59J6N2_01", "english/kaiwa" }, // ラジオ英会話
{ "368315KKP8_01", "english/business1" }, // ラジオビジネス英語
{ "BR8Z3NX7XM_01", "english/enjoy" }, // エンジョイ・シンプル・イングリッシュ
{ "77RQWQX1L6_01", "english/gendaieigo" }, // ニュースで学ぶ「現代英語」
{ "XQ487ZM61K_x1", "french/kouza" }, // まいにちフランス語 入門編
{ "XQ487ZM61K_y1", "french/kouza2" }, // まいにちフランス語 応用編
{ "N8PZRZ9WQY_x1", "german/kouza" }, // まいにちドイツ語 入門編
{ "N8PZRZ9WQY_y1", "german/kouza2" }, // まいにちドイツ語 応用編
{ "NRZWXVGQ19_x1", "spanish/kouza" }, // まいにちスペイン語 入門編
{ "NRZWXVGQ19_y1", "spanish/kouza2" }, // まいにちスペイン語 応用編
{ "LJWZP7XVMX_x1", "italian/kouza" }, // まいにちイタリア語 入門編
{ "LJWZP7XVMX_y1", "italian/kouza2" }, // まいにちイタリア語 応用編
{ "YRLK72JZ7Q_x1", "russian/kouza" }, // まいにちロシア語 入門編
{ "YRLK72JZ7Q_y1", "russian/kouza2" }, // まいにちロシア語 応用編
{ "983PKQPYN7_01", "chinese/kouza" }, // まいにち中国語
{ "MYY93M57V6_01", "chinese/stepup" }, // ステップアップ中国語
{ "LR47WW9K14_01", "hangeul/kouza" }, // まいにちハングル講座
{ "NLJM5V3WXK_01", "hangeul/stepup" }, // ステップアップ ハングル講座
{ "XQ487ZM61K_01", "french/kouza3" }, // まいにちフランス語 入門編/初級編/応用編
{ "N8PZRZ9WQY_01", "german/kouza3" }, // まいにちドイツ語 入門編/初級編/応用編
{ "NRZWXVGQ19_01", "spanish/kouza3" }, // まいにちスペイン語 入門編/初級編/中級編/応用編
{ "LJWZP7XVMX_01", "italian/kouza3" }, // まいにちイタリア語 入門編/初級編/応用編
{ "YRLK72JZ7Q_01", "russian/kouza3" }, // まいにちロシア語 入門編/初級編/応用編
{ "983PKQPYN7_s1", "chinese/kouza4" }, // まいにち中国語
{ "LR47WW9K14_s1", "hangeul/kouza4" }, // まいにちハングル講座
};
QMultiMap<QString, QString> RecordingCore::multimap = {
{ "小学生の基礎英語", "english/basic0" }, // 小学生の基礎英語
{ "中学生の基礎英語 レベル1", "english/basic1" }, // 中学生の基礎英語 レベル1
{ "中学生の基礎英語 レベル2", "english/basic2" }, // 中学生の基礎英語 レベル2
// { "中高生の基礎英語 in English", "english/basic3" }, // 中高生の基礎英語 in English
{ "英会話タイムトライアル", "english/timetrial" }, // 英会話タイムトライアル
{ "ラジオ英会話", "english/kaiwa" }, // ラジオ英会話
{ "ラジオビジネス英語", "english/business1" }, // ラジオビジネス英語
{ "エンジョイ・シンプル・イングリッシュ", "english/enjoy" }, // エンジョイ・シンプル・イングリッシュ
{ "77RQWQX1L6_01", "english/gendaieigo" }, // ニュースで学ぶ「現代英語」
{ "GGQY3M1929_01", "english/basic0" }, // 小学生の基礎英語
{ "148W8XX226_01", "english/basic1" }, // 中学生の基礎英語 レベル1
{ "83RW6PK3GG_01", "english/basic2" }, // 中学生の基礎英語 レベル2
// { "B2J88K328M_01", "english/basic3" }, // 中高生の基礎英語 in English
{ "8Z6XJ6J415_01", "english/timetrial" }, // 英会話タイムトライアル
{ "PMMJ59J6N2_01", "english/kaiwa" }, // ラジオ英会話
{ "368315KKP8_01", "english/business1" }, // ラジオビジネス英語
{ "BR8Z3NX7XM_01", "english/enjoy" }, // エンジョイ・シンプル・イングリッシュ
{ "XQ487ZM61K_x1", "french/kouza" }, // まいにちフランス語 入門編
{ "XQ487ZM61K_y1", "french/kouza2" }, // まいにちフランス語 応用編
{ "N8PZRZ9WQY_x1", "german/kouza" }, // まいにちドイツ語 入門編
{ "N8PZRZ9WQY_y1", "german/kouza2" }, // まいにちドイツ語 応用編
{ "NRZWXVGQ19_x1", "spanish/kouza" }, // まいにちスペイン語 入門編
{ "NRZWXVGQ19_y1", "spanish/kouza2" }, // まいにちスペイン語 応用編
{ "LJWZP7XVMX_x1", "italian/kouza" }, // まいにちイタリア語 入門編
{ "LJWZP7XVMX_y1", "italian/kouza2" }, // まいにちイタリア語 応用編
{ "YRLK72JZ7Q_x1", "russian/kouza" }, // まいにちロシア語 入門編
{ "YRLK72JZ7Q_y1", "russian/kouza2" }, // まいにちロシア語 応用編
{ "983PKQPYN7_01", "chinese/kouza" }, // まいにち中国語
{ "MYY93M57V6_01", "chinese/stepup" }, // ステップアップ中国語
{ "LR47WW9K14_01", "hangeul/kouza" }, // まいにちハングル講座
{ "NLJM5V3WXK_01", "hangeul/stepup" }, // ステップアップ ハングル講座
{ "XQ487ZM61K_01", "french/kouza" }, // まいにちフランス語 入門編/初級編/応用編
{ "XQ487ZM61K_01", "french/kouza2" }, // まいにちフランス語 入門編/初級編/応用編
{ "N8PZRZ9WQY_01", "german/kouza" }, // まいにちドイツ語 入門編/初級編/応用編
{ "N8PZRZ9WQY_01", "german/kouza2" }, // まいにちドイツ語 入門編/初級編/応用編
{ "NRZWXVGQ19_01", "spanish/kouza" }, // まいにちスペイン語 入門編/初級編/中級編/応用編
{ "NRZWXVGQ19_01", "spanish/kouza2" }, // まいにちスペイン語 入門編/初級編/中級編/応用編
{ "LJWZP7XVMX_01", "italian/kouza" }, // まいにちイタリア語 入門編/初級編/応用編
{ "LJWZP7XVMX_01", "italian/kouza2" }, // まいにちイタリア語 入門編/初級編/応用編
{ "YRLK72JZ7Q_01", "russian/kouza" }, // まいにちロシア語 入門編/初級編/応用編
{ "YRLK72JZ7Q_01", "russian/kouza2" }, // まいにちロシア語 入門編/初級編/応用編
{ "983PKQPYN7_s1", "chinese/kouza" }, // まいにち中国語
{ "LR47WW9K14_s1", "hangeul/kouza" }, // まいにちハングル講座
};
QMultiMap<QString, QString> RecordingCore::multimap1 = {
{ "983PKQPYN7_s1", "983PKQPYN7_01" }, // まいにち中国語
{ "LR47WW9K14_s1", "LR47WW9K14_01" }, // まいにちハングル講座
{ "6LPPKP6W8Q_s1", "6LPPKP6W8Q_01" }, // やさしい日本語
{ "6LPPKP6W8Q_s1", "D6RM27PGVM_01" }, // Learn Japanese from the News
{ "6LPPKP6W8Q_s1", "4MY6Q8XP88_01" }, // Living in Japan
};
void RecordingCore::run() {
QAbstractButton* checkbox[] = {
NULL
};
QTimeZone jstTimeZone("Asia/Tokyo");
QDateTime targetDateTime = QDateTime::fromString( "2025-04-07 10:00:00", "yyyy-MM-dd HH:mm:ss" );
targetDateTime.setTimeZone(jstTimeZone);
QDateTime currentDateTime = QDateTime::currentDateTime();
currentDateTime.setTimeZone(jstTimeZone);
if ( !isFfmpegAvailable( ffmpeg ) )
return;
QStringList ProgList;
ProgList = QStringList::fromVector( runtime.cliProgramIds() );
if ( runtime.cliProgramIds().isEmpty() ) {
ProgList.clear();
ProgList = QStringList::fromVector( runtime.checkedProgramIds() );
}
for ( int i = 0; i < ProgList.count() ; i++ ) {
// for ( const auto& id : ProgList ) {
if ( m_cancelRequested || isCanceled ) break;
QString Xml_koza = "";
Xml_koza = map.value( ProgList[i] );
if ( Xml_koza == "" || !(runtime.flag( QString::fromUtf8( Constants::KEY_LAST_WEEK ))) || runtime.flag( QString::fromUtf8( Constants::KEY_BOTH_WEEKS )) ) {
QStringList fileList2;
QStringList kouzaList2;
QStringList file_titleList;
QStringList hdateList1;
QStringList yearList;
QStringList site_id_List; site_id_List.clear();
if ( multimap1.contains( ProgList[i] ) )
site_id_List += multimap1.values( ProgList[i] );
else
site_id_List += ProgList[i];
for ( int n = 0; n < site_id_List.count(); n++ ){
if ( m_cancelRequested || isCanceled ) break;
std::tie( fileList2, kouzaList2, file_titleList, hdateList1, yearList ) = getJsonData( site_id_List[n] );
QStringList hdateList2 = one2two( hdateList1 );
QStringList dupnmbList;
dupnmbList.clear() ;
int k = 1;
for ( int ii = 0; ii < hdateList2.count() ; ii++ ) dupnmbList += "" ;
for ( int ii = 0; ii < hdateList2.count() - 1 ; ii++ ) {
if ( hdateList2[ii] == hdateList2[ii+1] ) {
if ( k == 1 ) dupnmbList[ii].replace( "", "-1" );
k = k + 1;
QString dup = "-" + QString::number( k );
dupnmbList[ii+1].replace( "", dup );
} else {
k = 1;
}
}
if ( fileList2.count() && fileList2.count() == kouzaList2.count() && fileList2.count() == hdateList2.count() ) {
for ( int j = 0; j < fileList2.count(); j++ ){
if ( fileList2[j] == "" || fileList2[j] == "null" ) continue;
captureStream_json( kouzaList2[j], hdateList2[j], fileList2[j], yearList[j], file_titleList[j], dupnmbList[j], site_id_List[n] );
}
}
}
}