-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathSmafWithVoiceMaker.java
337 lines (293 loc) · 13 KB
/
SmafWithVoiceMaker.java
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
/*
* Copyright (c) 2008 by Naohide Sano, All rights reserved.
*
* Programmed by Naohide Sano
*/
package vavi.sound.sampled.smaf;
import java.io.File;
import java.io.IOException;
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.UnsupportedAudioFileException;
import org.klab.commons.cli.Argument;
import org.klab.commons.cli.HelpOption;
import org.klab.commons.cli.Option;
import org.klab.commons.cli.Options;
import vavi.sound.mobile.AudioEngine;
import vavi.sound.sampled.FilterChain;
import vavi.sound.smaf.InvalidSmafDataException;
import vavi.sound.smaf.SmafMessage;
import vavi.sound.smaf.chunk.AudioSequenceDataChunk;
import vavi.sound.smaf.chunk.ContentsInfoChunk;
import vavi.sound.smaf.chunk.FileChunk;
import vavi.sound.smaf.chunk.PcmAudioTrackChunk;
import vavi.sound.smaf.chunk.SeekAndPhraseInfoChunk;
import vavi.sound.smaf.chunk.TrackChunk.FormatType;
import vavi.sound.smaf.chunk.TrackChunk.SequenceType;
import vavi.sound.smaf.chunk.WaveDataChunk;
import vavi.sound.smaf.chunk.WaveType;
import vavi.sound.smaf.message.EndOfSequenceMessage;
import vavi.sound.smaf.message.NopMessage;
import vavi.sound.smaf.message.VolumeMessage;
import vavi.sound.smaf.message.WaveMessage;
import vavi.sound.smaf.sequencer.WaveSequencer;
import static java.lang.System.getLogger;
/**
* SmafWithVoiceMaker.
*
* @author <a href="mailto:[email protected]">Naohide Sano</a> (nsano)
* @version 0.00 080415 nsano initial version <br>
*/
class SmafWithVoiceMaker {
private static final Logger logger = getLogger(SmafWithVoiceMaker.class.getName());
/** source PCM */
private AudioInputStream sourceAis;
/** output file */
private String filename;
/** time in second */
protected float time;
/** ADPCM sampling rate */
protected int samplingRate;
/** ADPCM sampling bits */
protected int bits;
/** ADPCM number of channels */
protected int channels;
/** master volume */
protected int masterVolume;
/** ADPCM volume */
protected int adpcmVolume;
/** */
private static int toReal(int base, int percent) {
return (int) ((float) base * percent / 100);
}
/**
*
* @param sourceAis source PCM
* @param filename output file
*/
public SmafWithVoiceMaker(AudioInputStream sourceAis, String filename, float time, int samplingRate, int bits, int channels, int masterVolume, int adpcmVolume) {
this(time, samplingRate, bits, channels, masterVolume, adpcmVolume);
this.sourceAis = sourceAis;
this.filename = filename;
}
/**
*
* @param time time in second
* @param bits ADPCM sampling bits
*/
protected SmafWithVoiceMaker(float time, int samplingRate, int bits, int channels, int masterVolume, int adpcmVolume) {
this.time = time;
this.samplingRate = samplingRate;
this.bits = bits;
this.channels = channels;
this.masterVolume = toReal(0x7f, masterVolume);
this.adpcmVolume = toReal(0x3f, adpcmVolume);
}
/**
* Creates a MFi.
* @throws IOException
* @throws UnsupportedAudioFileException
* @throws InvalidSmafDataException
* @return total size written
*/
public int create() throws IOException, UnsupportedAudioFileException, InvalidSmafDataException {
long t = System.currentTimeMillis();
// divide
logger.log(Level.DEBUG, "1: " + (System.currentTimeMillis() - t));
t = System.currentTimeMillis();
byte[] buffer = new byte[sourceAis.available()];
int l = 0;
while (l < buffer.length) {
int r = sourceAis.read(buffer, l, buffer.length - l);
l += r;
}
int result = createSMAF(buffer, new File(filename));
logger.log(Level.DEBUG, "2: " + (System.currentTimeMillis() - t));
t = System.currentTimeMillis();
return result;
}
/** */
private static final String df = "yyyyMMdd";
/** */
private static final int ADPCM = 1;
/**
* Creates a SMAF.
* TODO channels
* @param data PCM data
* @param file output file
* @return size written
*/
protected int createSMAF(byte[] data, File file) throws InvalidSmafDataException, IOException {
ContentsInfoChunk contentsInfoChunk = new ContentsInfoChunk();
contentsInfoChunk.setContentsClass(ContentsInfoChunk.CONTENT_CLASS_YAMAHA);
contentsInfoChunk.setContentsType(1);
contentsInfoChunk.setContentsCodeType(0);
contentsInfoChunk.setCopyStatus(0);
contentsInfoChunk.setCopyCounts(0);
contentsInfoChunk.addSubData("M2", "\0"); // ???
contentsInfoChunk.addSubData("ST", file.getName().substring(0, file.getName().lastIndexOf('.')));
contentsInfoChunk.addSubData("CD", new SimpleDateFormat(df).format(new Date()));
contentsInfoChunk.addSubData("A0", "YW21CE"); // ???
contentsInfoChunk.addSubData("A2", "YW21BA"); // ???
contentsInfoChunk.addSubData("VN", vn);
contentsInfoChunk.addSubData("CR", cr);
int timeBase = 4; // [ms]
logger.log(Level.DEBUG, "time: " + time + ", " + data.length);
int numberOfChunks = (int) ((time * 1000) / (NopMessage.maxSteps * timeBase));
logger.log(Level.DEBUG, "numberOfChunks: " + numberOfChunks);
int moduloOfChunks = (int) ((time * 1000) % (NopMessage.maxSteps * timeBase) / timeBase);
logger.log(Level.DEBUG, "moduloOfChunks: " + moduloOfChunks);
int messageBytes = 0;
int streamNumber = 1;
AudioSequenceDataChunk audioSequenceDataChunk = new AudioSequenceDataChunk();
SmafMessage message = new VolumeMessage(0, 0, 127);
audioSequenceDataChunk.addSmafMessage(message);
messageBytes += message.getLength();
//logger.log(Level.TRACE, "messageBytes: volume: " + messageBytes);
for (int i = 0; i < numberOfChunks; i++) {
message = new WaveMessage(0, 0, streamNumber++, NopMessage.maxSteps);
audioSequenceDataChunk.addSmafMessage(message);
messageBytes += message.getLength();
//logger.log(Level.TRACE, "messageBytes: wave: " + messageBytes);
message = new NopMessage(NopMessage.maxSteps);
audioSequenceDataChunk.addSmafMessage(message);
messageBytes += message.getLength();
//logger.log(Level.TRACE, "messageBytes: nop: " + messageBytes);
}
if (moduloOfChunks != 0) {
message = new WaveMessage(0, 0, streamNumber++, moduloOfChunks);
audioSequenceDataChunk.addSmafMessage(message);
messageBytes += message.getLength();
//logger.log(Level.TRACE, "messageBytes: wave: " + messageBytes);
message = new NopMessage(moduloOfChunks);
audioSequenceDataChunk.addSmafMessage(message);
messageBytes += message.getLength();
//logger.log(Level.TRACE, "messageBytes: nop: " + messageBytes);
}
audioSequenceDataChunk.addSmafMessage(new EndOfSequenceMessage(0));
SeekAndPhraseInfoChunk seekAndPhraseInfoChunk = new SeekAndPhraseInfoChunk();
seekAndPhraseInfoChunk.setStartPoint(0);
seekAndPhraseInfoChunk.setStopPoint(messageBytes);
logger.log(Level.DEBUG, "sp: " + messageBytes);
AudioEngine audioEngine = WaveSequencer.Factory.getAudioEngine(ADPCM);
int chunkSize = numberOfChunks == 0 ? 0 : data.length / numberOfChunks;
logger.log(Level.DEBUG, "chunkSize: " + chunkSize);
int moduloChunkSize = numberOfChunks == 0 ? data.length : data.length % chunkSize;
logger.log(Level.DEBUG, "moduloChunkSize: " + moduloChunkSize);
streamNumber = 1;
PcmAudioTrackChunk pcmAudioTrackChunk = new PcmAudioTrackChunk();
pcmAudioTrackChunk.setFormatType(FormatType.HandyPhoneStandard);
pcmAudioTrackChunk.setSequenceType(SequenceType.StreamSequence);
pcmAudioTrackChunk.setWaveType(new WaveType(channels, ADPCM, samplingRate, bits));
pcmAudioTrackChunk.setDurationTimeBase(timeBase);
pcmAudioTrackChunk.setGateTimeTimeBase(timeBase);
pcmAudioTrackChunk.setSeekAndPhraseInfoChunk(seekAndPhraseInfoChunk);
pcmAudioTrackChunk.setSequenceDataChunk(audioSequenceDataChunk);
for (int i = 0; i < numberOfChunks; i++) {
byte[] temp = new byte[chunkSize];
System.arraycopy(data, chunkSize * i, temp, 0, chunkSize);
byte[] adpcm = audioEngine.encode(bits, channels, temp);
WaveDataChunk waveDataChunk = new WaveDataChunk();
waveDataChunk.setWaveNumber(streamNumber++);
waveDataChunk.setWaveData(adpcm);
pcmAudioTrackChunk.addWaveDataChunk(waveDataChunk);
}
if (moduloOfChunks != 0) {
byte[] temp = new byte[moduloChunkSize];
System.arraycopy(data, chunkSize * numberOfChunks, temp, 0, moduloChunkSize);
byte[] adpcm = audioEngine.encode(bits, channels, temp);
WaveDataChunk waveDataChunk = new WaveDataChunk();
waveDataChunk.setWaveNumber(streamNumber++);
waveDataChunk.setWaveData(adpcm);
pcmAudioTrackChunk.addWaveDataChunk(waveDataChunk);
}
FileChunk fileChunk = new FileChunk();
fileChunk.setContentsInfoChunk(contentsInfoChunk);
fileChunk.addPcmAudioTrackChunk(pcmAudioTrackChunk);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
fileChunk.writeTo(Files.newOutputStream(file.toPath()));
int r = fileChunk.getSize();
logger.log(Level.DEBUG, "write: " + r);
return r;
}
/** vendor */
protected static final String vn;
/** copyright */
protected static final String cr;
/** */
protected static final String defaultModel;
/* */
static {
try {
Properties props = new Properties();
props.load(SmafWithVoiceMaker.class.getResourceAsStream("/vavi/sound/sampled/smaf/SmafWithVoiceMaker.properties"));
vn = props.getProperty("contentsInfo.subDatum.vn");
cr = props.getProperty("contentsInfo.subDatum.cr");
defaultModel = props.getProperty("defaultModel");
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
// ----
@Options
@HelpOption(argName = "help", option = "?", description = "print this help")
public static class Arguments {
@Argument(index = 0)
File file;
@Option(argName = "filename", option = "f", args = 1, required = false, description = "output mmf filename")
final
String outFilename = "out.mmf";
@Option(argName = "model", option = "m", required = false, args = 1, description = "terminal model")
String model = defaultModel;
@Option(argName = "rate", option = "r", required = false, args = 1, description = "adpcm sampling rate [Hz]")
final
int samplingRate = 16000;
@Option(argName = "bits", option = "b", required = false, args = 1, description = "adpcm sampling bits")
final
int bits = 4;
@Option(argName = "channels", option = "c", required = false, args = 1, description = "adpcm channels")
final
int channels = 1;
@Option(argName = "masterVolume", option = "v", required = false, args = 1, description = "master volume in [%]")
final
int masterVolume = 100;
@Option(argName = "adpcmVolume", option = "a", required = false, args = 1, description = "adpcm volume in [%]")
final
int adpcmVolume = 100;
}
/**
* Creates .mmf w/ voice file.
*
* @param args input wave file
* -f output mmf filename
* -r adpcm sampling rate [Hz]
* -b adpcm sampling bits
* -c adpcm channels
* -v master volume [%]
* -a adpcm volume [%]
*/
public static void main(String[] args) {
try {
Arguments arguments = new Arguments();
Options.Util.bind(args, arguments);
// create
AudioInputStream ais = AudioSystem.getAudioInputStream(arguments.file);
FilterChain filterChain = new FilterChain();
SmafWithVoiceMaker mwvm = new SmafWithVoiceMaker(filterChain.doFilter(ais), arguments.outFilename, 0 /* TODO */, arguments.samplingRate, arguments.bits, arguments.channels, arguments.masterVolume, arguments.adpcmVolume);
mwvm.create();
// done
System.exit(0);
} catch (Exception e) {
e.printStackTrace(System.err);
System.exit(1);
}
}
}