My favorites | Sign in
Project Home Downloads Wiki Issues Source
Checkout   Browse   Changes    
 
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
/*
* Based on Libavformat API example: Output a media file in any supported
* libavformat format. The default codecs are used.
*
* Copyright (c) 2003 Fabrice Bellard
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/*
* See: http://cekirdek.pardus.org.tr/~ismail/ffmpeg-docs/output-example_8c-source.html
*/
package au.notzed.jjmpeg.io;

import au.notzed.jjmpeg.AVCodec;
import au.notzed.jjmpeg.AVCodecContext;
import au.notzed.jjmpeg.AVFormatContext;
import au.notzed.jjmpeg.AVFrame;
import au.notzed.jjmpeg.AVIOContext;
import au.notzed.jjmpeg.AVMediaType;
import au.notzed.jjmpeg.AVOutputFormat;
import au.notzed.jjmpeg.AVPacket;
import au.notzed.jjmpeg.AVPlane;
import au.notzed.jjmpeg.AVRational;
import au.notzed.jjmpeg.AVSamples;
import au.notzed.jjmpeg.AVStream;
import au.notzed.jjmpeg.CodecID;
import au.notzed.jjmpeg.PixelFormat;
import au.notzed.jjmpeg.SampleFormat;
import au.notzed.jjmpeg.SwsContext;
import au.notzed.jjmpeg.exception.AVEncodingError;
import au.notzed.jjmpeg.exception.AVIOException;
import au.notzed.jjmpeg.exception.AVInvalidCodecException;
import au.notzed.jjmpeg.exception.AVInvalidFormatException;
import au.notzed.jjmpeg.exception.AVInvalidStreamException;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.LinkedList;

