forked from CSReviser/CaptureStream
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mp3.cpp
284 lines (238 loc) · 10.3 KB
/
mp3.cpp
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
/*
Copyright (C) 2009-2013 jakago
This file is part of CaptureStream, the flv downloader for NHK radio
language courses.
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 <http://www.gnu.org/licenses/>.
*/
#include "mp3.h"
#include <QFile>
#include <QDateTime>
namespace MP3 {
struct id3v22_header {
char identifier[3]; // "ID3"
char version[2]; // ID3v2.2.0 -> $02 00
char flags; // %ab000000 -> a:Unsynchronisation, b:compression
char size[4]; // 4 * %0xxxxxxx, excluding the header (total tag size - 10)
};
struct id3v22_frame_header {
char identifier[3];
char size[3]; // excluding frame header (frame size - 6)
};
void encodeSize( long int32, char* byte4 ) {
byte4[0] = (int32 & (0x0000007f << 21)) >> 21;
byte4[1] = (int32 & (0x0000007f << 14)) >> 14;
byte4[2] = (int32 & (0x0000007f << 7)) >> 7;
byte4[3] = int32 & 0x0000007f;
}
long decodeSize( const char* byte4 ) {
return ((long)(byte4[0] & 0x7f) << 21) + ((long)(byte4[1] & 0x7f) << 14) +
((long)(byte4[2] & 0x7f) << 7) + (long)(byte4[3] & 0x7f);
}
void asciiFrame( QByteArray& frames, id3v22_frame_header& frameHeader, QString string ) {
static const char asciiMark = '\0';
QByteArray asciiBytes = string.toLatin1();
long length = asciiBytes.size() + 2; // 末尾の1バイトの'\0'と文字コードの指定に1バイト
if ( length > 2 && length < 0x01000000 ) {
frameHeader.size[0] = (length & 0x00ff0000) >> 16;
frameHeader.size[1] = (length & 0x0000ff00) >> 8;
frameHeader.size[2] = length & 0x000000ff;
frames += QByteArray( (const char*)&frameHeader, sizeof (frameHeader) );
frames += asciiMark;
frames += asciiBytes;
frames += '\0';
}
}
void unicodeFrame( QByteArray& frames, id3v22_frame_header& frameHeader, QString string, QTextCodec* utf16 ) {
static const char unicodeMark = '\1';
QByteArray utf16Bytes = utf16->fromUnicode( string );
long length = utf16Bytes.size() + 3; // 末尾の2バイトの'\0'と文字コードの指定に1バイト
if ( length > 3 && length < 0x01000000 ) {
frameHeader.size[0] = (length & 0x00ff0000) >> 16;
frameHeader.size[1] = (length & 0x0000ff00) >> 8;
frameHeader.size[2] = length & 0x000000ff;
frames += QByteArray( (const char*)&frameHeader, sizeof (frameHeader) );
frames += unicodeMark;
frames += utf16Bytes;
frames += '\0';
frames += '\0';
}
}
void createTag( QByteArray& tagBytes, QString album, QString title, QString year, QString artist, QTextCodec* utf16 ) {
if ( utf16 ) {
id3v22_header header = { { 'I', 'D', '3' }, { '\x02', '\x00' }, '\0', {} };
id3v22_frame_header albumHeader = { { 'T', 'A', 'L' }, {} };
id3v22_frame_header titleHeader = { { 'T', 'T', '2' }, {} };
id3v22_frame_header yearHeader = { { 'T', 'Y', 'E' }, {} }; //numeric string, four characters long
id3v22_frame_header artistHeader = { { 'T', 'P', '1' }, {} };
id3v22_frame_header genreHeader = { { 'T', 'C', 'O' }, {} };
QByteArray frames;
unicodeFrame( frames, albumHeader, album, utf16 );
unicodeFrame( frames, titleHeader, title, utf16 );
asciiFrame( frames, yearHeader, year );
unicodeFrame( frames, artistHeader, artist, utf16 );
asciiFrame( frames, genreHeader, "(101)" );
if ( frames.size() ) {
encodeSize( frames.size(), header.size );
tagBytes = QByteArray( (const char*)&header, sizeof (header) );
tagBytes += frames;
}
}
}
// 2.2.0~2.4.0のタグのサイズを計算する
long tagSize( QByteArray buffer ) {
//static const int offset_identifier = 0;
static const int offset_version = 3;
//static const int offset_flags = 5;
static const int offset_size = 6;
static const int offset_data = 10;
static const char* identifier = "ID3";
long result = 0;
const char* data = buffer.constData();
const int length = buffer.size();
if ( length > 10 && !strncmp( data, identifier, offset_version ) ) {
// ID3v2.2.0 と ID3v2.3.0 のみサポート
if ( data[offset_version] >= 2 && data[offset_version] <= 4 && data[offset_version + 1] == 0 )
result = decodeSize( data + offset_size ) + offset_data;
}
return result;
}
//--------------------------------------------------------------------------------
struct FlvHeader {
unsigned char signature[3];
unsigned char version;
unsigned char flags;
unsigned char offset[4];
};
struct FlvTag {
unsigned char previousTagSize[4];
unsigned char type;
unsigned char bodyLength[3];
unsigned char timestamp[3];
unsigned char timestampExtended;
unsigned char streamId[3];
//このあとにbodyLengthのデータが続く
};
bool flv2mp3( const QString& flvPath, const QString& mp3Path, QString& error ) {
bool result = false;
try {
QFile flv( flvPath );
if ( !flv.open( QIODevice::ReadOnly ) ) {
throw QString::fromUtf8( "flvファイルのオープンに失敗しました。Code:" ) +
QString::number( flv.error() ) + " Description:" + flv.errorString();
}
QByteArray buffer = flv.readAll();
flv.close();
long bufferSize = buffer.length();
if ( bufferSize < (long)sizeof (FlvHeader) )
throw QString::fromUtf8( "flvファイルにヘッダが含まれていません。" );
FlvHeader& header = *(FlvHeader*)buffer.constData();
if ( strncmp( (const char*)header.signature, "FLV", sizeof header.signature ) )
throw QString::fromUtf8( "flvファイルではありません。" );
if ( (header.flags & 4) == 0 )
throw QString::fromUtf8( "音声データが含まれていません。" );
if ( header.offset[0] || header.offset[1] || header.offset[2] || header.offset[3] != sizeof header )
throw QString::fromUtf8( "flvファイルが対応できる形式ではありません。" );
long readSize = sizeof (FlvHeader);
QFile mp3( mp3Path );
if ( !mp3.open( QIODevice::WriteOnly ) ) {
throw QString::fromUtf8( "mp3ファイルのオープンに失敗しました。Code:" ) +
QString::number( mp3.error() ) + " Description:" + mp3.errorString();
}
const char* byte = buffer.constData();
while ( true ) {
if ( bufferSize - readSize == 4 ) //最後のPreviousTagSize
throw true;
if ( bufferSize - readSize < (long)sizeof (FlvTag) )
throw QString::fromUtf8( "flvファイルの内容が不正です。" );
FlvTag& tag = *(FlvTag*)(byte + readSize);
readSize += sizeof (FlvTag);
long bodyLength = (tag.bodyLength[0] << 16) + (tag.bodyLength[1] << 8) + tag.bodyLength[2];
if ( bufferSize - readSize < bodyLength )
throw QString::fromUtf8( "flvファイルの内容が不正です。" );
if ( tag.type == 0x08 ) {
if ( (byte[readSize] & 0x00f0) != 0x20 )
throw QString::fromUtf8( "音声データがmp3ではありません。" );
if ( mp3.write( byte + readSize + 1, bodyLength - 1 ) != bodyLength - 1 )
throw QString::fromUtf8( "mp3ファイルの書き込みに失敗しました。" );
}
readSize += bodyLength;
}
mp3.close();
} catch ( bool ) {
result = true;
} catch ( QString& message ) {
QFile::remove( mp3Path );
error = message;
}
return result;
}
//--------------------------------------------------------------------------------
QString mkTempName( QString original ) {
QString result;
for ( int i = 0; i < 100; i++ ) {
QString now = QDateTime::currentDateTime().toString( "yyyyMMddhhmmsszzz" );
if ( !QFile::exists( original + now ) ) {
result = original + now;
break;
}
}
return result;
}
bool id3tag( QString fullPath, QString album, QString title, QString year, QString artist, QString error ) {
bool result = false;
try {
QTextCodec* utf16 = QTextCodec::codecForName( "UTF-16" );
if ( !utf16 )
throw QString::fromUtf8( "文字コードの変換ができないのでID3v1の書き込みを中止します。" );
QByteArray tagBytes;
MP3::createTag( tagBytes, album, title, year, artist, utf16 );
if ( !tagBytes.size() )
throw QString::fromUtf8( "書き込むべきタグが見当たらないため、タグの書き込みを中止します。" );
QString tempName = mkTempName( fullPath );
if ( !tempName.size() )
throw QString::fromUtf8( "作業用ファイル名が作成できないため、タグの書き込みを中止します。" );
if ( !QFile::rename( fullPath, tempName ) )
throw QString::fromUtf8( "ダウンロードしたMP3のファイル名が変更できないため、タグの書き込みを中止します。" );
QFile srcFile( tempName );
if ( !srcFile.open( QIODevice::ReadOnly ) )
throw QString::fromUtf8( "ダウンロードしたMP3ファイルを開けないため、タグの書き込みを中止します。" );
QFile dstFile( fullPath );
if ( !dstFile.open( QIODevice::WriteOnly ) ) {
srcFile.close();
throw QString::fromUtf8( "作業用ファイルの作成に失敗したため、タグの書き込みを中止します。Code:" ) +
QString::number( dstFile.error() ) + " Description:" + dstFile.errorString();
}
qint64 writtenSize = dstFile.write( tagBytes );
if ( writtenSize != tagBytes.size() ) {
dstFile.remove();
srcFile.rename( fullPath );
throw QString::fromUtf8( "作業用ファイルへの書き込みに失敗しました。" );
}
QByteArray buffer = srcFile.readAll();
srcFile.close();
long skip = MP3::tagSize( buffer );
writtenSize = dstFile.write( buffer.constData() + skip, buffer.size() - skip );
dstFile.close();
if ( writtenSize != buffer.size() - skip ) {
dstFile.remove();
srcFile.rename( fullPath );
throw QString::fromUtf8( "作業用ファイルへの書き込みに失敗しました。" );
}
if ( !srcFile.remove() )
throw QString::fromUtf8( "「" ) + tempName + QString::fromUtf8( "」の削除に失敗しました。" );
result = true;
} catch ( QString& message ) {
error = message;
}
return result;
}
}