-
Notifications
You must be signed in to change notification settings - Fork 82
/
MosaicExample.java
428 lines (362 loc) · 15.2 KB
/
MosaicExample.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
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
package examples;
import com.github.kokorin.jaffree.LogLevel;
import com.github.kokorin.jaffree.StreamType;
import com.github.kokorin.jaffree.ffmpeg.FFmpeg;
import com.github.kokorin.jaffree.ffmpeg.FFmpegResult;
import com.github.kokorin.jaffree.ffmpeg.Frame;
import com.github.kokorin.jaffree.ffmpeg.FrameConsumer;
import com.github.kokorin.jaffree.ffmpeg.FrameInput;
import com.github.kokorin.jaffree.ffmpeg.FrameOutput;
import com.github.kokorin.jaffree.ffmpeg.FrameProducer;
import com.github.kokorin.jaffree.ffmpeg.ImageFormats;
import com.github.kokorin.jaffree.ffmpeg.Stream;
import com.github.kokorin.jaffree.ffmpeg.UrlInput;
import com.github.kokorin.jaffree.ffmpeg.UrlOutput;
import com.github.kokorin.jaffree.ffprobe.FFprobe;
import com.github.kokorin.jaffree.ffprobe.FFprobeResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Deque;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* Note: for some reason ffmpeg 3.3.1 fails when using amix or amerge filters (in this example)
* Use ffmpeg 4.0 at least, amix works (while amerge still fails)
*/
public class MosaicExample {
private final Path ffmpegBin;
private final List<String> inputs;
private final int sampleRate = 44100;
private final int frameRate = 25;
public static final Logger LOGGER = LoggerFactory.getLogger(MosaicExample.class);
public MosaicExample(String ffmpegBin, List<String> inputs) {
this.ffmpegBin = Paths.get(ffmpegBin);
this.inputs = inputs;
}
public void execute() {
final List<FFmpegResult> results = new CopyOnWriteArrayList<>();
List<FrameIterator> frameIterators = new ArrayList<>();
for (int i = 0; i < inputs.size(); i++) {
String input = inputs.get(i);
boolean hasAudioStream = false;
// We must test input for audio stream
// Other corner-cases (no video stream, multiple audio stream are not considered)
FFprobeResult probeResult = FFprobe.atPath(ffmpegBin)
.setShowStreams(true)
.setInput(Paths.get(input))
.execute();
for (com.github.kokorin.jaffree.ffprobe.Stream stream : probeResult.getStreams()) {
if (StreamType.AUDIO == stream.getCodecType()) {
hasAudioStream = true;
break;
}
}
FrameIterator frameIterator = new FrameIterator();
frameIterators.add(frameIterator);
final FFmpeg ffmpeg = FFmpeg.atPath(ffmpegBin)
.addInput(UrlInput
.fromUrl(input)
.setDuration(15_000))
.addOutput(FrameOutput
.withConsumer(frameIterator.getConsumer())
.setFrameRate(frameRate)
.addArguments("-ac", "1")
.addArguments("-ar", Integer.toString(sampleRate))
)
.setContextName("input" + i);
if (!hasAudioStream) {
ffmpeg
.addInput(
UrlInput.fromUrl("anullsrc")
.setFormat("lavfi")
)
.addArgument("-shortest");
}
Thread ffmpegThread = new Thread(new Runnable() {
@Override
public void run() {
FFmpegResult result = ffmpeg.execute();
results.add(result);
}
}, "Reader-" + i + "-main");
ffmpegThread.setDaemon(true);
ffmpegThread.start();
}
FrameProducer frameProducer = produceMosaic(frameIterators);
FFmpegResult mosaicResult = FFmpeg.atPath(ffmpegBin)
.addInput(
FrameInput
.withProducer(frameProducer, ImageFormats.BGR24, 5_000L)
.setFrameRate(frameRate)
)
.setOverwriteOutput(true)
.setLogLevel(LogLevel.TRACE)
.addOutput(UrlOutput
.toUrl("mosaic.mp4")
//.addMap(0)
)
.addArguments("-filter_complex", "amix=inputs=" + inputs.size())
.setContextName("result")
.execute();
}
private FrameProducer produceMosaic(final List<FrameIterator> frameIterators) {
final int rows = (int) Math.round(Math.sqrt(frameIterators.size()));
final int columns = (int) Math.ceil(1.0 * frameIterators.size() / rows);
return new FrameProducer() {
private final int elementWidth = 320;
private final int elementHeight = 240;
private final int mosaicWidth = columns * elementWidth;
private final int mosaicHeight = rows * elementHeight;
private final long videoFrameDuration = 1000 / frameRate;
private final Map<Integer, Deque<Frame>> audioQueues = new HashMap<>();
private long timecode = 0;
private final Frame[] nextVideoFrames = new Frame[frameIterators.size()];
private long nextVideoFrameTimecode = 0;
private long nextAudioFrameTimecode = 0;
@Override
public List<Stream> produceStreams() {
List<Stream> streams = new ArrayList<>();
streams.add(
new Stream()
.setId(0)
.setType(Stream.Type.VIDEO)
.setTimebase(1000L)
.setWidth(mosaicWidth)
.setHeight(mosaicHeight)
);
// We copy all audio streams to output and merge tham with amerge filter
for (int i = 0; i < frameIterators.size(); i++) {
streams.add(
new Stream()
.setId(1 + i)
.setType(Stream.Type.AUDIO)
.setTimebase((long) sampleRate)
.setChannels(1)
.setSampleRate(sampleRate)
);
}
return streams;
}
@Override
public Frame produce() {
Frame result = null;
if (nextVideoFrameTimecode <= timecode) {
if (nextVideoFrameTimecode == 0) {
readNextVideoFrames(nextVideoFrameTimecode);
}
result = produceVideoFrame(nextVideoFrames);
// We have to read video frames ahead, otherwise we will have no audio frames read
readNextVideoFrames(nextVideoFrameTimecode);
} else if (nextAudioFrameTimecode <= timecode) {
result = produceAudioFrame();
}
timecode = Math.min(nextVideoFrameTimecode, nextAudioFrameTimecode);
return result;
}
public Frame produceVideoFrame(Frame[] videoFrames) {
BufferedImage mosaic = new BufferedImage(mosaicWidth, mosaicHeight, BufferedImage.TYPE_3BYTE_BGR);
Graphics mosaicGraphics = mosaic.getGraphics();
mosaicGraphics.setColor(new Color(0));
mosaicGraphics.fillRect(0, 0, mosaicWidth, mosaicHeight);
boolean atLeastHasOneElement = false;
for (int i = 0; i < videoFrames.length; i++) {
Frame videoFrame = videoFrames[i];
if (videoFrame == null) {
continue;
}
atLeastHasOneElement = true;
BufferedImage element = videoFrame.getImage();
int row = i / columns;
int column = i % columns;
ImageObserver observer = new ImageObserver() {
@Override
public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) {
return false;
}
};
int dx1 = column * elementWidth;
int dy1 = row * elementHeight;
int dx2 = dx1 + elementWidth;
int dy2 = dy1 + elementHeight;
mosaicGraphics.drawImage(element,
dx1, dy1, dx2, dy2,
0, 0, element.getWidth(), element.getHeight(),
observer
);
}
if (!atLeastHasOneElement) {
return null;
}
Frame result = Frame.createVideoFrame(0, nextVideoFrameTimecode, mosaic);
nextVideoFrameTimecode += videoFrameDuration;
return result;
}
private Frame produceAudioFrame() {
long minPts = Long.MAX_VALUE;
long nextPts = Long.MAX_VALUE;
int minI = -1;
for (int i = 0; i < frameIterators.size(); i++) {
Deque<Frame> aQueue = audioQueues.get(i);
Frame frame = aQueue.peekFirst();
if (frame == null) {
continue;
}
long queuePts = frame.getPts();
if (queuePts < minPts) {
nextPts = minPts;
minPts = queuePts;
minI = i;
continue;
}
if (queuePts < nextPts) {
nextPts = queuePts;
}
}
if (minI == -1) {
return null;
}
Frame aFrame = audioQueues.get(minI).pollFirst();
if (aFrame == null) {
return null;
}
aFrame = Frame.createAudioFrame(1 + minI, aFrame.getPts(), aFrame.getSamples());
if (nextPts != Long.MAX_VALUE) {
nextAudioFrameTimecode = 1000L * nextPts / sampleRate;
} else {
nextAudioFrameTimecode = nextVideoFrameTimecode;
}
return aFrame;
}
// All video input streams have forced frameRate, so we know that in every stream
// frames will occur with the same timestamp
private void readNextVideoFrames(long videoTs) {
for (int i = 0; i < frameIterators.size(); i++) {
FrameIterator iter = frameIterators.get(i);
if (!iter.hasNext) {
nextVideoFrames[i] = null;
}
while (iter.hasNext) {
Frame frame = iter.next();
if (frame == null) {
break;
}
Stream stream = iter.getStream(frame.getStreamId());
if (stream == null) {
break;
}
switch (stream.getType()) {
case VIDEO:
nextVideoFrames[i] = frame;
break;
case AUDIO:
Deque<Frame> aQueue = audioQueues.get(i);
if (aQueue == null) {
aQueue = new LinkedList<>();
audioQueues.put(i, aQueue);
}
aQueue.addLast(frame);
break;
}
long frameTs = 1000L * frame.getPts() / stream.getTimebase();
if (frameTs >= videoTs) {
break;
}
}
}
}
};
}
public static void main(String[] args) {
Iterator<String> argIter = Arrays.asList(args).iterator();
String ffmpegBin = null;
List<String> inputs = new ArrayList<>();
while (argIter.hasNext()) {
String arg = argIter.next();
if ("-ffmpeg_bin".equals(arg)) {
ffmpegBin = argIter.next();
} else {
inputs.add(arg);
}
}
if (ffmpegBin == null || inputs.isEmpty()) {
System.err.println("Arguments: -ffmpeg_bin </path/to/ffmpeg/bin>");
return;
}
new MosaicExample(ffmpegBin, inputs).execute();
}
public static class FrameIterator implements Iterator<Frame> {
private volatile boolean hasNext = true;
private volatile Frame next = null;
private volatile List<Stream> tracks;
private final FrameConsumer consumer = new FrameConsumer() {
@Override
public void consumeStreams(List<Stream> tracks) {
FrameIterator.this.tracks = tracks;
}
@Override
public void consume(Frame frame) {
while (next != null) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
LOGGER.warn("Exception while supplying frame", e);
}
}
hasNext = frame != null;
next = frame;
}
};
@Override
public boolean hasNext() {
waitForNextFrame();
return hasNext;
}
@Override
public Frame next() {
waitForNextFrame();
Frame result = next;
next = null;
return result;
}
@Override
public void remove() {
throw new UnsupportedOperationException("remove");
}
public FrameConsumer getConsumer() {
return consumer;
}
public List<Stream> getTracks() {
return tracks;
}
public Stream getStream(int id) {
for (Stream stream : tracks) {
if (stream.getId() == id) {
return stream;
}
}
return null;
}
private void waitForNextFrame() {
while (hasNext && next == null) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
LOGGER.warn("Exception while waiting for frame", e);
}
}
}
}
}