/**
* High level av file writer interface
* @author notzed
*/
public class JJMediaWriter {

LinkedList<JJWriterStream> streams = new LinkedList<JJWriterStream>();
String filename;
AVOutputFormat format;
AVFormatContext oc;
AVIOContext output;

/**
* Create a new stream for writing to a file.
*
* Once created, call addVideoStream, (addAudioStream) and so on, before calling open().
* Frames are then added using the various addFrame() methods until finished,
* and then call close().
*
* @param filename
* @throws AVInvalidFormatException
*/
public JJMediaWriter(String filename) throws AVInvalidFormatException {
this.filename = filename;

/* create packet for re-use later */

/* auto detect the output format from the name. default is mpeg. */
format = AVOutputFormat.guessFormat(null, filename, null);
if (format == null) {
format = AVOutputFormat.guessFormat("mpeg", null, null);
}
if (format == null) {
throw new AVInvalidFormatException(filename);
}

/* allocate the output media context */
oc = AVFormatContext.allocContext();
oc.setOutputFormat(format);

// Caller now calls addVideoStream, etc.
}

/**
* Get the output format being used.
* @return
*/
public AVOutputFormat getFormat() {
return format;
}

/**
* The stream must be opened after adding streams and before writing to them.
* @throws AVInvalidFormatException
* @throws AVInvalidCodecException
* @throws AVIOException
*/
public void open() throws AVInvalidFormatException, AVInvalidCodecException, AVIOException {
/* set the output parameters (must be done even if no parameters). */
if (oc.setParameters(null) < 0) {
throw new AVInvalidFormatException("Unable to set parameters");
}

/* now that all the parameters are set, we can open the audio and
video codecs and allocate the necessary encode buffers */
for (JJWriterStream sd : streams) {
sd.open();
}

/* open the output file, if needed */
//if (!(format->flags & AVFMT_NOFILE)) {
output = AVIOContext.open(filename, AVIOContext.URL_WRONLY);
oc.setIOContext(output);

/* write the stream header, if any */
oc.writeHeader();
}

/**
* Add a stream using the default video codec for this stream.
* The streamid is the index of the stream in the streams list.
* @param width
* @param height
* @param frame_rate
* @param bit_rate
* @return
* @throws AVInvalidStreamException
*/
public JJWriterVideo addVideoStream(int width, int height, int frame_rate, int bit_rate) throws AVInvalidStreamException {
return addVideoStream(format.getVideoCodec(), streams.size(), width, height, frame_rate, bit_rate);
}

/**
* Add a video stream.
* @param codec_id
* @param width
* @param height
* @param frame_rate
* @param bit_rate
* @return
* @throws AVInvalidStreamException
*/
public JJWriterVideo addVideoStream(int codec_id, int streamid, int width, int height, int frame_rate, int bit_rate) throws AVInvalidStreamException {
AVCodecContext c;
AVStream st;

System.out.printf("adding video %s [%d %dx%d@%d]\n", codec_id, streamid, width, height, frame_rate);

st = oc.newStream(streamid);
if (st == null) {
throw new AVInvalidStreamException("Unable to create stream");
}

c = st.getCodec();
c.setCodecID(codec_id);
c.setCodecType(AVMediaType.AVMEDIA_TYPE_VIDEO.toC());
/* put sample parameters */
c.setBitRate(bit_rate);

/* resolution must be a multiple of two */
c.setWidth(width);
c.setHeight(height);
/* time base: this is the fundamental unit of time (in seconds) in terms
of which frame timestamps are represented. for fixed-fps content,
timebase should be 1/framerate and timestamp increments should be
identically 1. */
c.setTimeBaseDen(frame_rate);
c.setTimeBaseNum(1);
c.setGOPSize(12); /* emit one intra frame every twelve frames at most */
c.setPixFmt(PixelFormat.PIX_FMT_YUV420P);
if (codec_id == CodecID.CODEC_ID_MPEG2VIDEO) {
/* just for testing, we also add B frames */
c.setMaxBFrames(2);
}
if (codec_id == CodecID.CODEC_ID_MPEG1VIDEO) {
/* Needed to avoid using macroblocks in which some coeffs overflow.
This does not happen with normal video, it just happens here as
the motion of the chroma plane does not match the luma plane. */
c.setMbDecision(2);
}
// FIXME: some formats want stream headers to be separate
if ((oc.getOutputFormat().getFlags() & AVOutputFormat.AVFMT_GLOBALHEADER) != 0) {
c.setFlags(c.getFlags() | AVCodecContext.CODEC_FLAG_GLOBAL_HEADER);
}
JJWriterVideo sd = new JJWriterVideo(st);
streams.add(sd);

return sd;
}

/**
* Add a new audio stream.
* @param codec_id
* @param streamid
* @param fmt
* @param sample_rate
* @param bit_rate
* @return
* @throws AVInvalidStreamException
*/
public JJWriterAudio addAudioStream(int codec_id, int streamid, SampleFormat fmt, int sample_rate, int channels, int bit_rate) throws AVInvalidStreamException {
AVCodecContext c;
AVStream st;

st = oc.newStream(streamid);
if (st == null) {
throw new AVInvalidStreamException("Unable to create stream");
}

{
AVCodec codec = AVCodec.findDecoder(codec_id);
System.out.printf("Adding audio %s [%d %s %dHz %db]\n", codec.getName(), streamid, fmt, sample_rate, bit_rate);
}

c = st.getCodec();
c.setCodecID(codec_id);
c.setCodecType(AVMediaType.AVMEDIA_TYPE_AUDIO.toC());

// sample parameters
c.setSampleFmt(fmt);
c.setBitRate(bit_rate);
c.setSampleRate(sample_rate);

c.setChannels(channels);
c.setChannelLayout(4);

if ((oc.getOutputFormat().getFlags() & AVOutputFormat.AVFMT_GLOBALHEADER) != 0) {
c.setFlags(c.getFlags() | AVCodecContext.CODEC_FLAG_GLOBAL_HEADER);
}

JJWriterAudio as = new JJWriterAudio(st);

streams.add(as);

return as;
}

/**
* Close the file, completing the stream and freeing resources.
*/
public void close() {
/* write the trailer, if any. the trailer must be written
* before you close the CodecContexts open when you wrote the
* header; otherwise write_trailer may try to use memory that
* was freed on av_codec_close() */
oc.writeTrailer();

/* close each codec */
for (JJWriterStream sd : streams) {
sd.close();
}

/* close the output file */
output.close();

/* free the stream */
oc.dispose();
}

public abstract class JJWriterStream {

AVStream stream;
ByteBuffer outputBuffer;
AVCodecContext c;
AVPacket packet;

public JJWriterStream(AVStream stream) {
this.stream = stream;
c = stream.getCodec();
packet = AVPacket.create();
}

/**
* Retrieve the av stream.
* @return
*/
public AVStream getStream() {
return stream;
}

/**
* Retrieve the codec context for this stream.
* @return
*/
public AVCodecContext getContext() {
return c;
}

abstract void open() throws AVInvalidCodecException, AVIOException;

void close() {
stream.getCodec().close();
packet.dispose();
}
}

/**
* Represents a video stream.
*/
public class JJWriterVideo extends JJWriterStream {

AVFrame picture;
// for rgb input
private AVFrame rgbPicture;
private AVPlane rgbPlane;
private SwsContext rgbSWS;

public JJWriterVideo(AVStream stream) {
super(stream);
}

@Override
void open() throws AVInvalidCodecException, AVIOException {
AVCodec codec;

/* find the video encoder */
codec = AVCodec.findEncoder(c.getCodecID());
if (codec == null) {
throw new AVInvalidCodecException("codec not found");
}

/* open the codec */
c.open(codec);

//if (!(oc - > oformat - > flags & AVFMT_RAWPICTURE)) {
/* allocate output buffer */
/* XXX: API change will be done */
/* buffers passed into lav* can be allocated any way you prefer,
as long as they're aligned enough for the architecture, and
they're freed appropriately (such as using av_free for buffers
allocated with av_malloc) */
//video_outbuf_size = 200000;
//video_outbuf = av_malloc(video_outbuf_size);
//}
// Raw video will need a buffer as big as the image in yuv
int size = c.getWidth() * c.getHeight() * 2;

outputBuffer = ByteBuffer.allocateDirect(size);
/* allocate the encoded raw picture */
PixelFormat pixFmt = c.getPixFmt();
picture = AVFrame.create(pixFmt, c.getWidth(), c.getHeight());

/* if the output format is not YUV420P, then a temporary YUV420P
picture is needed too. It is then converted to the required
output format */
//if (pixFmt != PixelFormat.PIX_FMT_YUV420P) {
// tmp = AVFrame.create(PixelFormat.PIX_FMT_YUV420P, c.getWidth(), c.getHeight());
//}
}

@Override
void close() {
super.close();

picture.dispose();
//if (tmp != null) {
// tmp.dispose();
//}
if (rgbPicture != null) {
rgbPicture.dispose();
rgbSWS.dispose();
}
}

/**
* Convert bufferedimage to matching output format
* @param bi
*/
private AVFrame loadImage(BufferedImage bi) {
int height = c.getHeight();

byte[] data = ((DataBufferByte) bi.getRaster().getDataBuffer()).getData();
// Convert to YUV

// TODO: only if output format not bgr24
if (rgbPicture == null) {
int width = c.getWidth();

rgbPicture = AVFrame.create(PixelFormat.PIX_FMT_BGR24, width, height);
rgbSWS = SwsContext.create(width, height, PixelFormat.PIX_FMT_BGR24, width, height, c.getPixFmt(), SwsContext.SWS_X);
rgbPlane = rgbPicture.getPlaneAt(0, PixelFormat.PIX_FMT_BGR24, width, height);
}

rgbPlane.data.put(data);
rgbPlane.data.rewind();
rgbSWS.scale(rgbPicture, 0, height, picture);

return picture;
}

/**
* Create an image suitable for writing to this stream.
* i.e. will be TYPE_3BYTE_BGR
*/
public BufferedImage createImage() {
return new BufferedImage(c.getWidth(), c.getHeight(), BufferedImage.TYPE_3BYTE_BGR);
}

/**
* Write next video frame.
* @param sd
* @param frame format must match the codec pixel format
* @throws AVEncodingError
* @throws AVIOException
*/
public void addFrame(AVFrame frame) throws AVEncodingError, AVIOException {
// TODO: raw video case
/* encode the image */
int out_size = c.encodeVideo(outputBuffer, frame);

/* if zero size, it means the image was buffered */
if (out_size > 0) {
AVFrame cframe = c.getCodedFrame();

packet.initPacket();
if (cframe.getPTS() != AVCodecContext.AV_NOPTS_VALUE) {
packet.setPTS(AVRational.rescaleQ(cframe.getPTS(), c.getTimeBase(), stream.getTimeBase()));
}
if (cframe.isKeyFrame()) {
packet.setFlags(packet.getFlags() | AVPacket.AV_PKT_FLAG_KEY);
}
packet.setStreamIndex(stream.getIndex());
packet.setData(outputBuffer, out_size);

/* write the compressed frame in the media file */
int ret = oc.interleavedWriteFrame(packet);
//int ret = oc.writeFrame(pkt);

if (ret < 0) {
throw new AVIOException(ret);
}
}
}

/**
* Add a frame as an RGB buffered image.
* @param sd
* @param bi Should be created with createImage.
* @throws AVEncodingError
* @throws AVIOException
*/
public void addFrame(BufferedImage bi) throws AVEncodingError, AVIOException {
// TODO: check image is the right size and format

addFrame(loadImage(bi));
}
}

public class JJWriterAudio extends JJWriterStream {

AVFrame picture;
long audio_input_frame_size;

public JJWriterAudio(AVStream stream) {
super(stream);
}

@Override
void open() throws AVInvalidCodecException, AVIOException {
AVCodec codec;

/* find the audio encoder */
codec = AVCodec.findEncoder(c.getCodecID());
if (codec == null) {
throw new AVInvalidCodecException("codec not found");
}

/* open the codec */
c.open(codec);

// TODO: pcm hack stuff
if (c.getFrameSize() <= 1) {
}

System.out.println("audio codec framesize = " + c.getFrameSize());

this.outputBuffer = ByteBuffer.allocateDirect(AVCodecContext.FF_MIN_BUFFER_SIZE).order(ByteOrder.nativeOrder());
}

@Override
void close() {
super.close();
}

/**
* Create a samples buffer suitable for storing raw samples
* @return
*/
public AVSamples createSamples() {
return new AVSamples(c.getSampleFmt(), c.getChannels(), c.getFrameSize());
}

/**
* Write a new audio frame to the stream.
*
* It is up to the caller to interleave audio/video properly
* @param samples
* @throws AVEncodingError
* @throws AVIOException
*/
int n = 0;
public void addFrame(AVSamples samples) throws AVEncodingError, AVIOException {
int out_size = c.encodeAudio(this.outputBuffer, samples);

AVFrame cframe = c.getCodedFrame();

packet.initPacket();
if (cframe != null && cframe.getPTS() != AVCodecContext.AV_NOPTS_VALUE) {
packet.setPTS(AVRational.rescaleQ(cframe.getPTS(), c.getTimeBase(), stream.getTimeBase()));
}

packet.setStreamIndex(stream.getIndex());
packet.setData(outputBuffer, out_size);
int ret = oc.interleavedWriteFrame(packet);

if (ret < 0) {
throw new AVIOException(ret);
}
}
}
}

Change log

r74 by notzed on Mar 17, 2012   Diff
Minor api additions..
Added top-level makefile for building
releases.
Go to: 
Project members, sign in to write a code review

Older revisions

r57 by notzed on Feb 6, 2012   Diff
Added a fillBuffer function to
AVSamples to simplify encoding re-
packing.
Get of a null pointer now returns a
null pointer rather than a bytebuffer
...
r55 by notzed on Feb 5, 2012   Diff
Started work on a audio+video writer
api.
r47 by notzed on Nov 29, 2011   Diff
Added enough code to write video
streams in libavformat containers.
Juggled the api around a bit, and
exceptions.
Added demo for new JJMediaWriter
...
All revisions of this file

File info

Size: 15440 bytes, 537 lines
Powered by Google Project Hosting