xref: /haiku/src/add-ons/media/plugins/ffmpeg/AVFormatWriter.cpp (revision 26d22ee8dc5db3cea88354d0536f5dd9950b6bcf)
1 /*
2  * Copyright 2009-2010, Stephan Aßmus <superstippi@gmx.de>
3  * Copyright 2018, Dario Casalinuovo
4  * All rights reserved. Distributed under the terms of the GNU L-GPL license.
5  */
6 
7 #include "AVFormatWriter.h"
8 
9 #include <stdio.h>
10 #include <string.h>
11 #include <stdlib.h>
12 
13 #include <new>
14 
15 #include <Application.h>
16 #include <AutoDeleter.h>
17 #include <Autolock.h>
18 #include <ByteOrder.h>
19 #include <MediaIO.h>
20 #include <MediaDefs.h>
21 #include <MediaFormats.h>
22 #include <Roster.h>
23 
24 extern "C" {
25 	#include "avformat.h"
26 }
27 
28 #include "DemuxerTable.h"
29 #include "EncoderTable.h"
30 #include "gfx_util.h"
31 
32 
33 //#define TRACE_AVFORMAT_WRITER
34 #ifdef TRACE_AVFORMAT_WRITER
35 #	define TRACE printf
36 #	define TRACE_IO(a...)
37 #	define TRACE_PACKET printf
38 #else
39 #	define TRACE(a...)
40 #	define TRACE_IO(a...)
41 #	define TRACE_PACKET(a...)
42 #endif
43 
44 #define ERROR(a...) fprintf(stderr, a)
45 
46 
47 static const size_t kIOBufferSize = 64 * 1024;
48 	// TODO: This could depend on the BMediaFile creation flags, IIRC,
49 	// they allow to specify a buffering mode.
50 
51 typedef AVCodecID CodecID;
52 
53 // #pragma mark - AVFormatWriter::StreamCookie
54 
55 
56 class AVFormatWriter::StreamCookie {
57 public:
58 								StreamCookie(AVFormatContext* context,
59 									BLocker* streamLock);
60 	virtual						~StreamCookie();
61 
62 			status_t			Init(media_format* format,
63 									const media_codec_info* codecInfo);
64 
65 			status_t			WriteChunk(const void* chunkBuffer,
66 									size_t chunkSize,
67 									media_encode_info* encodeInfo);
68 
69 			status_t			AddTrackInfo(uint32 code, const void* data,
70 									size_t size, uint32 flags);
71 
72 private:
73 			AVFormatContext*	fFormatContext;
74 			AVStream*			fStream;
75 			AVPacket			fPacket;
76 			// Since different threads may write to the target,
77 			// we need to protect the file position and I/O by a lock.
78 			BLocker*			fStreamLock;
79 };
80 
81 
82 
83 AVFormatWriter::StreamCookie::StreamCookie(AVFormatContext* context,
84 		BLocker* streamLock)
85 	:
86 	fFormatContext(context),
87 	fStream(NULL),
88 	fStreamLock(streamLock)
89 {
90 	av_init_packet(&fPacket);
91 }
92 
93 
94 AVFormatWriter::StreamCookie::~StreamCookie()
95 {
96 	// fStream is freed automatically when the codec context is closed
97 }
98 
99 
100 status_t
101 AVFormatWriter::StreamCookie::Init(media_format* format,
102 	const media_codec_info* codecInfo)
103 {
104 	TRACE("AVFormatWriter::StreamCookie::Init()\n");
105 
106 	BAutolock _(fStreamLock);
107 
108 	fPacket.stream_index = fFormatContext->nb_streams;
109 	fStream = avformat_new_stream(fFormatContext, NULL);
110 
111 	if (fStream == NULL) {
112 		TRACE("  failed to add new stream\n");
113 		return B_ERROR;
114 	}
115 
116 	fStream->id = fPacket.stream_index;
117 
118 //	TRACE("  fStream->codecpar: %p\n", fStream->codecpar);
119 	// TODO: This is a hack for now! Use avcodec_find_encoder_by_name()
120 	// or something similar...
121 	fStream->codecpar->codec_id = (CodecID)codecInfo->sub_id;
122 	if (fStream->codecpar->codec_id == AV_CODEC_ID_NONE)
123 		fStream->codecpar->codec_id = raw_audio_codec_id_for(*format);
124 
125 	// Setup the stream according to the media format...
126 	if (format->type == B_MEDIA_RAW_VIDEO) {
127 		fStream->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
128 		fStream->time_base.den = (int)format->u.raw_video.field_rate;
129 		fStream->time_base.num = 1;
130 
131 		// video size
132 		fStream->codecpar->width = format->u.raw_video.display.line_width;
133 		fStream->codecpar->height = format->u.raw_video.display.line_count;
134 		// pixel aspect ratio
135 		fStream->sample_aspect_ratio.num
136 			= format->u.raw_video.pixel_width_aspect;
137 		fStream->sample_aspect_ratio.den
138 			= format->u.raw_video.pixel_height_aspect;
139 		if (fStream->sample_aspect_ratio.num == 0
140 			|| fStream->sample_aspect_ratio.den == 0) {
141 			av_reduce(&fStream->sample_aspect_ratio.num,
142 				&fStream->sample_aspect_ratio.den, fStream->codecpar->width,
143 				fStream->codecpar->height, 255);
144 		}
145 
146 		fStream->codecpar->sample_aspect_ratio = fStream->sample_aspect_ratio;
147 
148 		// Use the last supported pixel format of the AVCodec, which we hope
149 		// is the one with the best quality (true for all currently supported
150 		// encoders).
151 //		AVCodec* codec = fStream->codecpar->codec;
152 //		for (int i = 0; codec->pix_fmts[i] != PIX_FMT_NONE; i++)
153 //			fStream->codecpar->pix_fmt = codec->pix_fmts[i];
154 		fStream->codecpar->format = AV_PIX_FMT_YUV420P;
155 
156 	} else if (format->type == B_MEDIA_RAW_AUDIO) {
157 		fStream->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
158 
159 		// frame rate
160 		fStream->codecpar->sample_rate = (int)format->u.raw_audio.frame_rate;
161 
162 		// channels
163 		fStream->codecpar->channels = format->u.raw_audio.channel_count;
164 
165 		// set fStream to the audio format we want to use. This is only a hint
166 		// (each encoder has a different set of accepted formats)
167 		switch (format->u.raw_audio.format) {
168 			case media_raw_audio_format::B_AUDIO_FLOAT:
169 				fStream->codecpar->format = AV_SAMPLE_FMT_FLT;
170 				break;
171 			case media_raw_audio_format::B_AUDIO_DOUBLE:
172 				fStream->codecpar->format = AV_SAMPLE_FMT_DBL;
173 				break;
174 			case media_raw_audio_format::B_AUDIO_INT:
175 				fStream->codecpar->format = AV_SAMPLE_FMT_S32;
176 				break;
177 			case media_raw_audio_format::B_AUDIO_SHORT:
178 				fStream->codecpar->format = AV_SAMPLE_FMT_S16;
179 				break;
180 			case media_raw_audio_format::B_AUDIO_UCHAR:
181 				fStream->codecpar->format = AV_SAMPLE_FMT_U8;
182 				break;
183 
184 			case media_raw_audio_format::B_AUDIO_CHAR:
185 			default:
186 				return B_MEDIA_BAD_FORMAT;
187 				break;
188 		}
189 
190 		// Now negociate the actual format with the encoder
191 		// First check if the requested format is acceptable
192 		AVCodec* codec = avcodec_find_encoder(fStream->codecpar->codec_id);
193 
194 		if (codec == NULL)
195 			return B_MEDIA_BAD_FORMAT;
196 
197 		const enum AVSampleFormat *p = codec->sample_fmts;
198 		for (; *p != -1; p++) {
199 			if (*p == fStream->codecpar->format)
200 				break;
201 		}
202 		// If not, force one of the acceptable ones
203 		if (*p == -1) {
204 			fStream->codecpar->format = codec->sample_fmts[0];
205 
206 			// And finally set the format struct to the accepted format. It is
207 			// then up to the caller to make sure we get data matching that
208 			// format.
209 			switch (fStream->codecpar->format) {
210 				case AV_SAMPLE_FMT_FLT:
211 					format->u.raw_audio.format
212 						= media_raw_audio_format::B_AUDIO_FLOAT;
213 					break;
214 				case AV_SAMPLE_FMT_DBL:
215 					format->u.raw_audio.format
216 						= media_raw_audio_format::B_AUDIO_DOUBLE;
217 					break;
218 				case AV_SAMPLE_FMT_S32:
219 					format->u.raw_audio.format
220 						= media_raw_audio_format::B_AUDIO_INT;
221 					break;
222 				case AV_SAMPLE_FMT_S16:
223 					format->u.raw_audio.format
224 						= media_raw_audio_format::B_AUDIO_SHORT;
225 					break;
226 				case AV_SAMPLE_FMT_U8:
227 					format->u.raw_audio.format
228 						= media_raw_audio_format::B_AUDIO_UCHAR;
229 					break;
230 				default:
231 					return B_MEDIA_BAD_FORMAT;
232 					break;
233 			}
234 		}
235 
236 		if (format->u.raw_audio.channel_mask == 0) {
237 			// guess the channel mask...
238 			switch (format->u.raw_audio.channel_count) {
239 				default:
240 				case 2:
241 					fStream->codecpar->channel_layout = AV_CH_LAYOUT_STEREO;
242 					break;
243 				case 1:
244 					fStream->codecpar->channel_layout = AV_CH_LAYOUT_MONO;
245 					break;
246 				case 3:
247 					fStream->codecpar->channel_layout = AV_CH_LAYOUT_SURROUND;
248 					break;
249 				case 4:
250 					fStream->codecpar->channel_layout = AV_CH_LAYOUT_QUAD;
251 					break;
252 				case 5:
253 					fStream->codecpar->channel_layout = AV_CH_LAYOUT_5POINT0;
254 					break;
255 				case 6:
256 					fStream->codecpar->channel_layout = AV_CH_LAYOUT_5POINT1;
257 					break;
258 				case 8:
259 					fStream->codecpar->channel_layout = AV_CH_LAYOUT_7POINT1;
260 					break;
261 				case 10:
262 					fStream->codecpar->channel_layout = AV_CH_LAYOUT_7POINT1_WIDE;
263 					break;
264 			}
265 		} else {
266 			// The bits match 1:1 for media_multi_channels and FFmpeg defines.
267 			fStream->codecpar->channel_layout = format->u.raw_audio.channel_mask;
268 		}
269 	}
270 
271 	TRACE("  stream->time_base: (%d/%d)\n",
272 		fStream->time_base.num, fStream->time_base.den);
273 
274 #if 0
275 	// Write the AVCodecContext pointer to the user data section of the
276 	// media_format. For some encoders, it seems to be necessary to use
277 	// the AVCodecContext of the AVStream in order to successfully encode
278 	// anything and write valid media files. For example some codecs need
279 	// to store meta data or global data in the container.
280 	app_info appInfo;
281 	if (be_app->GetAppInfo(&appInfo) == B_OK) {
282 		uchar* userData = format->user_data;
283 		*(uint32*)userData = 'ffmp';
284 		userData += sizeof(uint32);
285 		*(team_id*)userData = appInfo.team;
286 		userData += sizeof(team_id);
287 		*(AVCodecContext**)userData = fStream->codec;
288 	}
289 #endif
290 
291 	return B_OK;
292 }
293 
294 
295 status_t
296 AVFormatWriter::StreamCookie::WriteChunk(const void* chunkBuffer,
297 	size_t chunkSize, media_encode_info* encodeInfo)
298 {
299 	TRACE_PACKET("AVFormatWriter::StreamCookie[%d]::WriteChunk(%p, %ld, "
300 		"start_time: %" B_PRIdBIGTIME ")\n", fStream->index, chunkBuffer, chunkSize,
301 		encodeInfo->start_time);
302 
303 	BAutolock _(fStreamLock);
304 
305 	fPacket.data = const_cast<uint8_t*>((const uint8_t*)chunkBuffer);
306 	fPacket.size = chunkSize;
307 	fPacket.stream_index = fStream->index;
308 
309 	fPacket.pts = int64_t((double)encodeInfo->start_time
310 		* fStream->time_base.den / (1000000.0 * fStream->time_base.num)
311 		+ 0.5);
312 
313 	fPacket.dts = fPacket.pts;
314 
315 	fPacket.flags = 0;
316 	if ((encodeInfo->flags & B_MEDIA_KEY_FRAME) != 0)
317 		fPacket.flags |= AV_PKT_FLAG_KEY;
318 
319 	TRACE_PACKET("  PTS: %" PRId64 " (stream->time_base: (%d/%d)\n", fPacket.pts,
320 		fStream->time_base.num, fStream->time_base.den);
321 
322 #if 0
323 	// TODO: Eventually, we need to write interleaved packets, but
324 	// maybe we are only supposed to use this if we have actually
325 	// more than one stream. For the moment, this crashes in AVPacket
326 	// shuffling inside libavformat. Maybe if we want to use this, we
327 	// need to allocate a separate AVPacket and copy the chunk buffer.
328 	int result = av_interleaved_write_frame(fFormatContext, &fPacket);
329 	if (result < 0)
330 		TRACE("  av_interleaved_write_frame(): %d\n", result);
331 #else
332 	int result = av_write_frame(fFormatContext, &fPacket);
333 	if (result < 0)
334 		TRACE("  av_write_frame(): %d\n", result);
335 #endif
336 
337 	return result == 0 ? B_OK : B_ERROR;
338 }
339 
340 
341 status_t
342 AVFormatWriter::StreamCookie::AddTrackInfo(uint32 code,
343 	const void* data, size_t size, uint32 flags)
344 {
345 	TRACE("AVFormatWriter::StreamCookie::AddTrackInfo(%" B_PRIu32 ", %p, %ld, %" B_PRIu32 ")\n",
346 		code, data, size, flags);
347 
348 	BAutolock _(fStreamLock);
349 
350 	return B_NOT_SUPPORTED;
351 }
352 
353 
354 // #pragma mark - AVFormatWriter
355 
356 
357 AVFormatWriter::AVFormatWriter()
358 	:
359 	fFormatContext(avformat_alloc_context()),
360 	fCodecOpened(false),
361 	fHeaderError(-1),
362 	fIOContext(NULL),
363 	fStreamLock("stream lock")
364 {
365 	TRACE("AVFormatWriter::AVFormatWriter\n");
366 }
367 
368 
369 AVFormatWriter::~AVFormatWriter()
370 {
371 	TRACE("AVFormatWriter::~AVFormatWriter\n");
372 
373 	// Free the streams and close the AVCodecContexts
374 	for (unsigned i = 0; i < fFormatContext->nb_streams; i++) {
375 		av_freep(&fFormatContext->streams[i]->codecpar);
376 		av_freep(&fFormatContext->streams[i]);
377 	}
378 
379 	avformat_free_context(fFormatContext);
380 	av_free(fIOContext->buffer);
381 	av_free(fIOContext);
382 }
383 
384 
385 // #pragma mark -
386 
387 
388 status_t
389 AVFormatWriter::Init(const media_file_format* fileFormat)
390 {
391 	TRACE("AVFormatWriter::Init()\n");
392 
393 	if (fIOContext == NULL) {
394 		uint8* buffer = static_cast<uint8*>(av_malloc(kIOBufferSize));
395 		if (buffer == NULL)
396 			return B_NO_MEMORY;
397 
398 		// Allocate I/O context and initialize it with buffer
399 		// and hook functions, pass ourself as cookie.
400 		fIOContext = avio_alloc_context(buffer, kIOBufferSize, 1, this,
401 				0, _Write, _Seek);
402 		if (fIOContext == NULL) {
403 			av_free(buffer);
404 			TRACE("av_alloc_put_byte() failed!\n");
405 			return B_ERROR;
406 		}
407 
408 		// Setup I/O hooks. This seems to be enough.
409 		fFormatContext->pb = fIOContext;
410 	}
411 
412 	// Set the AVOutputFormat according to fileFormat...
413 	fFormatContext->oformat = av_guess_format(fileFormat->short_name,
414 		fileFormat->file_extension, fileFormat->mime_type);
415 	if (fFormatContext->oformat == NULL) {
416 		TRACE("  failed to find AVOuputFormat for %s\n",
417 			fileFormat->short_name);
418 		return B_NOT_SUPPORTED;
419 	}
420 
421 	TRACE("  found AVOuputFormat for %s: %s\n", fileFormat->short_name,
422 		fFormatContext->oformat->name);
423 
424 	return B_OK;
425 }
426 
427 
428 status_t
429 AVFormatWriter::SetCopyright(const char* copyright)
430 {
431 	TRACE("AVFormatWriter::SetCopyright(%s)\n", copyright);
432 
433 	return B_NOT_SUPPORTED;
434 }
435 
436 
437 status_t
438 AVFormatWriter::CommitHeader()
439 {
440 	TRACE("AVFormatWriter::CommitHeader\n");
441 
442 	if (fFormatContext == NULL)
443 		return B_NO_INIT;
444 
445 	if (fCodecOpened)
446 		return B_NOT_ALLOWED;
447 
448 	// We need to close the codecs we opened, even in case of failure.
449 	fCodecOpened = true;
450 
451 	fHeaderError = avformat_write_header(fFormatContext, NULL);
452 
453 	#ifdef TRACE_AVFORMAT_WRITER
454 	if (fHeaderError < 0) {
455 		char errorBuffer[AV_ERROR_MAX_STRING_SIZE];
456 		av_strerror(fHeaderError, errorBuffer, sizeof(errorBuffer));
457 		TRACE("  avformat_write_header(): %s\n", errorBuffer);
458 	} else {
459 		TRACE("  wrote header\n");
460 	}
461 
462 	for (unsigned i = 0; i < fFormatContext->nb_streams; i++) {
463 		AVStream* stream = fFormatContext->streams[i];
464 		TRACE("  stream[%u] time_base: (%d/%d)\n",
465 			i, stream->time_base.num, stream->time_base.den);
466 	}
467 	#endif // TRACE_AVFORMAT_WRITER
468 
469 	return fHeaderError == 0 ? B_OK : B_ERROR;
470 }
471 
472 
473 status_t
474 AVFormatWriter::Flush()
475 {
476 	TRACE("AVFormatWriter::Flush\n");
477 
478 	return B_NOT_SUPPORTED;
479 }
480 
481 
482 status_t
483 AVFormatWriter::Close()
484 {
485 	TRACE("AVFormatWriter::Close\n");
486 
487 	if (fFormatContext == NULL)
488 		return B_NO_INIT;
489 
490 	if (!fCodecOpened)
491 		return B_NOT_ALLOWED;
492 
493 	// From ffmpeg documentation: [av_write_trailer] may only be called
494 	// after a successful call to avformat_write_header.
495 	if (fHeaderError != 0)
496 		return B_ERROR;
497 
498 	int result = av_write_trailer(fFormatContext);
499 	if (result < 0)
500 		TRACE("  av_write_trailer(): %d\n", result);
501 	return result == 0 ? B_OK : B_ERROR;
502 }
503 
504 
505 status_t
506 AVFormatWriter::AllocateCookie(void** _cookie, media_format* format,
507 	const media_codec_info* codecInfo)
508 {
509 	TRACE("AVFormatWriter::AllocateCookie()\n");
510 
511 	if (fCodecOpened)
512 		return B_NOT_ALLOWED;
513 
514 	BAutolock _(fStreamLock);
515 
516 	if (_cookie == NULL)
517 		return B_BAD_VALUE;
518 
519 	StreamCookie* cookie = new(std::nothrow) StreamCookie(fFormatContext,
520 		&fStreamLock);
521 
522 	status_t ret = cookie->Init(format, codecInfo);
523 	if (ret != B_OK) {
524 		delete cookie;
525 		return ret;
526 	}
527 
528 	*_cookie = cookie;
529 	return B_OK;
530 }
531 
532 
533 status_t
534 AVFormatWriter::FreeCookie(void* _cookie)
535 {
536 	BAutolock _(fStreamLock);
537 
538 	StreamCookie* cookie = reinterpret_cast<StreamCookie*>(_cookie);
539 	delete cookie;
540 
541 	return B_OK;
542 }
543 
544 
545 // #pragma mark -
546 
547 
548 status_t
549 AVFormatWriter::SetCopyright(void* cookie, const char* copyright)
550 {
551 	TRACE("AVFormatWriter::SetCopyright(%p, %s)\n", cookie, copyright);
552 
553 	return B_NOT_SUPPORTED;
554 }
555 
556 
557 status_t
558 AVFormatWriter::AddTrackInfo(void* _cookie, uint32 code,
559 	const void* data, size_t size, uint32 flags)
560 {
561 	TRACE("AVFormatWriter::AddTrackInfo(%" B_PRIu32 ", %p, %ld, %" B_PRIu32 ")\n",
562 		code, data, size, flags);
563 
564 	if (fHeaderError != 0)
565 		return B_ERROR;
566 
567 	StreamCookie* cookie = reinterpret_cast<StreamCookie*>(_cookie);
568 	return cookie->AddTrackInfo(code, data, size, flags);
569 }
570 
571 
572 status_t
573 AVFormatWriter::WriteChunk(void* _cookie, const void* chunkBuffer,
574 	size_t chunkSize, media_encode_info* encodeInfo)
575 {
576 	TRACE_PACKET("AVFormatWriter::WriteChunk(%p, %ld, %p)\n", chunkBuffer,
577 		chunkSize, encodeInfo);
578 
579 	if (fHeaderError != 0)
580 		return B_ERROR;
581 
582 	StreamCookie* cookie = reinterpret_cast<StreamCookie*>(_cookie);
583 	return cookie->WriteChunk(chunkBuffer, chunkSize, encodeInfo);
584 }
585 
586 
587 // #pragma mark - I/O hooks
588 
589 
590 /*static*/ int
591 AVFormatWriter::_Write(void* cookie, uint8* buffer, int bufferSize)
592 {
593 	TRACE_IO("AVFormatWriter::_Write(%p, %p, %d)\n",
594 		cookie, buffer, bufferSize);
595 
596 	AVFormatWriter* writer = reinterpret_cast<AVFormatWriter*>(cookie);
597 
598 	ssize_t written = writer->fTarget->Write(buffer, bufferSize);
599 
600 	TRACE_IO("  written: %ld\n", written);
601 	return (int)written;
602 
603 }
604 
605 
606 /*static*/ off_t
607 AVFormatWriter::_Seek(void* cookie, off_t offset, int whence)
608 {
609 	TRACE_IO("AVFormatWriter::_Seek(%p, %lld, %d)\n",
610 		cookie, offset, whence);
611 
612 	AVFormatWriter* writer = reinterpret_cast<AVFormatWriter*>(cookie);
613 
614 	BMediaIO* mediaIO = dynamic_cast<BMediaIO*>(writer->fTarget);
615 	if (mediaIO == NULL)
616 		return -1;
617 
618 	// Support for special file size retrieval API without seeking anywhere:
619 	if (whence == AVSEEK_SIZE) {
620 		off_t size;
621 		if (mediaIO->GetSize(&size) == B_OK)
622 			return size;
623 
624 		return -1;
625 	}
626 
627 	off_t position = mediaIO->Seek(offset, whence);
628 	TRACE_IO("  position: %lld\n", position);
629 	if (position < 0)
630 		return -1;
631 
632 	return position;
633 }
634 
635 
636