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