xref: /haiku/src/add-ons/media/plugins/ffmpeg/AVFormatReader.cpp (revision 7cea5bf07ffaec7e25508f3b81a2e5bd989e1b34)
1 /*
2  * Copyright 2009-2010, Stephan Aßmus <superstippi@gmx.de>
3  * Copyright 2014, Colin Günther <coling@gmx.de>
4  * Copyright 2018, Dario Casalinuovo
5  * All rights reserved. Distributed under the terms of the GNU L-GPL license.
6  */
7 
8 #include "AVFormatReader.h"
9 
10 #include <stdio.h>
11 #include <string.h>
12 #include <stdlib.h>
13 
14 #include <new>
15 
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 <MimeType.h>
23 
24 extern "C" {
25 	#include "avcodec.h"
26 	#include "avformat.h"
27 }
28 
29 #include "DemuxerTable.h"
30 #include "gfx_util.h"
31 #include "Utilities.h"
32 
33 
34 //#define TRACE_AVFORMAT_READER
35 #ifdef TRACE_AVFORMAT_READER
36 #	define TRACE printf
37 #	define TRACE_IO(a...)
38 #	define TRACE_SEEK(a...) printf(a)
39 #	define TRACE_FIND(a...)
40 #	define TRACE_PACKET(a...)
41 #else
42 #	define TRACE(a...)
43 #	define TRACE_IO(a...)
44 #	define TRACE_SEEK(a...)
45 #	define TRACE_FIND(a...)
46 #	define TRACE_PACKET(a...)
47 #endif
48 
49 #define ERROR(a...) fprintf(stderr, a)
50 
51 
52 static uint32
53 avformat_to_beos_byte_order(AVSampleFormat format)
54 {
55 	// TODO: Huh?
56 	return B_MEDIA_HOST_ENDIAN;
57 }
58 
59 
60 static void
61 avdictionary_to_message(AVDictionary* dictionary, BMessage* message)
62 {
63 	if (dictionary == NULL)
64 		return;
65 
66 	AVDictionaryEntry* entry = NULL;
67 	while ((entry = av_dict_get(dictionary, "", entry,
68 		AV_DICT_IGNORE_SUFFIX))) {
69 		// convert entry keys into something more meaningful using the names from
70 		// id3v2.c
71 		if (strcmp(entry->key, "TALB") == 0 || strcmp(entry->key, "TAL") == 0)
72 			message->AddString("album", entry->value);
73 		else if (strcmp(entry->key, "TCOM") == 0)
74 			message->AddString("composer", entry->value);
75 		else if (strcmp(entry->key, "TCON") == 0 || strcmp(entry->key, "TCO") == 0)
76 			message->AddString("genre", entry->value);
77 		else if (strcmp(entry->key, "TCOP") == 0)
78 			message->AddString("copyright", entry->value);
79 		else if (strcmp(entry->key, "TDRL") == 0 || strcmp(entry->key, "TDRC") == 0)
80 			message->AddString("date", entry->value);
81 		else if (strcmp(entry->key, "TENC") == 0 || strcmp(entry->key, "TEN") == 0)
82 			message->AddString("encoded_by", entry->value);
83 		else if (strcmp(entry->key, "TIT2") == 0 || strcmp(entry->key, "TT2") == 0)
84 			message->AddString("title", entry->value);
85 		else if (strcmp(entry->key, "TLAN") == 0)
86 			message->AddString("language", entry->value);
87 		else if (strcmp(entry->key, "TPE1") == 0 || strcmp(entry->key, "TP1") == 0)
88 			message->AddString("artist", entry->value);
89 		else if (strcmp(entry->key, "TPE2") == 0 || strcmp(entry->key, "TP2") == 0)
90 			message->AddString("album_artist", entry->value);
91 		else if (strcmp(entry->key, "TPE3") == 0 || strcmp(entry->key, "TP3") == 0)
92 			message->AddString("performer", entry->value);
93 		else if (strcmp(entry->key, "TPOS") == 0)
94 			message->AddString("disc", entry->value);
95 		else if (strcmp(entry->key, "TPUB") == 0)
96 			message->AddString("publisher", entry->value);
97 		else if (strcmp(entry->key, "TRCK") == 0 || strcmp(entry->key, "TRK") == 0)
98 			message->AddString("track", entry->value);
99 		else if (strcmp(entry->key, "TSOA") == 0)
100 			message->AddString("album-sort", entry->value);
101 		else if (strcmp(entry->key, "TSOP") == 0)
102 			message->AddString("artist-sort", entry->value);
103 		else if (strcmp(entry->key, "TSOT") == 0)
104 			message->AddString("title-sort", entry->value);
105 		else if (strcmp(entry->key, "TSSE") == 0)
106 			message->AddString("encoder", entry->value);
107 		else if (strcmp(entry->key, "TYER") == 0)
108 			message->AddString("year", entry->value);
109 		else
110 			message->AddString(entry->key, entry->value);
111 	}
112 }
113 
114 
115 // #pragma mark - StreamBase
116 
117 
118 class StreamBase {
119 public:
120 								StreamBase(BMediaIO* source,
121 									BLocker* sourceLock, BLocker* streamLock);
122 	virtual						~StreamBase();
123 
124 	// Init an indivual AVFormatContext
125 			status_t			Open();
126 
127 	// Setup this stream to point to the AVStream at the given streamIndex.
128 	virtual	status_t			Init(int32 streamIndex);
129 
130 	inline	const AVFormatContext* Context() const
131 									{ return fContext; }
132 			int32				Index() const;
133 			int32				CountStreams() const;
134 			int32				StreamIndexFor(int32 virtualIndex) const;
135 	inline	int32				VirtualIndex() const
136 									{ return fVirtualIndex; }
137 
138 			double				FrameRate() const;
139 			bigtime_t			Duration() const;
140 
141 	virtual	status_t			Seek(uint32 flags, int64* frame,
142 									bigtime_t* time);
143 
144 			status_t			GetNextChunk(const void** chunkBuffer,
145 									size_t* chunkSize,
146 									media_header* mediaHeader);
147 
148 protected:
149 	// I/O hooks for libavformat, cookie will be a Stream instance.
150 	// Since multiple StreamCookies use the same BMediaIO source, they
151 	// maintain the position individually, and may need to seek the source
152 	// if it does not match anymore in _Read().
153 	static	int					_Read(void* cookie, uint8* buffer,
154 									int bufferSize);
155 	static	off_t				_Seek(void* cookie, off_t offset, int whence);
156 
157 			status_t			_NextPacket(bool reuse);
158 
159 			int64_t				_ConvertToStreamTimeBase(bigtime_t time) const;
160 			bigtime_t			_ConvertFromStreamTimeBase(int64_t time) const;
161 
162 protected:
163 			BMediaIO*			fSource;
164 			off_t				fPosition;
165 			// Since different threads may read from the source,
166 			// we need to protect the file position and I/O by a lock.
167 			BLocker*			fSourceLock;
168 
169 			BLocker*			fStreamLock;
170 
171 			AVFormatContext*	fContext;
172 			AVStream*			fStream;
173 			int32				fVirtualIndex;
174 
175 			media_format		fFormat;
176 
177 			AVIOContext*		fIOContext;
178 
179 			AVPacket			fPacket;
180 			bool				fReusePacket;
181 
182 			bool				fSeekByBytes;
183 			bool				fStreamBuildsIndexWhileReading;
184 };
185 
186 
187 StreamBase::StreamBase(BMediaIO* source, BLocker* sourceLock,
188 		BLocker* streamLock)
189 	:
190 	fSource(source),
191 	fPosition(0),
192 	fSourceLock(sourceLock),
193 
194 	fStreamLock(streamLock),
195 
196 	fContext(NULL),
197 	fStream(NULL),
198 	fVirtualIndex(-1),
199 	fIOContext(NULL),
200 
201 	fReusePacket(false),
202 
203 	fSeekByBytes(false),
204 	fStreamBuildsIndexWhileReading(false)
205 {
206 	// NOTE: Don't use streamLock here, it may not yet be initialized!
207 
208 	av_new_packet(&fPacket, 0);
209 	fFormat.Clear();
210 }
211 
212 
213 StreamBase::~StreamBase()
214 {
215 	avformat_close_input(&fContext);
216 	av_packet_unref(&fPacket);
217 	if (fIOContext != NULL)
218 		av_free(fIOContext->buffer);
219 	av_free(fIOContext);
220 }
221 
222 
223 status_t
224 StreamBase::Open()
225 {
226 	BAutolock _(fStreamLock);
227 
228 	// Init probing data
229 	size_t bufferSize = 32768;
230 	uint8* buffer = static_cast<uint8*>(av_malloc(bufferSize));
231 	if (buffer == NULL)
232 		return B_NO_MEMORY;
233 
234 	// First try to identify the file using the MIME database, as ffmpeg
235 	// is not very good at this and relies on us to give it the file extension
236 	// as an hint.
237 	// For this we need some valid data in the buffer, the first 512 bytes
238 	// should do because our MIME sniffing never uses more.
239 	const char* extension = NULL;
240 	BMessage message;
241 	if (fSource->Read(buffer, 512) == 512) {
242 		BMimeType type;
243 		if (BMimeType::GuessMimeType(buffer, 512, &type) == B_OK) {
244 			if (type.GetFileExtensions(&message) == B_OK) {
245 				extension = message.FindString("extensions");
246 			}
247 		}
248 	}
249 
250 	// Allocate I/O context with buffer and hook functions, pass ourself as
251 	// cookie.
252 	memset(buffer, 0, bufferSize);
253 	fIOContext = avio_alloc_context(buffer, bufferSize, 0, this, _Read, 0,
254 		_Seek);
255 	if (fIOContext == NULL) {
256 		TRACE("StreamBase::Open() - avio_alloc_context() failed!\n");
257 		av_free(buffer);
258 		return B_ERROR;
259 	}
260 
261 	fContext = avformat_alloc_context();
262 	fContext->pb = fIOContext;
263 
264 	// Allocate our context and probe the input format
265 	if (avformat_open_input(&fContext, extension, NULL, NULL) < 0) {
266 		TRACE("StreamBase::Open() - avformat_open_input() failed!\n");
267 		// avformat_open_input() frees the context in case of failure
268 		fContext = NULL;
269 		av_free(fIOContext->buffer);
270 		av_free(fIOContext);
271 		fIOContext = NULL;
272 		return B_NOT_SUPPORTED;
273 	}
274 
275 	TRACE("StreamBase::Open() - "
276 		"avformat_open_input(): %s\n", fContext->iformat->name);
277 	TRACE("  flags:%s%s%s%s%s\n",
278 		(fContext->iformat->flags & AVFMT_GLOBALHEADER) ? " AVFMT_GLOBALHEADER" : "",
279 		(fContext->iformat->flags & AVFMT_NOTIMESTAMPS) ? " AVFMT_NOTIMESTAMPS" : "",
280 		(fContext->iformat->flags & AVFMT_GENERIC_INDEX) ? " AVFMT_GENERIC_INDEX" : "",
281 		(fContext->iformat->flags & AVFMT_TS_DISCONT) ? " AVFMT_TS_DISCONT" : "",
282 		(fContext->iformat->flags & AVFMT_VARIABLE_FPS) ? " AVFMT_VARIABLE_FPS" : ""
283 	);
284 
285 
286 	// Retrieve stream information
287 	if (avformat_find_stream_info(fContext, NULL) < 0) {
288 		TRACE("StreamBase::Open() - avformat_find_stream_info() failed!\n");
289 		return B_NOT_SUPPORTED;
290 	}
291 
292 	fSeekByBytes = (fContext->iformat->flags & AVFMT_TS_DISCONT) != 0;
293 	fStreamBuildsIndexWhileReading
294 		= (fContext->iformat->flags & AVFMT_GENERIC_INDEX) != 0
295 			|| fSeekByBytes;
296 
297 	TRACE("StreamBase::Open() - "
298 		"av_find_stream_info() success! Seeking by bytes: %d\n",
299 		fSeekByBytes);
300 
301 	return B_OK;
302 }
303 
304 
305 status_t
306 StreamBase::Init(int32 virtualIndex)
307 {
308 	BAutolock _(fStreamLock);
309 
310 	TRACE("StreamBase::Init(%ld)\n", virtualIndex);
311 
312 	if (fContext == NULL)
313 		return B_NO_INIT;
314 
315 	int32 streamIndex = StreamIndexFor(virtualIndex);
316 	if (streamIndex < 0) {
317 		TRACE("  bad stream index!\n");
318 		return B_BAD_INDEX;
319 	}
320 
321 	TRACE("  context stream index: %ld\n", streamIndex);
322 
323 	// We need to remember the virtual index so that
324 	// AVFormatReader::FreeCookie() can clear the correct stream entry.
325 	fVirtualIndex = virtualIndex;
326 
327 	// Make us point to the AVStream at streamIndex
328 	fStream = fContext->streams[streamIndex];
329 
330 // NOTE: Discarding other streams works for most, but not all containers,
331 // for example it does not work for the ASF demuxer. Since I don't know what
332 // other demuxer it breaks, let's just keep reading packets for unwanted
333 // streams, it just makes the _GetNextPacket() function slightly less
334 // efficient.
335 //	// Discard all other streams
336 //	for (unsigned i = 0; i < fContext->nb_streams; i++) {
337 //		if (i != (unsigned)streamIndex)
338 //			fContext->streams[i]->discard = AVDISCARD_ALL;
339 //	}
340 
341 	return B_OK;
342 }
343 
344 
345 int32
346 StreamBase::Index() const
347 {
348 	if (fStream != NULL)
349 		return fStream->index;
350 	return -1;
351 }
352 
353 
354 int32
355 StreamBase::CountStreams() const
356 {
357 	// Figure out the stream count. If the context has "AVPrograms", use
358 	// the first program (for now).
359 	// TODO: To support "programs" properly, the BMediaFile/Track API should
360 	// be extended accordingly. I guess programs are like TV channels in the
361 	// same satilite transport stream. Maybe call them "TrackGroups".
362 	if (fContext->nb_programs > 0) {
363 		// See libavformat/utils.c:dump_format()
364 		return fContext->programs[0]->nb_stream_indexes;
365 	}
366 	return fContext->nb_streams;
367 }
368 
369 
370 int32
371 StreamBase::StreamIndexFor(int32 virtualIndex) const
372 {
373 	// NOTE: See CountStreams()
374 	if (fContext->nb_programs > 0) {
375 		const AVProgram* program = fContext->programs[0];
376 		if (virtualIndex >= 0
377 			&& virtualIndex < (int32)program->nb_stream_indexes) {
378 			return program->stream_index[virtualIndex];
379 		}
380 	} else {
381 		if (virtualIndex >= 0 && virtualIndex < (int32)fContext->nb_streams)
382 			return virtualIndex;
383 	}
384 	return -1;
385 }
386 
387 
388 double
389 StreamBase::FrameRate() const
390 {
391 	// TODO: Find a way to always calculate a correct frame rate...
392 	double frameRate = 1.0;
393 	switch (fStream->codecpar->codec_type) {
394 		case AVMEDIA_TYPE_AUDIO:
395 			frameRate = (double)fStream->codecpar->sample_rate;
396 			break;
397 		case AVMEDIA_TYPE_VIDEO:
398 		{
399 			AVRational frame_rate = av_guess_frame_rate(NULL, fStream, NULL);
400 			if (frame_rate.den != 0 && frame_rate.num != 0)
401 				frameRate = av_q2d(frame_rate);
402 			else if (fStream->time_base.den != 0 && fStream->time_base.num != 0)
403 				frameRate = 1 / av_q2d(fStream->time_base);
404 
405 			// TODO: Fix up interlaced video for real
406 			if (frameRate == 50.0f)
407 				frameRate = 25.0f;
408 			break;
409 		}
410 		default:
411 			break;
412 	}
413 	if (frameRate <= 0.0)
414 		frameRate = 1.0;
415 	return frameRate;
416 }
417 
418 
419 bigtime_t
420 StreamBase::Duration() const
421 {
422 	// TODO: This is not working correctly for all stream types...
423 	// It seems that the calculations here are correct, because they work
424 	// for a couple of streams and are in line with the documentation, but
425 	// unfortunately, libavformat itself seems to set the time_base and
426 	// duration wrongly sometimes. :-(
427 
428 	int32 flags;
429 	fSource->GetFlags(&flags);
430 
431 	// "Mutable Size" (ie http streams) means we can't realistically compute
432 	// a duration. So don't let ffmpeg give a (wrong) estimate in this case.
433 	if ((flags & B_MEDIA_MUTABLE_SIZE) != 0)
434 		return 0;
435 
436 	if ((int64)fStream->duration != AV_NOPTS_VALUE)
437 		return _ConvertFromStreamTimeBase(fStream->duration);
438 	else if ((int64)fContext->duration != AV_NOPTS_VALUE)
439 		return (bigtime_t)fContext->duration;
440 
441 	return 0;
442 }
443 
444 
445 status_t
446 StreamBase::Seek(uint32 flags, int64* frame, bigtime_t* time)
447 {
448 	BAutolock _(fStreamLock);
449 
450 	if (fContext == NULL || fStream == NULL)
451 		return B_NO_INIT;
452 
453 	TRACE_SEEK("StreamBase::Seek(%ld,%s%s%s%s, %lld, "
454 		"%lld)\n", VirtualIndex(),
455 		(flags & B_MEDIA_SEEK_TO_FRAME) ? " B_MEDIA_SEEK_TO_FRAME" : "",
456 		(flags & B_MEDIA_SEEK_TO_TIME) ? " B_MEDIA_SEEK_TO_TIME" : "",
457 		(flags & B_MEDIA_SEEK_CLOSEST_BACKWARD)
458 			? " B_MEDIA_SEEK_CLOSEST_BACKWARD" : "",
459 		(flags & B_MEDIA_SEEK_CLOSEST_FORWARD)
460 			? " B_MEDIA_SEEK_CLOSEST_FORWARD" : "",
461 		*frame, *time);
462 
463 	double frameRate = FrameRate();
464 	if ((flags & B_MEDIA_SEEK_TO_FRAME) != 0) {
465 		// Seeking is always based on time, initialize it when client seeks
466 		// based on frame.
467 		*time = (bigtime_t)(*frame * 1000000.0 / frameRate + 0.5);
468 	}
469 
470 	int64_t timeStamp = *time;
471 
472 	int searchFlags = AVSEEK_FLAG_BACKWARD;
473 	if ((flags & B_MEDIA_SEEK_CLOSEST_FORWARD) != 0)
474 		searchFlags = 0;
475 
476 	if (fSeekByBytes) {
477 		searchFlags |= AVSEEK_FLAG_BYTE;
478 
479 		BAutolock _(fSourceLock);
480 		int64_t fileSize;
481 
482 		if (fSource->GetSize(&fileSize) != B_OK)
483 			return B_NOT_SUPPORTED;
484 
485 		int64_t duration = Duration();
486 		if (duration == 0)
487 			return B_NOT_SUPPORTED;
488 
489 		timeStamp = int64_t(fileSize * ((double)timeStamp / duration));
490 		if ((flags & B_MEDIA_SEEK_CLOSEST_BACKWARD) != 0) {
491 			timeStamp -= 65536;
492 			if (timeStamp < 0)
493 				timeStamp = 0;
494 		}
495 
496 		bool seekAgain = true;
497 		bool seekForward = true;
498 		bigtime_t lastFoundTime = -1;
499 		int64_t closestTimeStampBackwards = -1;
500 		while (seekAgain) {
501 			if (avformat_seek_file(fContext, -1, INT64_MIN, timeStamp,
502 				INT64_MAX, searchFlags) < 0) {
503 				TRACE("  avformat_seek_file() (by bytes) failed.\n");
504 				return B_ERROR;
505 			}
506 			seekAgain = false;
507 
508 			// Our last packet is toast in any case. Read the next one so we
509 			// know where we really seeked.
510 			fReusePacket = false;
511 			if (_NextPacket(true) == B_OK) {
512 				while (fPacket.pts == AV_NOPTS_VALUE) {
513 					fReusePacket = false;
514 					if (_NextPacket(true) != B_OK)
515 						return B_ERROR;
516 				}
517 				if (fPacket.pos >= 0)
518 					timeStamp = fPacket.pos;
519 				bigtime_t foundTime
520 					= _ConvertFromStreamTimeBase(fPacket.pts);
521 				if (foundTime != lastFoundTime) {
522 					lastFoundTime = foundTime;
523 					if (foundTime > *time) {
524 						if (closestTimeStampBackwards >= 0) {
525 							timeStamp = closestTimeStampBackwards;
526 							seekAgain = true;
527 							seekForward = false;
528 							continue;
529 						}
530 						int64_t diff = int64_t(fileSize
531 							* ((double)(foundTime - *time) / (2 * duration)));
532 						if (diff < 8192)
533 							break;
534 						timeStamp -= diff;
535 						TRACE_SEEK("  need to seek back (%lld) (time: %.2f "
536 							"-> %.2f)\n", timeStamp, *time / 1000000.0,
537 							foundTime / 1000000.0);
538 						if (timeStamp < 0)
539 							foundTime = 0;
540 						else {
541 							seekAgain = true;
542 							continue;
543 						}
544 					} else if (seekForward && foundTime < *time - 100000) {
545 						closestTimeStampBackwards = timeStamp;
546 						int64_t diff = int64_t(fileSize
547 							* ((double)(*time - foundTime) / (2 * duration)));
548 						if (diff < 8192)
549 							break;
550 						timeStamp += diff;
551 						TRACE_SEEK("  need to seek forward (%lld) (time: "
552 							"%.2f -> %.2f)\n", timeStamp, *time / 1000000.0,
553 							foundTime / 1000000.0);
554 						if (timeStamp > duration)
555 							foundTime = duration;
556 						else {
557 							seekAgain = true;
558 							continue;
559 						}
560 					}
561 				}
562 				TRACE_SEEK("  found time: %lld -> %lld (%.2f)\n", *time,
563 					foundTime, foundTime / 1000000.0);
564 				*time = foundTime;
565 				*frame = (uint64)(*time * frameRate / 1000000LL + 0.5);
566 				TRACE_SEEK("  seeked frame: %lld\n", *frame);
567 			} else {
568 				TRACE_SEEK("  _NextPacket() failed!\n");
569 				return B_ERROR;
570 			}
571 		}
572 	} else {
573 		// We may not get a PTS from the next packet after seeking, so
574 		// we try to get an expected time from the index.
575 		int64_t streamTimeStamp = _ConvertToStreamTimeBase(*time);
576 		int index = av_index_search_timestamp(fStream, streamTimeStamp,
577 			searchFlags);
578 		if (index < 0) {
579 			TRACE("  av_index_search_timestamp() failed\n");
580 		} else {
581 			if (index > 0) {
582 				const AVIndexEntry& entry = fStream->index_entries[index];
583 				streamTimeStamp = entry.timestamp;
584 			} else {
585 				// Some demuxers use the first index entry to store some
586 				// other information, like the total playing time for example.
587 				// Assume the timeStamp of the first entry is alays 0.
588 				// TODO: Handle start-time offset?
589 				streamTimeStamp = 0;
590 			}
591 			bigtime_t foundTime = _ConvertFromStreamTimeBase(streamTimeStamp);
592 			bigtime_t timeDiff = foundTime > *time
593 				? foundTime - *time : *time - foundTime;
594 
595 			if (timeDiff > 1000000
596 				&& (fStreamBuildsIndexWhileReading
597 					|| index == fStream->nb_index_entries - 1)) {
598 				// If the stream is building the index on the fly while parsing
599 				// it, we only have entries in the index for positions already
600 				// decoded, i.e. we cannot seek into the future. In that case,
601 				// just assume that we can seek where we want and leave
602 				// time/frame unmodified. Since successfully seeking one time
603 				// will generate index entries for the seeked to position, we
604 				// need to remember this in fStreamBuildsIndexWhileReading,
605 				// since when seeking back there will be later index entries,
606 				// but we still want to ignore the found entry.
607 				fStreamBuildsIndexWhileReading = true;
608 				TRACE_SEEK("  Not trusting generic index entry. "
609 					"(Current count: %d)\n", fStream->nb_index_entries);
610 			} else {
611 				// If we found a reasonably time, write it into *time.
612 				// After seeking, we will try to read the sought time from
613 				// the next packet. If the packet has no PTS value, we may
614 				// still have a more accurate time from the index lookup.
615 				*time = foundTime;
616 			}
617 		}
618 
619 		if (avformat_seek_file(fContext, -1, INT64_MIN, timeStamp, INT64_MAX,
620 				searchFlags) < 0) {
621 			TRACE("  avformat_seek_file() failed.\n");
622 			// Try to fall back to av_seek_frame()
623 			timeStamp = _ConvertToStreamTimeBase(timeStamp);
624 			if (av_seek_frame(fContext, fStream->index, timeStamp,
625 				searchFlags) < 0) {
626 				TRACE("  avformat_seek_frame() failed as well.\n");
627 				// Fall back to seeking to the beginning by bytes
628 				timeStamp = 0;
629 				if (av_seek_frame(fContext, fStream->index, timeStamp,
630 						AVSEEK_FLAG_BYTE) < 0) {
631 					TRACE("  avformat_seek_frame() by bytes failed as "
632 						"well.\n");
633 					// Do not propagate error in any case. We fail if we can't
634 					// read another packet.
635 				} else
636 					*time = 0;
637 			}
638 		}
639 
640 		// Our last packet is toast in any case. Read the next one so
641 		// we know where we really sought.
642 		bigtime_t foundTime = *time;
643 
644 		fReusePacket = false;
645 		if (_NextPacket(true) == B_OK) {
646 			if (fPacket.pts != AV_NOPTS_VALUE)
647 				foundTime = _ConvertFromStreamTimeBase(fPacket.pts);
648 			else
649 				TRACE_SEEK("  no PTS in packet after seeking\n");
650 		} else
651 			TRACE_SEEK("  _NextPacket() failed!\n");
652 
653 		*time = foundTime;
654 		TRACE_SEEK("  sought time: %.2fs\n", *time / 1000000.0);
655 		*frame = (uint64)(*time * frameRate / 1000000.0 + 0.5);
656 		TRACE_SEEK("  sought frame: %lld\n", *frame);
657 	}
658 
659 	return B_OK;
660 }
661 
662 
663 status_t
664 StreamBase::GetNextChunk(const void** chunkBuffer,
665 	size_t* chunkSize, media_header* mediaHeader)
666 {
667 	BAutolock _(fStreamLock);
668 
669 	TRACE_PACKET("StreamBase::GetNextChunk()\n");
670 
671 	// Get the last stream DTS before reading the next packet, since
672 	// then it points to that one.
673 	int64 lastStreamDTS = fStream->cur_dts;
674 
675 	status_t ret = _NextPacket(false);
676 	if (ret != B_OK) {
677 		*chunkBuffer = NULL;
678 		*chunkSize = 0;
679 		return ret;
680 	}
681 
682 	// According to libavformat documentation, fPacket is valid until the
683 	// next call to av_read_frame(). This is what we want and we can share
684 	// the memory with the least overhead.
685 	*chunkBuffer = fPacket.data;
686 	*chunkSize = fPacket.size;
687 
688 	if (mediaHeader != NULL) {
689 		mediaHeader->type = fFormat.type;
690 		mediaHeader->buffer = 0;
691 		mediaHeader->destination = -1;
692 		mediaHeader->time_source = -1;
693 		mediaHeader->size_used = fPacket.size;
694 
695 		// FFmpeg recommends to use the decoding time stamps as primary source
696 		// for presentation time stamps, especially for video formats that are
697 		// using frame reordering. More over this way it is ensured that the
698 		// returned start times are ordered in a monotonically increasing time
699 		// series (even for videos that contain B-frames).
700 		// \see http://git.videolan.org/?p=ffmpeg.git;a=blob;f=libavformat/avformat.h;h=1e8a6294890d580cd9ebc684eaf4ce57c8413bd8;hb=9153b33a742c4e2a85ff6230aea0e75f5a8b26c2#l1623
701 		bigtime_t presentationTimeStamp;
702 		if (fPacket.dts != AV_NOPTS_VALUE)
703 			presentationTimeStamp = fPacket.dts;
704 		else if (fPacket.pts != AV_NOPTS_VALUE)
705 			presentationTimeStamp = fPacket.pts;
706 		else
707 			presentationTimeStamp = lastStreamDTS;
708 
709 		mediaHeader->start_time	= _ConvertFromStreamTimeBase(presentationTimeStamp);
710 		mediaHeader->file_pos = fPacket.pos;
711 		mediaHeader->data_offset = 0;
712 		switch (mediaHeader->type) {
713 			case B_MEDIA_RAW_AUDIO:
714 				break;
715 			case B_MEDIA_ENCODED_AUDIO:
716 				mediaHeader->u.encoded_audio.buffer_flags
717 					= (fPacket.flags & AV_PKT_FLAG_KEY) ? B_MEDIA_KEY_FRAME : 0;
718 				break;
719 			case B_MEDIA_RAW_VIDEO:
720 				mediaHeader->u.raw_video.line_count
721 					= fFormat.u.raw_video.display.line_count;
722 				break;
723 			case B_MEDIA_ENCODED_VIDEO:
724 				mediaHeader->u.encoded_video.field_flags
725 					= (fPacket.flags & AV_PKT_FLAG_KEY) ? B_MEDIA_KEY_FRAME : 0;
726 				mediaHeader->u.encoded_video.line_count
727 					= fFormat.u.encoded_video.output.display.line_count;
728 				break;
729 			default:
730 				break;
731 		}
732 	}
733 
734 //	static bigtime_t pts[2];
735 //	static bigtime_t lastPrintTime = system_time();
736 //	static BLocker printLock;
737 //	if (fStream->index < 2) {
738 //		if (fPacket.pts != AV_NOPTS_VALUE)
739 //			pts[fStream->index] = _ConvertFromStreamTimeBase(fPacket.pts);
740 //		printLock.Lock();
741 //		bigtime_t now = system_time();
742 //		if (now - lastPrintTime > 1000000) {
743 //			printf("PTS: %.4f/%.4f, diff: %.4f\r", pts[0] / 1000000.0,
744 //				pts[1] / 1000000.0, (pts[0] - pts[1]) / 1000000.0);
745 //			fflush(stdout);
746 //			lastPrintTime = now;
747 //		}
748 //		printLock.Unlock();
749 //	}
750 
751 	return B_OK;
752 }
753 
754 
755 // #pragma mark -
756 
757 
758 /*static*/ int
759 StreamBase::_Read(void* cookie, uint8* buffer, int bufferSize)
760 {
761 	StreamBase* stream = reinterpret_cast<StreamBase*>(cookie);
762 
763 	BAutolock _(stream->fSourceLock);
764 
765 	TRACE_IO("StreamBase::_Read(%p, %p, %d) position: %lld\n",
766 		cookie, buffer, bufferSize, stream->fPosition);
767 
768 	if (stream->fPosition != stream->fSource->Position()) {
769 		TRACE_IO("StreamBase::_Read fSource position: %lld\n",
770 			stream->fSource->Position());
771 
772 		off_t position
773 			= stream->fSource->Seek(stream->fPosition, SEEK_SET);
774 		if (position != stream->fPosition)
775 			return -1;
776 	}
777 
778 	ssize_t read = stream->fSource->Read(buffer, bufferSize);
779 	if (read > 0)
780 		stream->fPosition += read;
781 
782 	TRACE_IO("  read: %ld\n", read);
783 	return (int)read;
784 
785 }
786 
787 
788 /*static*/ off_t
789 StreamBase::_Seek(void* cookie, off_t offset, int whence)
790 {
791 	TRACE_IO("StreamBase::_Seek(%p, %lld, %d)\n",
792 		cookie, offset, whence);
793 
794 	StreamBase* stream = reinterpret_cast<StreamBase*>(cookie);
795 
796 	BAutolock _(stream->fSourceLock);
797 
798 	// Support for special file size retrieval API without seeking
799 	// anywhere:
800 	if (whence == AVSEEK_SIZE) {
801 		off_t size;
802 		if (stream->fSource->GetSize(&size) == B_OK)
803 			return size;
804 		return -1;
805 	}
806 
807 	// If not requested to seek to an absolute position, we need to
808 	// confirm that the stream is currently at the position that we
809 	// think it is.
810 	if (whence != SEEK_SET
811 		&& stream->fPosition != stream->fSource->Position()) {
812 		off_t position
813 			= stream->fSource->Seek(stream->fPosition, SEEK_SET);
814 		if (position != stream->fPosition)
815 			return -1;
816 	}
817 
818 	off_t position = stream->fSource->Seek(offset, whence);
819 	TRACE_IO("  position: %lld\n", position);
820 	if (position < 0)
821 		return -1;
822 
823 	stream->fPosition = position;
824 
825 	return position;
826 }
827 
828 
829 status_t
830 StreamBase::_NextPacket(bool reuse)
831 {
832 	TRACE_PACKET("StreamBase::_NextPacket(%d)\n", reuse);
833 
834 	if (fReusePacket) {
835 		// The last packet was marked for reuse, so we keep using it.
836 		TRACE_PACKET("  re-using last packet\n");
837 		fReusePacket = reuse;
838 		return B_OK;
839 	}
840 
841 	av_packet_unref(&fPacket);
842 
843 	while (true) {
844 		if (av_read_frame(fContext, &fPacket) < 0) {
845 			// NOTE: Even though we may get the error for a different stream,
846 			// av_read_frame() is not going to be successful from here on, so
847 			// it doesn't matter
848 			fReusePacket = false;
849 			return B_LAST_BUFFER_ERROR;
850 		}
851 
852 		if (fPacket.stream_index == Index())
853 			break;
854 
855 		// This is a packet from another stream, ignore it.
856 		av_packet_unref(&fPacket);
857 	}
858 
859 	// Mark this packet with the new reuse flag.
860 	fReusePacket = reuse;
861 	return B_OK;
862 }
863 
864 
865 int64_t
866 StreamBase::_ConvertToStreamTimeBase(bigtime_t time) const
867 {
868 	int64 timeStamp = int64_t((double)time * fStream->time_base.den
869 		/ (1000000.0 * fStream->time_base.num) + 0.5);
870 	if (fStream->start_time != AV_NOPTS_VALUE)
871 		timeStamp += fStream->start_time;
872 	return timeStamp;
873 }
874 
875 
876 bigtime_t
877 StreamBase::_ConvertFromStreamTimeBase(int64_t time) const
878 {
879 	if (fStream->start_time != AV_NOPTS_VALUE)
880 		time -= fStream->start_time;
881 
882 	return bigtime_t(1000000.0 * time * fStream->time_base.num
883 		/ fStream->time_base.den + 0.5);
884 }
885 
886 
887 // #pragma mark - AVFormatReader::Stream
888 
889 
890 class AVFormatReader::Stream : public StreamBase {
891 public:
892 								Stream(BMediaIO* source,
893 									BLocker* streamLock);
894 	virtual						~Stream();
895 
896 	// Setup this stream to point to the AVStream at the given streamIndex.
897 	// This will also initialize the media_format.
898 	virtual	status_t			Init(int32 streamIndex);
899 
900 			status_t			GetMetaData(BMessage* data);
901 
902 	// Support for AVFormatReader
903 			status_t			GetStreamInfo(int64* frameCount,
904 									bigtime_t* duration, media_format* format,
905 									const void** infoBuffer,
906 									size_t* infoSize) const;
907 
908 			status_t			FindKeyFrame(uint32 flags, int64* frame,
909 									bigtime_t* time) const;
910 	virtual	status_t			Seek(uint32 flags, int64* frame,
911 									bigtime_t* time);
912 
913 private:
914 	mutable	BLocker				fLock;
915 
916 			struct KeyframeInfo {
917 				bigtime_t		requestedTime;
918 				int64			requestedFrame;
919 				bigtime_t		reportedTime;
920 				int64			reportedFrame;
921 				uint32			seekFlags;
922 			};
923 	mutable	KeyframeInfo		fLastReportedKeyframe;
924 	mutable	StreamBase*			fGhostStream;
925 };
926 
927 
928 
929 AVFormatReader::Stream::Stream(BMediaIO* source, BLocker* streamLock)
930 	:
931 	StreamBase(source, streamLock, &fLock),
932 	fLock("stream lock"),
933 	fGhostStream(NULL)
934 {
935 	fLastReportedKeyframe.requestedTime = 0;
936 	fLastReportedKeyframe.requestedFrame = 0;
937 	fLastReportedKeyframe.reportedTime = 0;
938 	fLastReportedKeyframe.reportedFrame = 0;
939 }
940 
941 
942 AVFormatReader::Stream::~Stream()
943 {
944 	delete fGhostStream;
945 }
946 
947 
948 status_t
949 AVFormatReader::Stream::Init(int32 virtualIndex)
950 {
951 	TRACE("AVFormatReader::Stream::Init(%ld)\n", virtualIndex);
952 
953 	status_t ret = StreamBase::Init(virtualIndex);
954 	if (ret != B_OK)
955 		return ret;
956 
957 	// Get a pointer to the AVCodecPaarameters for the stream at streamIndex.
958 	AVCodecParameters* codecParams = fStream->codecpar;
959 
960 	// initialize the media_format for this stream
961 	media_format* format = &fFormat;
962 	format->Clear();
963 
964 	media_format_description description;
965 
966 	// Set format family and type depending on codec_type of the stream.
967 	switch (codecParams->codec_type) {
968 		case AVMEDIA_TYPE_AUDIO:
969 			if ((codecParams->codec_id >= AV_CODEC_ID_PCM_S16LE)
970 				&& (codecParams->codec_id <= AV_CODEC_ID_PCM_U8)) {
971 				TRACE("  raw audio\n");
972 				format->type = B_MEDIA_RAW_AUDIO;
973 				description.family = B_ANY_FORMAT_FAMILY;
974 				// This will then apparently be handled by the (built into
975 				// BMediaTrack) RawDecoder.
976 			} else {
977 				TRACE("  encoded audio\n");
978 				format->type = B_MEDIA_ENCODED_AUDIO;
979 				description.family = B_MISC_FORMAT_FAMILY;
980 				description.u.misc.file_format = 'ffmp';
981 			}
982 			break;
983 		case AVMEDIA_TYPE_VIDEO:
984 			TRACE("  encoded video\n");
985 			format->type = B_MEDIA_ENCODED_VIDEO;
986 			description.family = B_MISC_FORMAT_FAMILY;
987 			description.u.misc.file_format = 'ffmp';
988 			break;
989 		default:
990 			TRACE("  unknown type\n");
991 			format->type = B_MEDIA_UNKNOWN_TYPE;
992 			return B_ERROR;
993 			break;
994 	}
995 
996 	if (format->type == B_MEDIA_RAW_AUDIO) {
997 		// We cannot describe all raw-audio formats, some are unsupported.
998 		switch (codecParams->codec_id) {
999 			case AV_CODEC_ID_PCM_S16LE:
1000 				format->u.raw_audio.format
1001 					= media_raw_audio_format::B_AUDIO_SHORT;
1002 				format->u.raw_audio.byte_order
1003 					= B_MEDIA_LITTLE_ENDIAN;
1004 				break;
1005 			case AV_CODEC_ID_PCM_S16BE:
1006 				format->u.raw_audio.format
1007 					= media_raw_audio_format::B_AUDIO_SHORT;
1008 				format->u.raw_audio.byte_order
1009 					= B_MEDIA_BIG_ENDIAN;
1010 				break;
1011 			case AV_CODEC_ID_PCM_U16LE:
1012 //				format->u.raw_audio.format
1013 //					= media_raw_audio_format::B_AUDIO_USHORT;
1014 //				format->u.raw_audio.byte_order
1015 //					= B_MEDIA_LITTLE_ENDIAN;
1016 				return B_NOT_SUPPORTED;
1017 				break;
1018 			case AV_CODEC_ID_PCM_U16BE:
1019 //				format->u.raw_audio.format
1020 //					= media_raw_audio_format::B_AUDIO_USHORT;
1021 //				format->u.raw_audio.byte_order
1022 //					= B_MEDIA_BIG_ENDIAN;
1023 				return B_NOT_SUPPORTED;
1024 				break;
1025 			case AV_CODEC_ID_PCM_S8:
1026 				format->u.raw_audio.format
1027 					= media_raw_audio_format::B_AUDIO_CHAR;
1028 				break;
1029 			case AV_CODEC_ID_PCM_U8:
1030 				format->u.raw_audio.format
1031 					= media_raw_audio_format::B_AUDIO_UCHAR;
1032 				break;
1033 			default:
1034 				return B_NOT_SUPPORTED;
1035 				break;
1036 		}
1037 	} else {
1038 		if (description.family == B_MISC_FORMAT_FAMILY)
1039 			description.u.misc.codec = codecParams->codec_id;
1040 
1041 		BMediaFormats formats;
1042 		status_t status = formats.GetFormatFor(description, format);
1043 		if (status < B_OK)
1044 			TRACE("  formats.GetFormatFor() error: %s\n", strerror(status));
1045 
1046 		format->user_data_type = B_CODEC_TYPE_INFO;
1047 		*(uint32*)format->user_data = codecParams->codec_tag;
1048 		format->user_data[4] = 0;
1049 	}
1050 
1051 	format->require_flags = 0;
1052 	format->deny_flags = B_MEDIA_MAUI_UNDEFINED_FLAGS;
1053 
1054 	switch (format->type) {
1055 		case B_MEDIA_RAW_AUDIO:
1056 			format->u.raw_audio.frame_rate = (float)codecParams->sample_rate;
1057 			format->u.raw_audio.channel_count = codecParams->channels;
1058 			format->u.raw_audio.channel_mask = codecParams->channel_layout;
1059 			ConvertAVSampleFormatToRawAudioFormat(
1060 				(AVSampleFormat)codecParams->format,
1061 				format->u.raw_audio.format);
1062 			format->u.raw_audio.buffer_size = 0;
1063 
1064 			// Read one packet and mark it for later re-use. (So our first
1065 			// GetNextChunk() call does not read another packet.)
1066 			if (_NextPacket(true) == B_OK) {
1067 				TRACE("  successfully determined audio buffer size: %d\n",
1068 					fPacket.size);
1069 				format->u.raw_audio.buffer_size = fPacket.size;
1070 			}
1071 			break;
1072 
1073 		case B_MEDIA_ENCODED_AUDIO:
1074 			format->u.encoded_audio.bit_rate = codecParams->bit_rate;
1075 			format->u.encoded_audio.frame_size = codecParams->frame_size;
1076 			// Fill in some info about possible output format
1077 			format->u.encoded_audio.output
1078 				= media_multi_audio_format::wildcard;
1079 			format->u.encoded_audio.output.frame_rate
1080 				= (float)codecParams->sample_rate;
1081 			// Channel layout bits match in Be API and FFmpeg.
1082 			format->u.encoded_audio.output.channel_count
1083 				= codecParams->channels;
1084 			format->u.encoded_audio.multi_info.channel_mask
1085 				= codecParams->channel_layout;
1086 			format->u.encoded_audio.output.byte_order
1087 				= avformat_to_beos_byte_order(
1088 					(AVSampleFormat)codecParams->format);
1089 
1090 			ConvertAVSampleFormatToRawAudioFormat(
1091 					(AVSampleFormat)codecParams->format,
1092 				format->u.encoded_audio.output.format);
1093 
1094 			if (codecParams->block_align > 0) {
1095 				format->u.encoded_audio.output.buffer_size
1096 					= codecParams->block_align;
1097 			} else {
1098 				format->u.encoded_audio.output.buffer_size
1099 					= codecParams->frame_size * codecParams->channels
1100 						* (format->u.encoded_audio.output.format
1101 							& media_raw_audio_format::B_AUDIO_SIZE_MASK);
1102 			}
1103 			break;
1104 
1105 		case B_MEDIA_ENCODED_VIDEO:
1106 // TODO: Specifying any of these seems to throw off the format matching
1107 // later on.
1108 //			format->u.encoded_video.avg_bit_rate = codecParams->bit_rate;
1109 //			format->u.encoded_video.max_bit_rate = codecParams->bit_rate
1110 //				+ codecParams->bit_rate_tolerance;
1111 
1112 //			format->u.encoded_video.encoding
1113 //				= media_encoded_video_format::B_ANY;
1114 
1115 //			format->u.encoded_video.frame_size = 1;
1116 //			format->u.encoded_video.forward_history = 0;
1117 //			format->u.encoded_video.backward_history = 0;
1118 
1119 			format->u.encoded_video.output.field_rate = FrameRate();
1120 			format->u.encoded_video.output.interlace = 1;
1121 
1122 			format->u.encoded_video.output.first_active = 0;
1123 			format->u.encoded_video.output.last_active
1124 				= codecParams->height - 1;
1125 				// TODO: Maybe libavformat actually provides that info
1126 				// somewhere...
1127 			format->u.encoded_video.output.orientation
1128 				= B_VIDEO_TOP_LEFT_RIGHT;
1129 
1130 			ConvertAVCodecParametersToVideoAspectWidthAndHeight(*codecParams,
1131 				format->u.encoded_video.output.pixel_width_aspect,
1132 				format->u.encoded_video.output.pixel_height_aspect);
1133 
1134 			format->u.encoded_video.output.display.format
1135 				= pixfmt_to_colorspace(codecParams->format);
1136 			format->u.encoded_video.output.display.line_width
1137 				= codecParams->width;
1138 			format->u.encoded_video.output.display.line_count
1139 				= codecParams->height;
1140 			TRACE("  width/height: %d/%d\n", codecParams->width,
1141 				codecParams->height);
1142 			format->u.encoded_video.output.display.bytes_per_row = 0;
1143 			format->u.encoded_video.output.display.pixel_offset = 0;
1144 			format->u.encoded_video.output.display.line_offset = 0;
1145 			format->u.encoded_video.output.display.flags = 0; // TODO
1146 
1147 			break;
1148 
1149 		default:
1150 			// This is an unknown format to us.
1151 			break;
1152 	}
1153 
1154 	// Add the meta data, if any
1155 	if (codecParams->extradata_size > 0) {
1156 		format->SetMetaData(codecParams->extradata,
1157 			codecParams->extradata_size);
1158 		TRACE("  extradata: %p\n", format->MetaData());
1159 	}
1160 
1161 	TRACE("  extradata_size: %d\n", codecParams->extradata_size);
1162 //	TRACE("  intra_matrix: %p\n", codecParams->intra_matrix);
1163 //	TRACE("  inter_matrix: %p\n", codecParams->inter_matrix);
1164 //	TRACE("  get_buffer(): %p\n", codecParams->get_buffer);
1165 //	TRACE("  release_buffer(): %p\n", codecParams->release_buffer);
1166 
1167 #ifdef TRACE_AVFORMAT_READER
1168 	char formatString[512];
1169 	if (string_for_format(*format, formatString, sizeof(formatString)))
1170 		TRACE("  format: %s\n", formatString);
1171 
1172 	uint32 encoding = format->Encoding();
1173 	TRACE("  encoding '%.4s'\n", (char*)&encoding);
1174 #endif
1175 
1176 	return B_OK;
1177 }
1178 
1179 
1180 status_t
1181 AVFormatReader::Stream::GetMetaData(BMessage* data)
1182 {
1183 	BAutolock _(&fLock);
1184 
1185 	avdictionary_to_message(fStream->metadata, data);
1186 
1187 	return B_OK;
1188 }
1189 
1190 
1191 status_t
1192 AVFormatReader::Stream::GetStreamInfo(int64* frameCount,
1193 	bigtime_t* duration, media_format* format, const void** infoBuffer,
1194 	size_t* infoSize) const
1195 {
1196 	BAutolock _(&fLock);
1197 
1198 	TRACE("AVFormatReader::Stream::GetStreamInfo(%ld)\n",
1199 		VirtualIndex());
1200 
1201 	double frameRate = FrameRate();
1202 	TRACE("  frameRate: %.4f\n", frameRate);
1203 
1204 	#ifdef TRACE_AVFORMAT_READER
1205 	if (fStream->start_time != AV_NOPTS_VALUE) {
1206 		bigtime_t startTime = _ConvertFromStreamTimeBase(fStream->start_time);
1207 		TRACE("  start_time: %lld or %.5fs\n", startTime,
1208 			startTime / 1000000.0);
1209 		// TODO: Handle start time in FindKeyFrame() and Seek()?!
1210 	}
1211 	#endif // TRACE_AVFORMAT_READER
1212 
1213 	*duration = Duration();
1214 
1215 	TRACE("  duration: %lld or %.5fs\n", *duration, *duration / 1000000.0);
1216 
1217 	#if 0
1218 	if (fStream->nb_index_entries > 0) {
1219 		TRACE("  dump of index entries:\n");
1220 		int count = 5;
1221 		int firstEntriesCount = min_c(fStream->nb_index_entries, count);
1222 		int i = 0;
1223 		for (; i < firstEntriesCount; i++) {
1224 			AVIndexEntry& entry = fStream->index_entries[i];
1225 			bigtime_t timeGlobal = entry.timestamp;
1226 			bigtime_t timeNative = _ConvertFromStreamTimeBase(timeGlobal);
1227 			TRACE("    [%d] native: %.5fs global: %.5fs\n", i,
1228 				timeNative / 1000000.0f, timeGlobal / 1000000.0f);
1229 		}
1230 		if (fStream->nb_index_entries - count > i) {
1231 			i = fStream->nb_index_entries - count;
1232 			TRACE("    ...\n");
1233 			for (; i < fStream->nb_index_entries; i++) {
1234 				AVIndexEntry& entry = fStream->index_entries[i];
1235 				bigtime_t timeGlobal = entry.timestamp;
1236 				bigtime_t timeNative = _ConvertFromStreamTimeBase(timeGlobal);
1237 				TRACE("    [%d] native: %.5fs global: %.5fs\n", i,
1238 					timeNative / 1000000.0f, timeGlobal / 1000000.0f);
1239 			}
1240 		}
1241 	}
1242 	#endif
1243 
1244 	*frameCount = fStream->nb_frames * fStream->codecpar->frame_size;
1245 	if (*frameCount == 0) {
1246 		// Calculate from duration and frame rate
1247 		*frameCount = (int64)(*duration * frameRate / 1000000LL);
1248 		TRACE("  frameCount calculated: %lld, from context: %lld\n",
1249 			*frameCount, fStream->nb_frames);
1250 	} else
1251 		TRACE("  frameCount: %lld\n", *frameCount);
1252 
1253 	*format = fFormat;
1254 
1255 	*infoBuffer = fStream->codecpar->extradata;
1256 	*infoSize = fStream->codecpar->extradata_size;
1257 
1258 	return B_OK;
1259 }
1260 
1261 
1262 status_t
1263 AVFormatReader::Stream::FindKeyFrame(uint32 flags, int64* frame,
1264 	bigtime_t* time) const
1265 {
1266 	BAutolock _(&fLock);
1267 
1268 	if (fContext == NULL || fStream == NULL)
1269 		return B_NO_INIT;
1270 
1271 	TRACE_FIND("AVFormatReader::Stream::FindKeyFrame(%ld,%s%s%s%s, "
1272 		"%lld, %lld)\n", VirtualIndex(),
1273 		(flags & B_MEDIA_SEEK_TO_FRAME) ? " B_MEDIA_SEEK_TO_FRAME" : "",
1274 		(flags & B_MEDIA_SEEK_TO_TIME) ? " B_MEDIA_SEEK_TO_TIME" : "",
1275 		(flags & B_MEDIA_SEEK_CLOSEST_BACKWARD)
1276 			? " B_MEDIA_SEEK_CLOSEST_BACKWARD" : "",
1277 		(flags & B_MEDIA_SEEK_CLOSEST_FORWARD)
1278 			? " B_MEDIA_SEEK_CLOSEST_FORWARD" : "",
1279 		*frame, *time);
1280 
1281 	bool inLastRequestedRange = false;
1282 	if ((flags & B_MEDIA_SEEK_TO_FRAME) != 0) {
1283 		if (fLastReportedKeyframe.reportedFrame
1284 			<= fLastReportedKeyframe.requestedFrame) {
1285 			inLastRequestedRange
1286 				= *frame >= fLastReportedKeyframe.reportedFrame
1287 					&& *frame <= fLastReportedKeyframe.requestedFrame;
1288 		} else {
1289 			inLastRequestedRange
1290 				= *frame >= fLastReportedKeyframe.requestedFrame
1291 					&& *frame <= fLastReportedKeyframe.reportedFrame;
1292 		}
1293 	} else if ((flags & B_MEDIA_SEEK_TO_FRAME) == 0) {
1294 		if (fLastReportedKeyframe.reportedTime
1295 			<= fLastReportedKeyframe.requestedTime) {
1296 			inLastRequestedRange
1297 				= *time >= fLastReportedKeyframe.reportedTime
1298 					&& *time <= fLastReportedKeyframe.requestedTime;
1299 		} else {
1300 			inLastRequestedRange
1301 				= *time >= fLastReportedKeyframe.requestedTime
1302 					&& *time <= fLastReportedKeyframe.reportedTime;
1303 		}
1304 	}
1305 
1306 	if (inLastRequestedRange) {
1307 		*frame = fLastReportedKeyframe.reportedFrame;
1308 		*time = fLastReportedKeyframe.reportedTime;
1309 		TRACE_FIND("  same as last reported keyframe\n");
1310 		return B_OK;
1311 	}
1312 
1313 	double frameRate = FrameRate();
1314 	if ((flags & B_MEDIA_SEEK_TO_FRAME) != 0)
1315 		*time = (bigtime_t)(*frame * 1000000.0 / frameRate + 0.5);
1316 
1317 	status_t ret;
1318 	if (fGhostStream == NULL) {
1319 		BAutolock _(fSourceLock);
1320 
1321 		fGhostStream = new(std::nothrow) StreamBase(fSource, fSourceLock,
1322 			&fLock);
1323 		if (fGhostStream == NULL) {
1324 			TRACE("  failed to allocate ghost stream\n");
1325 			return B_NO_MEMORY;
1326 		}
1327 
1328 		ret = fGhostStream->Open();
1329 		if (ret != B_OK) {
1330 			TRACE("  ghost stream failed to open: %s\n", strerror(ret));
1331 			return B_ERROR;
1332 		}
1333 
1334 		ret = fGhostStream->Init(fVirtualIndex);
1335 		if (ret != B_OK) {
1336 			TRACE("  ghost stream failed to init: %s\n", strerror(ret));
1337 			return B_ERROR;
1338 		}
1339 	}
1340 	fLastReportedKeyframe.requestedFrame = *frame;
1341 	fLastReportedKeyframe.requestedTime = *time;
1342 	fLastReportedKeyframe.seekFlags = flags;
1343 
1344 	ret = fGhostStream->Seek(flags, frame, time);
1345 	if (ret != B_OK) {
1346 		TRACE("  ghost stream failed to seek: %s\n", strerror(ret));
1347 		return B_ERROR;
1348 	}
1349 
1350 	fLastReportedKeyframe.reportedFrame = *frame;
1351 	fLastReportedKeyframe.reportedTime = *time;
1352 
1353 	TRACE_FIND("  found time: %.2fs\n", *time / 1000000.0);
1354 	if ((flags & B_MEDIA_SEEK_TO_FRAME) != 0) {
1355 		*frame = int64_t(*time * FrameRate() / 1000000.0 + 0.5);
1356 		TRACE_FIND("  found frame: %lld\n", *frame);
1357 	}
1358 
1359 	return B_OK;
1360 }
1361 
1362 
1363 status_t
1364 AVFormatReader::Stream::Seek(uint32 flags, int64* frame, bigtime_t* time)
1365 {
1366 	BAutolock _(&fLock);
1367 
1368 	if (fContext == NULL || fStream == NULL)
1369 		return B_NO_INIT;
1370 
1371 	// Put the old requested values into frame/time, since we already know
1372 	// that the sought frame/time will then match the reported values.
1373 	// TODO: Will not work if client changes seek flags (from backwards to
1374 	// forward or vice versa)!!
1375 	bool inLastRequestedRange = false;
1376 	if ((flags & B_MEDIA_SEEK_TO_FRAME) != 0) {
1377 		if (fLastReportedKeyframe.reportedFrame
1378 			<= fLastReportedKeyframe.requestedFrame) {
1379 			inLastRequestedRange
1380 				= *frame >= fLastReportedKeyframe.reportedFrame
1381 					&& *frame <= fLastReportedKeyframe.requestedFrame;
1382 		} else {
1383 			inLastRequestedRange
1384 				= *frame >= fLastReportedKeyframe.requestedFrame
1385 					&& *frame <= fLastReportedKeyframe.reportedFrame;
1386 		}
1387 	} else if ((flags & B_MEDIA_SEEK_TO_FRAME) == 0) {
1388 		if (fLastReportedKeyframe.reportedTime
1389 			<= fLastReportedKeyframe.requestedTime) {
1390 			inLastRequestedRange
1391 				= *time >= fLastReportedKeyframe.reportedTime
1392 					&& *time <= fLastReportedKeyframe.requestedTime;
1393 		} else {
1394 			inLastRequestedRange
1395 				= *time >= fLastReportedKeyframe.requestedTime
1396 					&& *time <= fLastReportedKeyframe.reportedTime;
1397 		}
1398 	}
1399 
1400 	if (inLastRequestedRange) {
1401 		*frame = fLastReportedKeyframe.requestedFrame;
1402 		*time = fLastReportedKeyframe.requestedTime;
1403 		flags = fLastReportedKeyframe.seekFlags;
1404 	}
1405 
1406 	return StreamBase::Seek(flags, frame, time);
1407 }
1408 
1409 
1410 // #pragma mark - AVFormatReader
1411 
1412 
1413 AVFormatReader::AVFormatReader()
1414 	:
1415 	fCopyright(""),
1416 	fStreams(NULL),
1417 	fSourceLock("source I/O lock")
1418 {
1419 	TRACE("AVFormatReader::AVFormatReader\n");
1420 }
1421 
1422 
1423 AVFormatReader::~AVFormatReader()
1424 {
1425 	TRACE("AVFormatReader::~AVFormatReader\n");
1426 	if (fStreams != NULL) {
1427 		// The client was supposed to call FreeCookie() on all
1428 		// allocated streams. Deleting the first stream is always
1429 		// prevented, we delete the other ones just in case.
1430 		int32 count = fStreams[0]->CountStreams();
1431 		for (int32 i = 0; i < count; i++)
1432 			delete fStreams[i];
1433 		delete[] fStreams;
1434 	}
1435 }
1436 
1437 
1438 // #pragma mark -
1439 
1440 
1441 const char*
1442 AVFormatReader::Copyright()
1443 {
1444 	if (fCopyright.Length() <= 0) {
1445 		BMessage message;
1446 		if (GetMetaData(&message) == B_OK)
1447 			message.FindString("copyright", &fCopyright);
1448 	}
1449 	return fCopyright.String();
1450 }
1451 
1452 
1453 status_t
1454 AVFormatReader::Sniff(int32* _streamCount)
1455 {
1456 	TRACE("AVFormatReader::Sniff\n");
1457 
1458 	BMediaIO* source = dynamic_cast<BMediaIO*>(Source());
1459 	if (source == NULL) {
1460 		TRACE("  not a BMediaIO, but we need it to be one.\n");
1461 		return B_NOT_SUPPORTED;
1462 	}
1463 
1464 	Stream* stream = new(std::nothrow) Stream(source,
1465 		&fSourceLock);
1466 	if (stream == NULL) {
1467 		ERROR("AVFormatReader::Sniff() - failed to allocate Stream\n");
1468 		return B_NO_MEMORY;
1469 	}
1470 
1471 	ObjectDeleter<Stream> streamDeleter(stream);
1472 
1473 	status_t ret = stream->Open();
1474 	if (ret != B_OK) {
1475 		TRACE("  failed to detect stream: %s\n", strerror(ret));
1476 		return ret;
1477 	}
1478 
1479 	delete[] fStreams;
1480 	fStreams = NULL;
1481 
1482 	int32 streamCount = stream->CountStreams();
1483 	if (streamCount == 0) {
1484 		TRACE("  failed to detect any streams: %s\n", strerror(ret));
1485 		return B_ERROR;
1486 	}
1487 
1488 	fStreams = new(std::nothrow) Stream*[streamCount];
1489 	if (fStreams == NULL) {
1490 		ERROR("AVFormatReader::Sniff() - failed to allocate streams\n");
1491 		return B_NO_MEMORY;
1492 	}
1493 
1494 	memset(fStreams, 0, sizeof(Stream*) * streamCount);
1495 	fStreams[0] = stream;
1496 	streamDeleter.Detach();
1497 
1498 	#ifdef TRACE_AVFORMAT_READER
1499 	av_dump_format(const_cast<AVFormatContext*>(stream->Context()), 0, "", 0);
1500 	#endif
1501 
1502 	if (_streamCount != NULL)
1503 		*_streamCount = streamCount;
1504 
1505 	return B_OK;
1506 }
1507 
1508 
1509 void
1510 AVFormatReader::GetFileFormatInfo(media_file_format* mff)
1511 {
1512 	TRACE("AVFormatReader::GetFileFormatInfo\n");
1513 
1514 	if (fStreams == NULL)
1515 		return;
1516 
1517 	// The first cookie is always there!
1518 	const AVFormatContext* context = fStreams[0]->Context();
1519 
1520 	if (context == NULL || context->iformat == NULL) {
1521 		TRACE("  no AVFormatContext or AVInputFormat!\n");
1522 		return;
1523 	}
1524 
1525 	const media_file_format* format = demuxer_format_for(context->iformat);
1526 
1527 	mff->capabilities = media_file_format::B_READABLE
1528 		| media_file_format::B_KNOWS_ENCODED_VIDEO
1529 		| media_file_format::B_KNOWS_ENCODED_AUDIO
1530 		| media_file_format::B_IMPERFECTLY_SEEKABLE;
1531 
1532 	if (format != NULL) {
1533 		mff->family = format->family;
1534 	} else {
1535 		TRACE("  no DemuxerFormat for AVInputFormat!\n");
1536 		mff->family = B_MISC_FORMAT_FAMILY;
1537 	}
1538 
1539 	mff->version = 100;
1540 
1541 	if (format != NULL) {
1542 		strcpy(mff->mime_type, format->mime_type);
1543 	} else {
1544 		// TODO: Would be nice to be able to provide this from AVInputFormat,
1545 		// maybe by extending the FFmpeg code itself (all demuxers).
1546 		strcpy(mff->mime_type, "");
1547 	}
1548 
1549 	if (context->iformat->extensions != NULL)
1550 		strcpy(mff->file_extension, context->iformat->extensions);
1551 	else {
1552 		TRACE("  no file extensions for AVInputFormat.\n");
1553 		strcpy(mff->file_extension, "");
1554 	}
1555 
1556 	if (context->iformat->name != NULL)
1557 		strcpy(mff->short_name,  context->iformat->name);
1558 	else {
1559 		TRACE("  no short name for AVInputFormat.\n");
1560 		strcpy(mff->short_name, "");
1561 	}
1562 
1563 	if (context->iformat->long_name != NULL)
1564 		sprintf(mff->pretty_name, "%s (FFmpeg)", context->iformat->long_name);
1565 	else {
1566 		if (format != NULL)
1567 			sprintf(mff->pretty_name, "%s (FFmpeg)", format->pretty_name);
1568 		else
1569 			strcpy(mff->pretty_name, "Unknown (FFmpeg)");
1570 	}
1571 }
1572 
1573 
1574 status_t
1575 AVFormatReader::GetMetaData(BMessage* _data)
1576 {
1577 	// The first cookie is always there!
1578 	const AVFormatContext* context = fStreams[0]->Context();
1579 
1580 	if (context == NULL)
1581 		return B_NO_INIT;
1582 
1583 	avdictionary_to_message(context->metadata, _data);
1584 
1585 	// Add chapter info
1586 	for (unsigned i = 0; i < context->nb_chapters; i++) {
1587 		AVChapter* chapter = context->chapters[i];
1588 		BMessage chapterData;
1589 		chapterData.AddInt64("start", bigtime_t(1000000.0
1590 			* chapter->start * chapter->time_base.num
1591 			/ chapter->time_base.den + 0.5));
1592 		chapterData.AddInt64("end", bigtime_t(1000000.0
1593 			* chapter->end * chapter->time_base.num
1594 			/ chapter->time_base.den + 0.5));
1595 
1596 		avdictionary_to_message(chapter->metadata, &chapterData);
1597 		_data->AddMessage("be:chapter", &chapterData);
1598 	}
1599 
1600 	// Add program info
1601 	for (unsigned i = 0; i < context->nb_programs; i++) {
1602 		BMessage programData;
1603 		avdictionary_to_message(context->programs[i]->metadata, &programData);
1604 		_data->AddMessage("be:program", &programData);
1605 	}
1606 
1607 	return B_OK;
1608 }
1609 
1610 
1611 // #pragma mark -
1612 
1613 
1614 status_t
1615 AVFormatReader::AllocateCookie(int32 streamIndex, void** _cookie)
1616 {
1617 	TRACE("AVFormatReader::AllocateCookie(%ld)\n", streamIndex);
1618 
1619 	BAutolock _(fSourceLock);
1620 
1621 	if (fStreams == NULL)
1622 		return B_NO_INIT;
1623 
1624 	if (streamIndex < 0 || streamIndex >= fStreams[0]->CountStreams())
1625 		return B_BAD_INDEX;
1626 
1627 	if (_cookie == NULL)
1628 		return B_BAD_VALUE;
1629 
1630 	Stream* cookie = fStreams[streamIndex];
1631 	if (cookie == NULL) {
1632 		// Allocate the cookie
1633 		BMediaIO* source = dynamic_cast<BMediaIO*>(Source());
1634 		if (source == NULL) {
1635 			TRACE("  not a BMediaIO, but we need it to be one.\n");
1636 			return B_NOT_SUPPORTED;
1637 		}
1638 
1639 		cookie = new(std::nothrow) Stream(source, &fSourceLock);
1640 		if (cookie == NULL) {
1641 			ERROR("AVFormatReader::Sniff() - failed to allocate "
1642 				"Stream\n");
1643 			return B_NO_MEMORY;
1644 		}
1645 
1646 		status_t ret = cookie->Open();
1647 		if (ret != B_OK) {
1648 			TRACE("  stream failed to open: %s\n", strerror(ret));
1649 			delete cookie;
1650 			return ret;
1651 		}
1652 	}
1653 
1654 	status_t ret = cookie->Init(streamIndex);
1655 	if (ret != B_OK) {
1656 		TRACE("  stream failed to initialize: %s\n", strerror(ret));
1657 		// NOTE: Never delete the first stream!
1658 		if (streamIndex != 0)
1659 			delete cookie;
1660 		return ret;
1661 	}
1662 
1663 	fStreams[streamIndex] = cookie;
1664 	*_cookie = cookie;
1665 
1666 	return B_OK;
1667 }
1668 
1669 
1670 status_t
1671 AVFormatReader::FreeCookie(void *_cookie)
1672 {
1673 	BAutolock _(fSourceLock);
1674 
1675 	Stream* cookie = reinterpret_cast<Stream*>(_cookie);
1676 
1677 	// NOTE: Never delete the first cookie!
1678 	if (cookie != NULL && cookie->VirtualIndex() != 0) {
1679 		if (fStreams != NULL)
1680 			fStreams[cookie->VirtualIndex()] = NULL;
1681 		delete cookie;
1682 	}
1683 
1684 	return B_OK;
1685 }
1686 
1687 
1688 // #pragma mark -
1689 
1690 
1691 status_t
1692 AVFormatReader::GetStreamInfo(void* _cookie, int64* frameCount,
1693 	bigtime_t* duration, media_format* format, const void** infoBuffer,
1694 	size_t* infoSize)
1695 {
1696 	Stream* cookie = reinterpret_cast<Stream*>(_cookie);
1697 	return cookie->GetStreamInfo(frameCount, duration, format, infoBuffer,
1698 		infoSize);
1699 }
1700 
1701 
1702 status_t
1703 AVFormatReader::GetStreamMetaData(void* _cookie, BMessage* _data)
1704 {
1705 	Stream* cookie = reinterpret_cast<Stream*>(_cookie);
1706 	return cookie->GetMetaData(_data);
1707 }
1708 
1709 
1710 status_t
1711 AVFormatReader::Seek(void* _cookie, uint32 seekTo, int64* frame,
1712 	bigtime_t* time)
1713 {
1714 	Stream* cookie = reinterpret_cast<Stream*>(_cookie);
1715 	return cookie->Seek(seekTo, frame, time);
1716 }
1717 
1718 
1719 status_t
1720 AVFormatReader::FindKeyFrame(void* _cookie, uint32 flags, int64* frame,
1721 	bigtime_t* time)
1722 {
1723 	Stream* cookie = reinterpret_cast<Stream*>(_cookie);
1724 	return cookie->FindKeyFrame(flags, frame, time);
1725 }
1726 
1727 
1728 status_t
1729 AVFormatReader::GetNextChunk(void* _cookie, const void** chunkBuffer,
1730 	size_t* chunkSize, media_header* mediaHeader)
1731 {
1732 	Stream* cookie = reinterpret_cast<Stream*>(_cookie);
1733 	return cookie->GetNextChunk(chunkBuffer, chunkSize, mediaHeader);
1734 }
1735