From 8235bfab976dfd20a40ef95dec28f2ada48c05ec Mon Sep 17 00:00:00 2001 From: Damiano Galassi Date: Mon, 21 Sep 2020 13:09:46 +0200 Subject: [PATCH] Update matroska parser. --- MP42/MP42MkvImporter.m | 294 ++--- MP42/muxer/MatroskaParser.c | 2498 +++++++++++++++++++++-------------- MP42/muxer/MatroskaParser.h | 356 ++--- 3 files changed, 1840 insertions(+), 1308 deletions(-) diff --git a/MP42/MP42MkvImporter.m b/MP42/MP42MkvImporter.m index 40f47a4..a95e859 100644 --- a/MP42/MP42MkvImporter.m +++ b/MP42/MP42MkvImporter.m @@ -23,33 +23,19 @@ #define SCALE_FACTOR 1000000.f -MP42_OBJC_DIRECT_MEMBERS -@interface MatroskaSample : NSObject { -@public - unsigned long long startTime; - unsigned long long endTime; - unsigned long long filePos; - unsigned int frameSize; - unsigned int frameFlags; -} -@end - -@implementation MatroskaSample -@end - MP42_OBJC_DIRECT_MEMBERS @interface MatroskaDemuxHelper : NSObject { @public MP42TrackId sourceID; TrackInfo *trackInfo; - NSMutableArray *queue; + NSMutableArray *queue; uint32_t timescale; uint64_t currentTime; uint64_t startTime; int64_t minDisplayOffset; - uint32_t buffer, samplesWritten, bufferFlush; + uint32_t buffer, samplesWritten, bufferFlush; MP42SampleBuffer *previousSample; } @@ -59,7 +45,8 @@ MP42_OBJC_DIRECT_MEMBERS - (instancetype)init { - if ((self = [super init])) { + self = [super init]; + if (self) { queue = [[NSMutableArray alloc] init]; startTime = INT64_MAX; } @@ -103,18 +90,11 @@ static int readData(struct StdIoStream *ioStream, uint64_t pos, uint8_t **data, return 1; } -static int readMkvPacket(struct StdIoStream *ioStream, TrackInfo *trackInfo, uint64_t FilePos, uint8_t** frame, uint32_t *FrameSize) +static int copyMkvPacket(TrackInfo *trackInfo, char **Frame, uint32_t *FrameSize) { uint8_t *packet = NULL; uint32_t iSize = *FrameSize; - if (fseeko(ioStream->fp, FilePos, SEEK_SET)) { -#ifdef DEBUG - fprintf(stderr,"fseeko(): %s\n", strerror(errno)); -#endif - return 0; - } - if (trackInfo->CompMethodPrivateSize != 0) { packet = malloc(iSize + trackInfo->CompMethodPrivateSize); memcpy(packet, trackInfo->CompMethodPrivate, trackInfo->CompMethodPrivateSize); @@ -128,29 +108,7 @@ static int readMkvPacket(struct StdIoStream *ioStream, TrackInfo *trackInfo, ui return 0; } - size_t rd = fread(packet + trackInfo->CompMethodPrivateSize, 1, iSize, ioStream->fp); - if (rd != iSize) { - if (rd == 0) { - if (feof(ioStream->fp)) { -#ifdef DEBUG - fprintf(stderr,"Unexpected EOF while reading frame\n"); -#endif - } - else { -#ifdef DEBUG - fprintf(stderr,"Error reading frame: %s\n",strerror(errno)); -#endif - } - } else { -#ifdef DEBUG - fprintf(stderr,"Short read while reading frame\n"); -#endif - } - - free(packet); - return 0; - } - + memcpy(packet + trackInfo->CompMethodPrivateSize, *Frame, iSize); iSize += trackInfo->CompMethodPrivateSize; if (trackInfo->CompEnabled) { @@ -178,7 +136,7 @@ static int readMkvPacket(struct StdIoStream *ioStream, TrackInfo *trackInfo, ui } } - *frame = packet; + *Frame = (char *)packet; *FrameSize = iSize; return 1; @@ -481,15 +439,17 @@ MP42_OBJC_DIRECT_MEMBERS - (NSArray *)approximatedTrackDataLength { SegmentInfo *segInfo = mkv_GetFileInfo(_matroskaFile); - NSInteger trackCount = mkv_GetNumTracks(_matroskaFile); + unsigned int trackCount = mkv_GetNumTracks(_matroskaFile); uint64_t trackSizes[trackCount]; uint64_t trackTimestamp[trackCount]; uint64_t StartTime, EndTime, FilePos; uint32_t Track, FrameSize, FrameFlags; + int64_t FrameDiscard; + char *frame; if (trackCount) { - for (int i = 0; i < trackCount; i++) { + for (unsigned int i = 0; i < trackCount; i++) { trackSizes[i] = 0; trackTimestamp[i] = 0; } @@ -497,17 +457,16 @@ MP42_OBJC_DIRECT_MEMBERS StartTime = 0; int i = 0; while (StartTime < (segInfo->Duration / 64)) { - if (!mkv_ReadFrame(_matroskaFile, 0, &Track, &StartTime, &EndTime, &FilePos, &FrameSize, &FrameFlags)) { + if (!mkv_ReadFrame(_matroskaFile, 0, &Track, &StartTime, &EndTime, &FilePos, &FrameSize, &frame, &FrameFlags, &FrameDiscard)) { trackSizes[Track] += FrameSize; trackTimestamp[Track] = StartTime; i++; - } - else { + } else { break; } } - for (int j = 0; i < trackCount; i++) { + for (unsigned int j = 0; i < trackCount; i++) { if (trackTimestamp[j] > 0) { trackSizes[j] = trackSizes[j] * (segInfo->Duration / trackTimestamp[j]); } @@ -517,7 +476,7 @@ MP42_OBJC_DIRECT_MEMBERS } NSMutableArray *sizes = [NSMutableArray array]; - for (int i = 0; i < trackCount; i++) { + for (unsigned int i = 0; i < trackCount; i++) { [sizes addObject:@(trackSizes[i])]; } @@ -551,6 +510,7 @@ static const struct { { "V_VP8", kMP42VideoCodecType_VP8 }, { "V_VP9", kMP42VideoCodecType_VP9 }, { "V_PRORES", kMP42VideoCodecType_AppleProRes422 }, + { "V_AV1", kMP42VideoCodecType_AV1 }, { "A_AAC", kMP42AudioCodecType_MPEG4AAC }, { "A_AAC/MPEG2/LC", kMP42AudioCodecType_MPEG4AAC }, @@ -572,7 +532,6 @@ static const struct { { "A_PCM/FLOAT/IEEE", kMP42AudioCodecType_LinearPCM }, { "A_ALAC", kMP42AudioCodecType_AppleLossless }, - { "S_TEXT/UTF8", kMP42SubtitleCodecType_Text }, { "S_TEXT/WEBVTT", kMP42SubtitleCodecType_WebVTT }, { "S_TEXT/ASS", kMP42SubtitleCodecType_SSA }, @@ -614,13 +573,15 @@ static NSString * TrackNameToString(TrackInfo *track) { uint64_t StartTime, EndTime, FilePos; uint32_t Track, FrameSize, FrameFlags; + int64_t FrameDiscard; + char *frame; // mask other tracks because we don't need them unsigned long TrackMask = ~0; TrackMask &= ~(1l << Id); mkv_SetTrackMask(_matroskaFile, TrackMask); - mkv_ReadFrame(_matroskaFile, 0, &Track, &StartTime, &EndTime, &FilePos, &FrameSize, &FrameFlags); + mkv_ReadFrame(_matroskaFile, 0, &Track, &StartTime, &EndTime, &FilePos, &FrameSize, &frame, &FrameFlags, &FrameDiscard); mkv_Seek(_matroskaFile, 0, 0); TrackInfo *trackInfo = mkv_GetTrackInfo(_matroskaFile, Id); @@ -683,35 +644,35 @@ static uint32_t timescale(TrackInfo *trackInfo) else if (!strcmp(trackInfo->CodecID, "A_AC3") || !strcmp(trackInfo->CodecID, "A_EAC3")) { mkv_SetTrackMask(_matroskaFile, ~(1l << track.sourceId)); - uint64_t StartTime, EndTime, FilePos; - uint32_t rt, FrameSize, FrameFlags; - uint8_t *frame = NULL; - NSData *magicCookie = nil; + uint64_t StartTime, EndTime, FilePos; + uint32_t rt, FrameSize, FrameFlags; + int64_t FrameDiscard; + char *Frame = NULL; + NSData *magicCookie = nil; if (!strcmp(trackInfo->CodecID, "A_AC3")) { // read first header to create track - int firstFrame = mkv_ReadFrame(_matroskaFile, 0, &rt, &StartTime, &EndTime, &FilePos, &FrameSize, &FrameFlags); + int firstFrame = mkv_ReadFrame(_matroskaFile, 0, &rt, &StartTime, &EndTime, &FilePos, &FrameSize, &Frame, &FrameFlags, &FrameDiscard); if (firstFrame != 0) { return nil; } - if (readMkvPacket(_ioStream, trackInfo, FilePos, &frame, &FrameSize)) { + if (copyMkvPacket(trackInfo, &Frame, &FrameSize)) { // parse AC3 header // collect all the necessary meta information uint64_t fscod, frmsizecod, bsid, bsmod, acmod, lfeon; uint32_t lfe_offset = 4; - fscod = (*(frame+4) >> 6) & 0x3; - frmsizecod = (*(frame+4) & 0x3f) >> 1; - bsid = (*(frame+5) >> 3) & 0x1f; - bsmod = (*(frame+5) & 0xf); - acmod = (*(frame+6) >> 5) & 0x7; + fscod = (*(Frame+4) >> 6) & 0x3; + frmsizecod = (*(Frame+4) & 0x3f) >> 1; + bsid = (*(Frame+5) >> 3) & 0x1f; + bsmod = (*(Frame+5) & 0xf); + acmod = (*(Frame+6) >> 5) & 0x7; if (acmod == 2) { lfe_offset -= 2; - } - else { + } else { if ((acmod & 1) && acmod != 1) { lfe_offset -= 2; } @@ -719,7 +680,7 @@ static uint32_t timescale(TrackInfo *trackInfo) lfe_offset -= 2; } } - lfeon = (*(frame+6) >> lfe_offset) & 0x1; + lfeon = (*(Frame+6) >> lfe_offset) & 0x1; NSMutableData *mutableCookie = [[NSMutableData alloc] init]; [mutableCookie appendBytes:&fscod length:sizeof(uint64_t)]; @@ -731,7 +692,7 @@ static uint32_t timescale(TrackInfo *trackInfo) magicCookie = mutableCookie; - free(frame); + free(Frame); } mkv_Seek(_matroskaFile, 0, 0); @@ -744,14 +705,14 @@ static uint32_t timescale(TrackInfo *trackInfo) struct eac3_info *context = NULL; SegmentInfo *segInfo = mkv_GetFileInfo(_matroskaFile); - while (!mkv_ReadFrame(_matroskaFile, 0, &rt, &StartTime, &EndTime, &FilePos, &FrameSize, &FrameFlags) && StartTime < (segInfo->Duration / 64)) + while (!mkv_ReadFrame(_matroskaFile, 0, &rt, &StartTime, &EndTime, &FilePos, &FrameSize, &Frame, &FrameFlags, &FrameDiscard) && StartTime < (segInfo->Duration / 64)) { - if (readMkvPacket(_ioStream, trackInfo, FilePos, &frame, &FrameSize)) { + if (copyMkvPacket(trackInfo, &Frame, &FrameSize)) { #ifdef DEBUG_PARSER printf("\n\nMP42MkvImporter.magicCookieForTrack Analyzing MKV EAC3 packet number %d at filepos 0x%llX (%llu) with size 0x%X (%u) bits\n", mkvpktnum++, FilePos, FilePos, FrameSize * 8, FrameSize * 8); #endif - analyze_EAC3((void *)&context, frame, FrameSize); - free(frame); + analyze_EAC3((void *)&context, (uint8_t *)Frame, FrameSize); + free(Frame); } } @@ -796,18 +757,16 @@ static uint32_t timescale(TrackInfo *trackInfo) if (!strcmp(trackInfo->CodecID, "A_EAC3")) { mkv_SetTrackMask(_matroskaFile, ~(1l << track.sourceId)); - uint64_t StartTime, EndTime, FilePos; - uint32_t rt, FrameSize, FrameFlags; - uint8_t *frame = NULL; + uint64_t StartTime, EndTime, FilePos; + uint32_t rt, FrameSize, FrameFlags; + int64_t FrameDiscard; + char *frame = NULL; - while (!mkv_ReadFrame(_matroskaFile, 0, &rt, &StartTime, &EndTime, &FilePos, &FrameSize, &FrameFlags) && mkvpktnum++ < 5) { - if (readMkvPacket(_ioStream, trackInfo, FilePos, &frame, &FrameSize)) - { + while (!mkv_ReadFrame(_matroskaFile, 0, &rt, &StartTime, &EndTime, &FilePos, &FrameSize, &frame, &FrameFlags, &FrameDiscard) && mkvpktnum++ < 5) { #ifdef DEBUG_PARSER printf("\nMP42MkvImporter.streamExtensionTypeForAudioTrack analyzing MKV EAC3 packet number %d at filepos 0x%llX (%llu) with size 0x%X (%u) bits\n", mkvpktnum++, FilePos, FilePos, FrameSize * 8, FrameSize * 8); #endif - analyze_EAC3((void *)&context, frame, FrameSize); //NB! This routine allocates buffer for context, because we're passing NULL as input! - } + analyze_EAC3((void *)&context, (uint8_t *)frame, FrameSize); //NB! This routine allocates buffer for context, because we're passing NULL as input! } } @@ -911,13 +870,15 @@ static uint32_t timescale(TrackInfo *trackInfo) // mask other tracks because we don't need them mkv_SetTrackMask(_matroskaFile, TrackMask); - uint64_t StartTime, EndTime, FilePos; - uint32_t Track, FrameSize, FrameFlags; - uint8_t *frame = NULL; - MatroskaSample *frameSample = nil, *currentSample = nil; - int64_t duration, next_duration; + uint64_t StartTime, EndTime, FilePos; + uint32_t Track, FrameSize, FrameFlags; + int64_t FrameDiscard; + char *Frame = NULL; - while (!mkv_ReadFrame(_matroskaFile, 0, &Track, &StartTime, &EndTime, &FilePos, &FrameSize, &FrameFlags) && !self.isCancelled) { + MP42SampleBuffer *frameSample = nil, *currentSample = nil; + int64_t duration, next_duration; + + while (!mkv_ReadFrame(_matroskaFile, 0, &Track, &StartTime, &EndTime, &FilePos, &FrameSize, &Frame, &FrameFlags, &FrameDiscard) && !self.isCancelled) { self.progress = (StartTime / _fileDuration / 10000); MatroskaDemuxHelper *demuxHelper = helpers[Track]; @@ -928,12 +889,11 @@ static uint32_t timescale(TrackInfo *trackInfo) } if (trackInfo->Type == TT_AUDIO) { - demuxHelper->samplesWritten++; - if (readMkvPacket(_ioStream, trackInfo, FilePos, &frame, &FrameSize)) { + if (copyMkvPacket(trackInfo, &Frame, &FrameSize)) { MP42SampleBuffer *sample = [[MP42SampleBuffer alloc] init]; - sample->data = frame; + sample->data = Frame; sample->size = FrameSize; sample->duration = MP4_INVALID_DURATION; sample->offset = 0; @@ -978,15 +938,16 @@ static uint32_t timescale(TrackInfo *trackInfo) #else [self enqueue:sample]; #endif + demuxHelper->samplesWritten++; } } if (trackInfo->Type == TT_SUB) { - if (readMkvPacket(_ioStream, trackInfo, FilePos, &frame, &FrameSize)) { + if (copyMkvPacket(trackInfo, &Frame, &FrameSize)) { if (strcmp(trackInfo->CodecID, "S_VOBSUB") && strcmp(trackInfo->CodecID, "S_HDMV/PGS")) { MP42SampleBuffer *sample = [[MP42SampleBuffer alloc] init]; - sample->data = frame; + sample->data = Frame; sample->size = FrameSize; sample->timescale = demuxHelper->timescale; sample->duration = EndTime / SCALE_FACTOR - StartTime / SCALE_FACTOR; @@ -995,16 +956,16 @@ static uint32_t timescale(TrackInfo *trackInfo) sample->flags |= MP42SampleBufferFlagIsSync; sample->trackId = demuxHelper->sourceID; + demuxHelper->samplesWritten++; [self enqueue:sample]; - demuxHelper->samplesWritten++; } else { MP42SampleBuffer *nextSample = [[MP42SampleBuffer alloc] init]; nextSample->timescale = demuxHelper->timescale; nextSample->duration = 0; nextSample->offset = 0; nextSample->decodeTimestamp = StartTime; - nextSample->data = frame; + nextSample->data = Frame; nextSample->size = FrameSize; nextSample->flags |= MP42SampleBufferFlagIsSync; nextSample->trackId = demuxHelper->sourceID; @@ -1030,10 +991,11 @@ static uint32_t timescale(TrackInfo *trackInfo) demuxHelper->previousSample->duration = (nextSample->decodeTimestamp - demuxHelper->previousSample->decodeTimestamp) / SCALE_FACTOR; } + demuxHelper->samplesWritten++; [self enqueue:demuxHelper->previousSample]; demuxHelper->previousSample = nextSample; - demuxHelper->samplesWritten++; + } else if (!strcmp(trackInfo->CodecID, "S_VOBSUB")) { // VobSub seems to have an end duration, and no blank samples, so create a new one each time to fill the gaps if (StartTime > demuxHelper->currentTime) { @@ -1060,28 +1022,32 @@ static uint32_t timescale(TrackInfo *trackInfo) else if (trackInfo->Type == TT_VIDEO) { + copyMkvPacket(trackInfo, &Frame, &FrameSize); + // read frames from file - frameSample = [[MatroskaSample alloc] init]; - frameSample->startTime = StartTime; - frameSample->endTime = EndTime; - frameSample->filePos = FilePos; - frameSample->frameSize = FrameSize; - frameSample->frameFlags = FrameFlags; + frameSample = [[MP42SampleBuffer alloc] init]; + frameSample->data = Frame; + frameSample->size = FrameSize; + frameSample->timescale = demuxHelper->timescale; + frameSample->decodeTimestamp = StartTime; + frameSample->presentationOutputTimestamp = EndTime; + frameSample->flags = (FrameFlags & FRAME_KF) ? MP42SampleBufferFlagIsSync : 0; + frameSample->trackId = demuxHelper->sourceID; [demuxHelper->queue addObject:frameSample]; - if ([demuxHelper->queue count] < bufferSize) { + if (demuxHelper->queue.count < bufferSize) { continue; } else { currentSample = [demuxHelper->queue objectAtIndex:demuxHelper->buffer]; - // matroska stores only the start and end time, so we need to recreate + // Matroska stores only the start and end time in decode order, so we need to recreate // the frame duration and the offset from the start time, the end time is useless // duration calculation - duration = demuxHelper->queue.lastObject->startTime - currentSample->startTime; + duration = demuxHelper->queue.lastObject->decodeTimestamp - currentSample->decodeTimestamp; - for (MatroskaSample *sample in demuxHelper->queue) { - if (sample != currentSample && (sample->startTime >= currentSample->startTime)) { - if ((next_duration = (sample->startTime - currentSample->startTime)) < duration) { + for (MP42SampleBuffer *sample in demuxHelper->queue) { + if (sample != currentSample && (sample->decodeTimestamp >= currentSample->decodeTimestamp)) { + if ((next_duration = (sample->decodeTimestamp - currentSample->decodeTimestamp)) < duration) { duration = next_duration; } } @@ -1092,40 +1058,27 @@ static uint32_t timescale(TrackInfo *trackInfo) } // offset calculation - int64_t offset = currentSample->startTime / 10000.0f - demuxHelper->currentTime / 10000.0f; + int64_t offset = currentSample->decodeTimestamp / 10000.0f - demuxHelper->currentTime / 10000.0f; demuxHelper->currentTime += duration; - if (readMkvPacket(_ioStream, trackInfo, currentSample->filePos, &frame, ¤tSample->frameSize)) { - MP42SampleBuffer *sample = [[MP42SampleBuffer alloc] init]; - sample->data = frame; - sample->size = currentSample->frameSize; - sample->timescale = demuxHelper->timescale; - sample->duration = duration / 10000.0f; - sample->offset = offset; - sample->decodeTimestamp = StartTime; - sample->flags |= (currentSample->frameFlags & FRAME_KF) ? MP42SampleBufferFlagIsSync : 0; - sample->trackId = demuxHelper->sourceID; + currentSample->duration = duration / 10000.0f; + currentSample->offset = offset; - demuxHelper->samplesWritten++; - - // save the minimum offset, used later to keep all the offset values positive - if (sample->offset < demuxHelper->minDisplayOffset) { - demuxHelper->minDisplayOffset = sample->offset; - } - - if (demuxHelper->buffer >= bufferSize) { - [demuxHelper->queue removeObjectAtIndex:0]; - } - if (demuxHelper->buffer < bufferSize) { - demuxHelper->buffer++; - } - - [self enqueue:sample]; + // save the minimum offset, used later to keep all the offset values positive + if (currentSample->offset < demuxHelper->minDisplayOffset) { + demuxHelper->minDisplayOffset = currentSample->offset; } - else { - continue; + + if (demuxHelper->buffer >= bufferSize) { + [demuxHelper->queue removeObjectAtIndex:0]; } + if (demuxHelper->buffer < bufferSize) { + demuxHelper->buffer++; + } + + demuxHelper->samplesWritten++; + [self enqueue:currentSample]; } } } @@ -1138,14 +1091,14 @@ static uint32_t timescale(TrackInfo *trackInfo) while (demuxHelper->queue.count) { if (demuxHelper->bufferFlush == 1) { // add a last sample to get the duration for the last frame - MatroskaSample *lastSample = [demuxHelper->queue lastObject]; - for (MatroskaSample *sample in demuxHelper->queue) { - if (sample->startTime > lastSample->startTime) { + MP42SampleBuffer *lastSample = demuxHelper->queue.lastObject; + for (MP42SampleBuffer *sample in demuxHelper->queue) { + if (sample->decodeTimestamp > lastSample->decodeTimestamp) { lastSample = sample; } } - frameSample = [[MatroskaSample alloc] init]; - frameSample->startTime = lastSample->endTime; + frameSample = [[MP42SampleBuffer alloc] init]; + frameSample->decodeTimestamp = lastSample->presentationOutputTimestamp; [demuxHelper->queue addObject:frameSample]; } currentSample = [demuxHelper->queue objectAtIndex:demuxHelper->buffer]; @@ -1153,51 +1106,40 @@ static uint32_t timescale(TrackInfo *trackInfo) // matroska stores only the start and end time, so we need to recreate // the frame duration and the offset from the start time, the end time is useless // duration calculation - duration = demuxHelper->queue.lastObject->startTime - currentSample->startTime; + duration = demuxHelper->queue.lastObject->decodeTimestamp - currentSample->decodeTimestamp; - for (MatroskaSample *sample in demuxHelper->queue) { - if (sample != currentSample && (sample->startTime >= currentSample->startTime)) { - if ((next_duration = (sample->startTime - currentSample->startTime)) < duration) { + for (MP42SampleBuffer *sample in demuxHelper->queue) { + if (sample != currentSample && (sample->decodeTimestamp >= currentSample->decodeTimestamp)) { + if ((next_duration = (sample->decodeTimestamp - currentSample->decodeTimestamp)) < duration) { duration = next_duration; } } } // offset calculation - int64_t offset = currentSample->startTime / 10000.0f - demuxHelper->currentTime / 10000.0f; + int64_t offset = currentSample->decodeTimestamp / 10000.0f - demuxHelper->currentTime / 10000.0f; demuxHelper->currentTime += duration; - if (readMkvPacket(_ioStream, trackInfo, currentSample->filePos, &frame, ¤tSample->frameSize)) { - MP42SampleBuffer *sample = [[MP42SampleBuffer alloc] init]; - sample->data = frame; - sample->size = currentSample->frameSize; - sample->timescale = demuxHelper->timescale; - sample->duration = duration / 10000.0f; - sample->offset = offset; - sample->decodeTimestamp = StartTime; - sample->flags |= (currentSample->frameFlags & FRAME_KF) ? MP42SampleBufferFlagIsSync : 0; - sample->trackId = demuxHelper->sourceID; + currentSample->timescale = demuxHelper->timescale; + currentSample->duration = duration / 10000.0f; + currentSample->offset = offset; - demuxHelper->samplesWritten++; - // save the minimum offset, used later to keep the all the offset values positive - if (sample->offset < demuxHelper->minDisplayOffset) { - demuxHelper->minDisplayOffset = sample->offset; - } - - if (demuxHelper->buffer >= bufferSize) { - [demuxHelper->queue removeObjectAtIndex:0]; - } - - [self enqueue:sample]; - - demuxHelper->bufferFlush++; - if (demuxHelper->bufferFlush >= bufferSize - 1) { - break; - } + // save the minimum offset, used later to keep the all the offset values positive + if (currentSample->offset < demuxHelper->minDisplayOffset) { + demuxHelper->minDisplayOffset = currentSample->offset; } - else { + + if (demuxHelper->buffer >= bufferSize) { + [demuxHelper->queue removeObjectAtIndex:0]; + } + + demuxHelper->samplesWritten++; + [self enqueue:currentSample]; + + demuxHelper->bufferFlush++; + if (demuxHelper->bufferFlush >= bufferSize - 1) { break; } } diff --git a/MP42/muxer/MatroskaParser.c b/MP42/muxer/MatroskaParser.c index c696392..c4c80ae 100644 --- a/MP42/muxer/MatroskaParser.c +++ b/MP42/muxer/MatroskaParser.c @@ -24,77 +24,75 @@ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * + * * $Id: MatroskaParser.c,v 1.75 2010/08/14 08:38:41 mike Exp $ - * + * */ -#ifdef HAVE_CONFIG_H -#include "config.h" -#endif - #include #include #include #include #include -#ifdef _WIN32 -#ifdef _MSC_VER -// MS names some functions differently -#define alloca _alloca -#define inline __inline -#else /* _MSC_VER */ -// support for building with MinGW on Windows -#include -#endif /* _MSC_VER */ -#include -#endif /* _WIN32 */ +#include "libavutil/common.h" -#ifdef HAVE_ALLOCA_H -#include +#if defined(_WIN32) && defined(_MSC_VER) +// MS names some functions differently +#define alloca _alloca +#define inline __inline + +#include +#elif defined(__MINGW32__) +#ifdef alloca +#undef alloca +#endif +#define alloca __builtin_alloca #endif #ifndef EVCBUG -#define EVCBUG +#define EVCBUG #endif -#include "matroskaparser.h" +#include "MatroskaParser.h" #ifdef MATROSKA_COMPRESSION_SUPPORT #include #endif -#define EBML_VERSION 1 -#define EBML_MAX_ID_LENGTH 4 -#define EBML_MAX_SIZE_LENGTH 8 -#define MATROSKA_VERSION 2 -#define MATROSKA_DOCTYPE "matroska" +#define EBML_VERSION 1 +#define EBML_MAX_ID_LENGTH 4 +#define EBML_MAX_SIZE_LENGTH 8 +#define MATROSKA_VERSION 2 +#define MATROSKA_DOCTYPE "matroska" #define WEBM_DOCTYPE "webm" -#define MAX_STRING_LEN 1023 -#define QSEGSIZE 512 -#define MAX_TRACKS 64 -#define MAX_READAHEAD (256*1024) +#define MAX_STRING_LEN 1023 +#define QSEGSIZE 512 +#define MAX_TRACKS 64 +#define MAX_READAHEAD (256*1024) -#define MAXCLUSTER (64*1048576) -#define MAXFRAME (4*1048576) +#define MAXCLUSTER (256*1048576) +#define MAXFRAME (4*1048576) -#ifdef _MSC_VER -#define LL(x) x##i64 -#define ULL(x) x##ui64 +#define MAXDURATIONREAD (13000000LL) +#define MAXDURATIONRETRY (6) + +#if defined(_WIN32) && defined(_MSC_VER) +#define LL(x) x##i64 +#define ULL(x) x##ui64 #else -#define LL(x) x##ll -#define ULL(x) x##ull +#define LL(x) x##ll +#define ULL(x) x##ull #endif -#define MAXU64 ULL(0xffffffffffffffff) -#define ONE ULL(1) +#define MAXU64 ULL(0xffffffffffffffff) +#define ONE ULL(1) // compatibility static char *mystrdup(struct InputStream *is,const char *src) { size_t len; - char *dst; + char *dst; if (src==NULL) return NULL; @@ -118,22 +116,18 @@ static void mystrlcpy(char *dst,const char *src,unsigned size) { dst[i] = 0; } -struct Cue { - ulonglong Time; - ulonglong Position; - ulonglong Block; - unsigned char Track; -}; - struct QueueEntry { - struct QueueEntry *next; - unsigned int Length; + struct QueueEntry *next; + unsigned int Length; + char *Data; - ulonglong Start; - ulonglong End; - ulonglong Position; + ulonglong Start; + ulonglong End; + ulonglong Position; - unsigned int flags; + longlong DiscardPadding; + + unsigned int flags; }; struct Queue { @@ -141,10 +135,10 @@ struct Queue { struct QueueEntry *tail; }; -#define MPF_ERROR 0x10000 -#define IBSZ 1024 +#define MPF_ERROR 0x10000 +#define IBSZ 1024 -#define RBRESYNC 1 +#define RBRESYNC 1 struct MatroskaFile { // parser config @@ -154,13 +148,14 @@ struct MatroskaFile { InputStream *cache; // internal buffering - char inbuf[IBSZ]; + char inbuf[IBSZ]; ulonglong bufbase; // file offset of the first byte in buffer - int bufpos; // current read position in buffer - int buflen; // valid bytes in buffer + int bufpos; // current read position in buffer + int buflen; // valid bytes in buffer + char *cpbuf; // error reporting - char errmsg[128]; + char errmsg[128]; jmp_buf jb; // pointers to key elements @@ -192,40 +187,41 @@ struct MatroskaFile { struct SegmentInfo Seg; // Tracks - unsigned int nTracks,nTracksSize; + unsigned int nTracks,nTracksSize; struct TrackInfo **Tracks; // Queues struct QueueEntry *QFreeList; - unsigned int nQBlocks,nQBlocksSize; + unsigned int nQBlocks,nQBlocksSize; struct QueueEntry **QBlocks; - struct Queue *Queues; - ulonglong readPosition; - unsigned long trackMask; - ulonglong pSegmentTop; // offset of next byte after the segment - ulonglong tcCluster; // current cluster timecode + struct Queue *Queues; + ulonglong readPosition; + ulonglong trackMask; + ulonglong pSegmentTop; // offset of next byte after the segment + ulonglong tcCluster; // current cluster timecode // Cues - unsigned int nCues,nCuesSize; - struct Cue *Cues; + unsigned int nCues,nCuesSize; + struct Cue *Cues; + unsigned char CueBestType; // Attachments - unsigned int nAttachments,nAttachmentsSize; + unsigned int nAttachments,nAttachmentsSize; struct Attachment *Attachments; // Chapters - unsigned int nChapters,nChaptersSize; + unsigned int nChapters,nChaptersSize; struct Chapter *Chapters; // Tags - unsigned int nTags,nTagsSize; - struct Tag *Tags; + unsigned int nTags,nTagsSize; + struct Tag *Tags; }; /////////////////////////////////////////////////////////////////////////// // error reporting static void myvsnprintf_string(char **pdest,char *de,const char *str) { - char *dest = *pdest; + char *dest = *pdest; while (dest < de && *str) *dest++ = *str++; @@ -234,21 +230,21 @@ static void myvsnprintf_string(char **pdest,char *de,const char *str) { } static void myvsnprintf_uint_impl(char **pdest,char *de,int width,int zero, - int neg,unsigned base,int letter, - int ms,ulonglong val) + int neg,unsigned base,int letter, + int ms,ulonglong val) { - char *dest = *pdest; - char tmp[21]; /* enough for 64 bit ints */ - char *np = tmp + sizeof(tmp); - int rw,pad,trail; - char pc = zero ? '0' : ' '; + char *dest = *pdest; + char tmp[21]; /* enough for 64 bit ints */ + char *np = tmp + sizeof(tmp); + int rw,pad,trail; + char pc = zero ? '0' : ' '; *--np = '\0'; if (val == 0) *--np = '0'; else while (val != 0) { - int rem = (int)(val % base); + int rem = (int)(val % base); val = val / base; *--np = (char)(rem < 10 ? rem + '0' : rem - 10 + letter); @@ -282,15 +278,15 @@ static void myvsnprintf_uint_impl(char **pdest,char *de,int width,int zero, } static void myvsnprintf_uint(char **pdest,char *de,int width,int zero, - int neg,unsigned base,int letter, - ulonglong val) + int neg,unsigned base,int letter, + ulonglong val) { myvsnprintf_uint_impl(pdest,de,width,zero,neg,base,letter,0,val); } static void myvsnprintf_int(char **pdest,char *de,int width,int zero, - int neg,unsigned base,int letter, - longlong val) + int neg,unsigned base,int letter, + longlong val) { if (val < 0) myvsnprintf_uint_impl(pdest,de,width,zero,neg,base,letter,1,-val); @@ -300,8 +296,8 @@ static void myvsnprintf_int(char **pdest,char *de,int width,int zero, static void myvsnprintf(char *dest,unsigned dsize,const char *fmt,va_list ap) { // s,d,x,u,ll - char *de = dest + dsize - 1; - int state = 0, width, zero, neg, ll; + char *de = dest + dsize - 1; + int state = 0, width, zero, neg, ll; if (dsize <= 1) { if (dsize > 0) @@ -312,102 +308,102 @@ static void myvsnprintf(char *dest,unsigned dsize,const char *fmt,va_list ap) while (*fmt && dest < de) switch (state) { case 0: - if (*fmt == '%') { - ++fmt; - state = 1; - width = zero = neg = ll = 0; - } else - *dest++ = *fmt++; - break; + if (*fmt == '%') { + ++fmt; + state = 1; + width = zero = neg = ll = 0; + } else + *dest++ = *fmt++; + break; case 1: - if (*fmt == '-') { - neg = 1; - ++fmt; - state = 2; - break; - } - if (*fmt == '0') - zero = 1; - state = 2; + if (*fmt == '-') { + neg = 1; + ++fmt; + state = 2; + break; + } + if (*fmt == '0') + zero = 1; + state = 2; case 2: - if (*fmt >= '0' && *fmt <= '9') { - width = width * 10 + *fmt++ - '0'; - break; - } - state = 3; + if (*fmt >= '0' && *fmt <= '9') { + width = width * 10 + *fmt++ - '0'; + break; + } + state = 3; case 3: - if (*fmt == 'l') { - ++ll; - ++fmt; - break; - } - state = 4; + if (*fmt == 'l') { + ++ll; + ++fmt; + break; + } + state = 4; case 4: - switch (*fmt) { - case 's': - myvsnprintf_string(&dest,de,va_arg(ap,const char *)); - break; - case 'd': - switch (ll) { - case 0: - myvsnprintf_int(&dest,de,width,zero,neg,10,'a',va_arg(ap,int)); - break; - case 1: - myvsnprintf_int(&dest,de,width,zero,neg,10,'a',va_arg(ap,long)); - break; - case 2: - myvsnprintf_int(&dest,de,width,zero,neg,10,'a',va_arg(ap,longlong)); - break; - } - break; - case 'u': - switch (ll) { - case 0: - myvsnprintf_uint(&dest,de,width,zero,neg,10,'a',va_arg(ap,unsigned int)); - break; - case 1: - myvsnprintf_uint(&dest,de,width,zero,neg,10,'a',va_arg(ap,unsigned long)); - break; - case 2: - myvsnprintf_uint(&dest,de,width,zero,neg,10,'a',va_arg(ap,ulonglong)); - break; - } - break; - case 'x': - switch (ll) { - case 0: - myvsnprintf_uint(&dest,de,width,zero,neg,16,'a',va_arg(ap,unsigned int)); - break; - case 1: - myvsnprintf_uint(&dest,de,width,zero,neg,16,'a',va_arg(ap,unsigned long)); - break; - case 2: - myvsnprintf_uint(&dest,de,width,zero,neg,16,'a',va_arg(ap,ulonglong)); - break; - } - break; - case 'X': - switch (ll) { - case 0: - myvsnprintf_uint(&dest,de,width,zero,neg,16,'A',va_arg(ap,unsigned int)); - break; - case 1: - myvsnprintf_uint(&dest,de,width,zero,neg,16,'A',va_arg(ap,unsigned long)); - break; - case 2: - myvsnprintf_uint(&dest,de,width,zero,neg,16,'A',va_arg(ap,ulonglong)); - break; - } - break; - default: - break; - } - ++fmt; - state = 0; - break; + switch (*fmt) { + case 's': + myvsnprintf_string(&dest,de,va_arg(ap,const char *)); + break; + case 'd': + switch (ll) { + case 0: + myvsnprintf_int(&dest,de,width,zero,neg,10,'a',va_arg(ap,int)); + break; + case 1: + myvsnprintf_int(&dest,de,width,zero,neg,10,'a',va_arg(ap,long)); + break; + case 2: + myvsnprintf_int(&dest,de,width,zero,neg,10,'a',va_arg(ap,longlong)); + break; + } + break; + case 'u': + switch (ll) { + case 0: + myvsnprintf_uint(&dest,de,width,zero,neg,10,'a',va_arg(ap,unsigned int)); + break; + case 1: + myvsnprintf_uint(&dest,de,width,zero,neg,10,'a',va_arg(ap,unsigned long)); + break; + case 2: + myvsnprintf_uint(&dest,de,width,zero,neg,10,'a',va_arg(ap,ulonglong)); + break; + } + break; + case 'x': + switch (ll) { + case 0: + myvsnprintf_uint(&dest,de,width,zero,neg,16,'a',va_arg(ap,unsigned int)); + break; + case 1: + myvsnprintf_uint(&dest,de,width,zero,neg,16,'a',va_arg(ap,unsigned long)); + break; + case 2: + myvsnprintf_uint(&dest,de,width,zero,neg,16,'a',va_arg(ap,ulonglong)); + break; + } + break; + case 'X': + switch (ll) { + case 0: + myvsnprintf_uint(&dest,de,width,zero,neg,16,'A',va_arg(ap,unsigned int)); + break; + case 1: + myvsnprintf_uint(&dest,de,width,zero,neg,16,'A',va_arg(ap,unsigned long)); + break; + case 2: + myvsnprintf_uint(&dest,de,width,zero,neg,16,'A',va_arg(ap,ulonglong)); + break; + } + break; + default: + break; + } + ++fmt; + state = 0; + break; default: - state = 0; - break; + state = 0; + break; } *dest = '\0'; } @@ -427,7 +423,7 @@ static void errorjmp(MatroskaFile *mf,const char *fmt, ...) { /////////////////////////////////////////////////////////////////////////// // arrays static void *ArrayAlloc(MatroskaFile *mf,void **base, - unsigned *cur,unsigned *max,unsigned elem_size) + unsigned *cur,unsigned *max,unsigned elem_size) { if (*cur>=*max) { void *np; @@ -447,7 +443,7 @@ static void *ArrayAlloc(MatroskaFile *mf,void **base, } static void ArrayReleaseMemory(MatroskaFile *mf,void **base, - unsigned cur,unsigned *max,unsigned elem_size) + unsigned cur,unsigned *max,unsigned elem_size) { if (cur<*max) { void *np = mf->cache->memrealloc(mf->cache,*base,cur*elem_size); @@ -457,9 +453,9 @@ static void ArrayReleaseMemory(MatroskaFile *mf,void **base, } -#define ASGET(f,s,name) ArrayAlloc((f),(void**)&(s)->name,&(s)->n##name,&(s)->n##name##Size,sizeof(*((s)->name))) -#define AGET(f,name) ArrayAlloc((f),(void**)&(f)->name,&(f)->n##name,&(f)->n##name##Size,sizeof(*((f)->name))) -#define ARELEASE(f,s,name) ArrayReleaseMemory((f),(void**)&(s)->name,(s)->n##name,&(s)->n##name##Size,sizeof(*((s)->name))) +#define ASGET(f,s,name) ArrayAlloc((f),(void**)&(s)->name,&(s)->n##name,&(s)->n##name##Size,sizeof(*((s)->name))) +#define AGET(f,name) ArrayAlloc((f),(void**)&(f)->name,&(f)->n##name,&(f)->n##name##Size,sizeof(*((f)->name))) +#define ARELEASE(f,s,name) ArrayReleaseMemory((f),(void**)&(s)->name,(s)->n##name,&(s)->n##name##Size,sizeof(*((s)->name))) /////////////////////////////////////////////////////////////////////////// // queues @@ -484,10 +480,36 @@ static struct QueueEntry *QGet(struct Queue *q) { return qe; } +// allocate and initialize an array of Queues, one for each track +static struct Queue* QsStructAlloc(MatroskaFile *mf) { + struct Queue *q = mf->cache->memalloc(mf->cache, mf->nTracks * sizeof(struct Queue)); + if (q == NULL) + errorjmp(mf, "Ouf of memory"); + memset(q, 0, mf->nTracks * sizeof(struct Queue)); + + return q; +} + +// dump the contents of src into the head of each dest queue such that the +// old tail of src[i] points to the old head of dest[i], the new head of dest[i] +// is the old head of src[i], and the src queues are now empty. +static void QsDumpHead(struct Queue *destination, struct Queue *source, int n) { + for (int i = 0; i < n; ++i) { + struct Queue *dest = &destination[i]; + struct Queue *src = &source[i]; + if (!src->tail) // do nothing if src queue empty + continue; + src->tail->next = dest->head; // link up queues + dest->head = src->head; // set heads and tails properly + src->head = NULL; + src->tail = NULL; + } +} + static struct QueueEntry *QAlloc(MatroskaFile *mf) { struct QueueEntry *qe,**qep; if (mf->QFreeList == NULL) { - unsigned i; + unsigned i; qep = AGET(mf,QBlocks); @@ -496,10 +518,12 @@ static struct QueueEntry *QAlloc(MatroskaFile *mf) { errorjmp(mf,"Ouf of memory"); qe = *qep; - - for (i=0;iQFreeList = qe; } @@ -511,13 +535,24 @@ static struct QueueEntry *QAlloc(MatroskaFile *mf) { } static inline void QFree(MatroskaFile *mf,struct QueueEntry *qe) { + mf->cache->memfree(mf->cache, qe->Data); + qe->Data = NULL; qe->next = mf->QFreeList; mf->QFreeList = qe; } +// deallocatee an array of Queues, one for each track +static void QsStructFree(MatroskaFile *mf, struct Queue *q) { + for (int i = 0; i < mf->nTracks; ++i) { + while (q[i].head) + QFree(mf, QGet(&q[i])); + } + mf->cache->memfree(mf->cache, q); +} + // fill the buffer at current position static void fillbuf(MatroskaFile *mf) { - int rd; + int rd; // advance buffer pointers mf->bufbase += mf->buflen; @@ -545,13 +580,13 @@ static inline int readch(MatroskaFile *mf) { return mf->bufpos < mf->buflen ? (unsigned char)(mf->inbuf[mf->bufpos++]) : nextbuf(mf); } -static inline ulonglong filepos(MatroskaFile *mf) { +static inline ulonglong filepos(MatroskaFile *mf) { return mf->bufbase + mf->bufpos; } static void readbytes(MatroskaFile *mf,void *buffer,int len) { - char *cp = buffer; - int nb = mf->buflen - mf->bufpos; + char *cp = buffer; + int nb = mf->buflen - mf->bufpos; if (nb > len) nb = len; @@ -575,7 +610,7 @@ static void readbytes(MatroskaFile *mf,void *buffer,int len) { } static void skipbytes(MatroskaFile *mf,ulonglong len) { - int nb = mf->buflen - mf->bufpos; + int nb = mf->buflen - mf->bufpos; if (nb > len) nb = (int)len; @@ -604,7 +639,7 @@ static void seek(MatroskaFile *mf,ulonglong pos) { /////////////////////////////////////////////////////////////////////////// // floating point -static inline MKFLOAT mkfi(int i) { +static inline MKFLOAT mkfi(int i) { #ifdef MATROSKA_INTEGER_ONLY MKFLOAT f; f.v = (longlong)i << 32; @@ -629,7 +664,7 @@ static inline longlong mul3(MKFLOAT scale,longlong tc) { // r = ((x0*y0) >> 32) + (x1*y0) + (x0*y1) + ((x1*y1) << 32) unsigned x0,x1,y0,y1; ulonglong p; - char sign = 0; + char sign = 0; if (scale.v < 0) sign = !sign, scale.v = -scale.v; @@ -655,7 +690,7 @@ static inline longlong mul3(MKFLOAT scale,longlong tc) { /////////////////////////////////////////////////////////////////////////// // EBML support static int readID(MatroskaFile *mf) { - int c1,c2,c3,c4; + int c1,c2,c3,c4; c1 = readch(mf); if (c1 == EOF) @@ -693,8 +728,8 @@ fail: } static ulonglong readVLUIntImp(MatroskaFile *mf,int *mask) { - int c,d,m; - ulonglong v = 0; + int c,d,m; + ulonglong v = 0; c = readch(mf); if (c == EOF) @@ -707,7 +742,7 @@ static ulonglong readVLUIntImp(MatroskaFile *mf,int *mask) { if (c & (0x80 >> m)) { c &= 0x7f >> m; if (mask) - *mask = m; + *mask = m; return v | ((ulonglong)c << m*8); } d = readch(mf); @@ -718,12 +753,12 @@ static ulonglong readVLUIntImp(MatroskaFile *mf,int *mask) { // NOT REACHED } -static inline ulonglong readVLUInt(MatroskaFile *mf) { +static inline ulonglong readVLUInt(MatroskaFile *mf) { return readVLUIntImp(mf,NULL); } -static ulonglong readSizeUnspec(MatroskaFile *mf) { - int m; +static ulonglong readSizeUnspec(MatroskaFile *mf) { + int m = 0; ulonglong v = readVLUIntImp(mf,&m); // see if it's unspecified @@ -733,7 +768,7 @@ static ulonglong readSizeUnspec(MatroskaFile *mf) { return v; } -static ulonglong readSize(MatroskaFile *mf) { +static ulonglong readSize(MatroskaFile *mf) { ulonglong v = readSizeUnspec(mf); // see if it's unspecified @@ -743,20 +778,20 @@ static ulonglong readSize(MatroskaFile *mf) { return v; } -static inline longlong readVLSInt(MatroskaFile *mf) { +static inline longlong readVLSInt(MatroskaFile *mf) { static longlong bias[8] = { (ONE<<6)-1, (ONE<<13)-1, (ONE<<20)-1, (ONE<<27)-1, - (ONE<<34)-1, (ONE<<41)-1, (ONE<<48)-1, (ONE<<55)-1 }; + (ONE<<34)-1, (ONE<<41)-1, (ONE<<48)-1, (ONE<<55)-1 }; - int m; + int m; longlong v = readVLUIntImp(mf,&m); return v - bias[m]; } static ulonglong readUInt(MatroskaFile *mf,unsigned int len) { - int c; - unsigned int m = len; - ulonglong v = 0; + int c; + unsigned int m = len; + ulonglong v = 0; if (len==0) return v; @@ -773,22 +808,22 @@ static ulonglong readUInt(MatroskaFile *mf,unsigned int len) { return v; } -static inline longlong readSInt(MatroskaFile *mf,unsigned int len) { - longlong v = readUInt(mf,(unsigned)len); - int s = 64 - (len<<3); - return ((ulonglong)v << s) >> s; +static inline longlong readSInt(MatroskaFile *mf,unsigned int len) { + longlong v = readUInt(mf,(unsigned)len); + int s = 64 - (len<<3); + return (v << s) >> s; } static MKFLOAT readFloat(MatroskaFile *mf,unsigned int len) { #ifdef MATROSKA_INTEGER_ONLY - MKFLOAT f; - int shift; + MKFLOAT f; + int shift; #else union { unsigned int ui; - ulonglong ull; - float f; - double d; + ulonglong ull; + float f; + double d; } u; #endif @@ -808,18 +843,18 @@ zero: else if (shift == 255) inf: if (ui & 0x80000000) - f.v = LL(0x8000000000000000); + f.v = LL(0x8000000000000000); else - f.v = LL(0x7fffffffffffffff); + f.v = LL(0x7fffffffffffffff); else { shift += -127 + 9; if (shift > 39) - goto inf; + goto inf; shift: if (shift < 0) - f.v = f.v >> -shift; + f.v = f.v >> -shift; else if (shift > 0) - f.v = f.v << shift; + f.v = f.v << shift; } } else if (len == 8) { ulonglong ui = readUInt(mf,(unsigned)len); @@ -834,7 +869,7 @@ shift: else { shift += -1023 - 20; if (shift > 10) - goto inf; + goto inf; goto shift; } } @@ -856,7 +891,7 @@ shift: } static void readString(MatroskaFile *mf,ulonglong len,char *buffer,int buflen) { - int nread; + int nread; if (buflen<1) errorjmp(mf,"Invalid buffer size in readString: %d",buflen); @@ -885,41 +920,41 @@ static void readLangCC(MatroskaFile *mf, ulonglong len, char lcc[4]) { /////////////////////////////////////////////////////////////////////////// // file parser -#define FOREACH2(f,tl,clid) \ +#define FOREACH2(f,tl,clid) \ { \ - ulonglong tmplen = (tl); \ + ulonglong tmplen = (tl); \ { \ ulonglong start = filepos(f); \ ulonglong cur,len; \ - int id; \ + int id; \ for (;;) { \ - cur = filepos(mf); \ - if (tmplen != MAXU64 && cur == start + tmplen) \ - break; \ - id = readID(f); \ - if (id==EOF) \ - errorjmp(mf,"Unexpected EOF while reading EBML container"); \ + cur = filepos(mf); \ + if (tmplen != MAXU64 && cur == start + tmplen) \ + break; \ + id = readID(f); \ + if (id==EOF) \ + errorjmp(mf,"Unexpected EOF while reading EBML container"); \ len = id == clid ? readSizeUnspec(mf) : readSize(mf); \ - switch (id) { + switch (id) { #define FOREACH(f,tl) FOREACH2(f,tl,EOF) #define RESTART() (tmplen=len),(start=cur) -#define ENDFOR1(f) \ - default: \ - skipbytes(f,len); \ - break; \ - } -#define ENDFOR2() \ +#define ENDFOR1(f) \ + default: \ + skipbytes(f,len); \ + break; \ + } +#define ENDFOR2() \ } \ } \ } -#define ENDFOR(f) ENDFOR1(f) ENDFOR2() +#define ENDFOR(f) ENDFOR1(f) ENDFOR2() -#define myalloca(f,c) alloca(c) -#define STRGETF(f,v,len,func) \ +#define myalloca(f,c) alloca(c) +#define STRGETF(f,v,len,func) \ { \ char *TmpVal; \ unsigned TmpLen = (len)>MAX_STRING_LEN ? MAX_STRING_LEN : (unsigned)(len); \ @@ -930,12 +965,24 @@ static void readLangCC(MatroskaFile *mf, ulonglong len, char lcc[4]) { (v) = TmpVal; \ } -#define STRGETA(f,v,len) STRGETF(f,v,len,myalloca) -#define STRGETM(f,v,len) STRGETF(f,v,len,f->cache->memalloc) +#define STRGETA(f,v,len) STRGETF(f,v,len,myalloca) +#define STRGETM(f,v,len) STRGETF(f,v,len,f->cache->memalloc) + +#if 0 +static int IsWritingApp(MatroskaFile *mf,const char *str) { + const char *cp = mf->Seg.WritingApp; + if (!cp) + return 0; + + while (*str && *str++==*cp++) ; + + return !*str; +} +#endif static void parseEBML(MatroskaFile *mf,ulonglong toplen) { ulonglong v; - char buf[32]; + char buf[32]; FOREACH(mf,toplen) case 0x4286: // Version @@ -944,22 +991,22 @@ static void parseEBML(MatroskaFile *mf,ulonglong toplen) { case 0x42f7: // ReadVersion v = readUInt(mf,(unsigned)len); if (v > EBML_VERSION) - errorjmp(mf,"File requires version %d EBML parser",(int)v); + errorjmp(mf,"File requires version %d EBML parser",(int)v); break; case 0x42f2: // MaxIDLength v = readUInt(mf,(unsigned)len); if (v > EBML_MAX_ID_LENGTH) - errorjmp(mf,"File has identifiers longer than %d",(int)v); + errorjmp(mf,"File has identifiers longer than %d",(int)v); break; case 0x42f3: // MaxSizeLength v = readUInt(mf,(unsigned)len); if (v > EBML_MAX_SIZE_LENGTH) - errorjmp(mf,"File has integers longer than %d",(int)v); + errorjmp(mf,"File has integers longer than %d",(int)v); break; case 0x4282: // DocType readString(mf,len,buf,sizeof(buf)); if (strcmp(buf,MATROSKA_DOCTYPE) != 0 && strcmp(buf,WEBM_DOCTYPE) != 0) - errorjmp(mf,"Unsupported DocType: %s",buf); + errorjmp(mf,"Unsupported DocType: %s",buf); break; case 0x4287: // DocTypeVersion v = readUInt(mf,(unsigned)len); @@ -967,19 +1014,19 @@ static void parseEBML(MatroskaFile *mf,ulonglong toplen) { case 0x4285: // DocTypeReadVersion v = readUInt(mf,(unsigned)len); if (v > MATROSKA_VERSION) - errorjmp(mf,"File requires version %d Matroska parser",(int)v); + errorjmp(mf,"File requires version %d Matroska parser",(int)v); break; ENDFOR(mf); } static void parseSeekEntry(MatroskaFile *mf,ulonglong toplen) { - int seekid = 0; + int seekid = 0; ulonglong pos = (ulonglong)-1; FOREACH(mf,toplen) case 0x53ab: // SeekID if (len>EBML_MAX_ID_LENGTH) - errorjmp(mf,"Invalid ID size in parseSeekEntry: %d\n",(int)len); + errorjmp(mf,"Invalid ID size in parseSeekEntry: %d\n",(int)len); seekid = (int)readUInt(mf,(unsigned)len); break; case 0x53ac: // SeekPos @@ -994,7 +1041,7 @@ static void parseSeekEntry(MatroskaFile *mf,ulonglong toplen) { switch (seekid) { case 0x114d9b74: // next SeekHead if (mf->pSeekHead) - errorjmp(mf,"SeekHead contains more than one SeekHead pointer"); + errorjmp(mf,"SeekHead contains more than one SeekHead pointer"); mf->pSeekHead = pos; break; case 0x1549a966: // SegmentInfo @@ -1002,7 +1049,7 @@ static void parseSeekEntry(MatroskaFile *mf,ulonglong toplen) { break; case 0x1f43b675: // Cluster if (!mf->pCluster) - mf->pCluster = pos; + mf->pCluster = pos; break; case 0x1654ae6b: // Tracks mf->pTracks = pos; @@ -1044,7 +1091,7 @@ static void parseSegmentInfo(MatroskaFile *mf,ulonglong toplen) { FOREACH(mf,toplen) case 0x73a4: // SegmentUID if (len!=sizeof(mf->Seg.UID)) - errorjmp(mf,"SegmentUID size is not %d bytes",mf->Seg.UID); + errorjmp(mf,"SegmentUID size is not %d bytes",mf->Seg.UID); readbytes(mf,mf->Seg.UID,sizeof(mf->Seg.UID)); break; case 0x7384: // SegmentFilename @@ -1052,7 +1099,7 @@ static void parseSegmentInfo(MatroskaFile *mf,ulonglong toplen) { break; case 0x3cb923: // PrevUID if (len!=sizeof(mf->Seg.PrevUID)) - errorjmp(mf,"PrevUID size is not %d bytes",mf->Seg.PrevUID); + errorjmp(mf,"PrevUID size is not %d bytes",mf->Seg.PrevUID); readbytes(mf,mf->Seg.PrevUID,sizeof(mf->Seg.PrevUID)); break; case 0x3c83ab: // PrevFilename @@ -1060,7 +1107,7 @@ static void parseSegmentInfo(MatroskaFile *mf,ulonglong toplen) { break; case 0x3eb923: // NextUID if (len!=sizeof(mf->Seg.NextUID)) - errorjmp(mf,"NextUID size is not %d bytes",mf->Seg.NextUID); + errorjmp(mf,"NextUID size is not %d bytes",mf->Seg.NextUID); readbytes(mf,mf->Seg.NextUID,sizeof(mf->Seg.NextUID)); break; case 0x3e83bb: // NextFilename @@ -1069,7 +1116,7 @@ static void parseSegmentInfo(MatroskaFile *mf,ulonglong toplen) { case 0x2ad7b1: // TimecodeScale mf->Seg.TimecodeScale = readUInt(mf,(unsigned)len); if (mf->Seg.TimecodeScale == 0) - errorjmp(mf,"Segment timecode scale is zero"); + errorjmp(mf,"Segment timecode scale is zero"); break; case 0x4489: // Duration duration = readFloat(mf,(unsigned)len); @@ -1105,9 +1152,7 @@ static void parseFirstCluster(MatroskaFile *mf,ulonglong toplen) { tc = readUInt(mf,(unsigned)len); if (!seenTimecode) { seenTimecode = 1; - // Commented out, MP42Foundation wants the real timecode, - // not timecode starting at 0. - //mf->firstTimecode += tc; + mf->firstTimecode += tc; } if (seenBlock) { @@ -1132,9 +1177,9 @@ out: break; case 0xa0: // BlockGroup FOREACH(mf,len) - case 0xa1: // Block - readVLUInt(mf); // track number - tc = readSInt(mf,2); + case 0xa1: // Block + readVLUInt(mf); // track number + tc = readSInt(mf,2); if (!seenBlock) { seenBlock = 1; mf->firstTimecode += tc; @@ -1149,27 +1194,87 @@ out: ENDFOR(mf); } -static void parseColourInfo(MatroskaFile *mf,ulonglong toplen,struct TrackInfo *ti) { - - FOREACH(mf,toplen) - case 0x55b1: // MatrixCoefficients - ti->AV.Video.Colour.MatrixCoefficients = (unsigned)readUInt(mf,len); - break; - case 0x55b2: // BitsPerChannel - ti->AV.Video.Colour.BitsPerChannel = (unsigned)readUInt(mf,len); - break; - case 0x55ba: // TransferCharacteristics - ti->AV.Video.Colour.TransferCharacteristics = (unsigned)readUInt(mf,len); - break; - case 0x55bb: // Primaries - ti->AV.Video.Colour.Primaries = (unsigned)readUInt(mf,len); - break; - ENDFOR(mf); +static void parseVideoColourInfo(MatroskaFile *mf,ulonglong toplen,struct TrackInfo *ti) { + FOREACH(mf,toplen) + case 0x55b1: + ti->AV.Video.Colour.MatrixCoefficients = readUInt(mf,(unsigned)len); + break; + case 0x55b2: + ti->AV.Video.Colour.BitsPerChannel = readUInt(mf,(unsigned)len); + break; + case 0x55b3: + ti->AV.Video.Colour.ChromaSubsamplingHorz = readUInt(mf,(unsigned)len); + break; + case 0x55b4: + ti->AV.Video.Colour.ChromaSubsamplingVert = readUInt(mf,(unsigned)len); + break; + case 0x55b5: + ti->AV.Video.Colour.CbSubsamplingHorz = readUInt(mf,(unsigned)len); + break; + case 0x55b6: + ti->AV.Video.Colour.CbSubsamplingVert = readUInt(mf,(unsigned)len); + break; + case 0x55b7: + ti->AV.Video.Colour.ChromaSitingHorz = readUInt(mf,(unsigned)len); + break; + case 0x55b8: + ti->AV.Video.Colour.ChromaSitingVert = readUInt(mf,(unsigned)len); + break; + case 0x55b9: + ti->AV.Video.Colour.Range = readUInt(mf,(unsigned)len); + break; + case 0x55ba: + ti->AV.Video.Colour.TransferCharacteristics = readUInt(mf,(unsigned)len); + break; + case 0x55bb: + ti->AV.Video.Colour.Primaries = readUInt(mf,(unsigned)len); + break; + case 0x55bc: + ti->AV.Video.Colour.MaxCLL = readUInt(mf,(unsigned)len); + break; + case 0x55bd: + ti->AV.Video.Colour.MaxFALL = readUInt(mf,(unsigned)len); + break; + case 0x55d0: + FOREACH(mf,len) + case 0x55d1: + ti->AV.Video.Colour.MasteringMetadata.PrimaryRChromaticityX = readFloat(mf,(unsigned)len); + break; + case 0x55d2: + ti->AV.Video.Colour.MasteringMetadata.PrimaryRChromaticityY = readFloat(mf,(unsigned)len); + break; + case 0x55d3: + ti->AV.Video.Colour.MasteringMetadata.PrimaryGChromaticityX = readFloat(mf,(unsigned)len); + break; + case 0x55d4: + ti->AV.Video.Colour.MasteringMetadata.PrimaryGChromaticityY = readFloat(mf,(unsigned)len); + break; + case 0x55d5: + ti->AV.Video.Colour.MasteringMetadata.PrimaryBChromaticityX = readFloat(mf,(unsigned)len); + break; + case 0x55d6: + ti->AV.Video.Colour.MasteringMetadata.PrimaryBChromaticityY = readFloat(mf,(unsigned)len); + break; + case 0x55d7: + ti->AV.Video.Colour.MasteringMetadata.WhitePointChromaticityX = readFloat(mf,(unsigned)len); + break; + case 0x55d8: + ti->AV.Video.Colour.MasteringMetadata.WhitePointChromaticityY = readFloat(mf,(unsigned)len); + break; + case 0x55d9: + ti->AV.Video.Colour.MasteringMetadata.LuminanceMax = readFloat(mf,(unsigned)len); + break; + case 0x55da: + ti->AV.Video.Colour.MasteringMetadata.LuminanceMin = readFloat(mf,(unsigned)len); + break; + ENDFOR(mf); + break; + ENDFOR(mf); } static void parseVideoInfo(MatroskaFile *mf,ulonglong toplen,struct TrackInfo *ti) { ulonglong v; - char dW = 0, dH = 0; + char dW = 0, dH = 0; FOREACH(mf,toplen) case 0x9a: // FlagInterlaced @@ -1177,37 +1282,37 @@ static void parseVideoInfo(MatroskaFile *mf,ulonglong toplen,struct TrackInfo *t break; case 0x53b8: // StereoMode v = readUInt(mf,(unsigned)len); - if (v>3) - errorjmp(mf,"Invalid stereo mode"); + if (v>14) + errorjmp(mf,"Invalid stereo mode"); ti->AV.Video.StereoMode = (unsigned char)v; break; case 0xb0: // PixelWidth v = readUInt(mf,(unsigned)len); if (v>0xffffffff) - errorjmp(mf,"PixelWidth is too large"); + errorjmp(mf,"PixelWidth is too large"); ti->AV.Video.PixelWidth = (unsigned)v; if (!dW) - ti->AV.Video.DisplayWidth = ti->AV.Video.PixelWidth; + ti->AV.Video.DisplayWidth = ti->AV.Video.PixelWidth; break; case 0xba: // PixelHeight v = readUInt(mf,(unsigned)len); if (v>0xffffffff) - errorjmp(mf,"PixelHeight is too large"); + errorjmp(mf,"PixelHeight is too large"); ti->AV.Video.PixelHeight = (unsigned)v; if (!dH) - ti->AV.Video.DisplayHeight = ti->AV.Video.PixelHeight; + ti->AV.Video.DisplayHeight = ti->AV.Video.PixelHeight; break; case 0x54b0: // DisplayWidth v = readUInt(mf,(unsigned)len); if (v>0xffffffff) - errorjmp(mf,"DisplayWidth is too large"); + errorjmp(mf,"DisplayWidth is too large"); ti->AV.Video.DisplayWidth = (unsigned)v; dW = 1; break; case 0x54ba: // DisplayHeight v = readUInt(mf,(unsigned)len); if (v>0xffffffff) - errorjmp(mf,"DisplayHeight is too large"); + errorjmp(mf,"DisplayHeight is too large"); ti->AV.Video.DisplayHeight = (unsigned)v; dH = 1; break; @@ -1222,25 +1327,25 @@ static void parseVideoInfo(MatroskaFile *mf,ulonglong toplen,struct TrackInfo *t case 0x54aa: // PixelCropBottom v = readUInt(mf,(unsigned)len); if (v>0xffffffff) - errorjmp(mf,"PixelCropBottom is too large"); + errorjmp(mf,"PixelCropBottom is too large"); ti->AV.Video.CropB = (unsigned)v; break; case 0x54bb: // PixelCropTop v = readUInt(mf,(unsigned)len); if (v>0xffffffff) - errorjmp(mf,"PixelCropTop is too large"); + errorjmp(mf,"PixelCropTop is too large"); ti->AV.Video.CropT = (unsigned)v; break; case 0x54cc: // PixelCropLeft v = readUInt(mf,(unsigned)len); if (v>0xffffffff) - errorjmp(mf,"PixelCropLeft is too large"); + errorjmp(mf,"PixelCropLeft is too large"); ti->AV.Video.CropL = (unsigned)v; break; case 0x54dd: // PixelCropRight v = readUInt(mf,(unsigned)len); if (v>0xffffffff) - errorjmp(mf,"PixelCropRight is too large"); + errorjmp(mf,"PixelCropRight is too large"); ti->AV.Video.CropR = (unsigned)v; break; case 0x2eb524: // ColourSpace @@ -1250,9 +1355,17 @@ static void parseVideoInfo(MatroskaFile *mf,ulonglong toplen,struct TrackInfo *t ti->AV.Video.GammaValue = readFloat(mf,(unsigned)len); break; case 0x55b0: // Colour - parseColourInfo(mf,len,ti); + parseVideoColourInfo(mf,len,ti); break; ENDFOR(mf); + + // DisplayWidth/Height defaults don't apply for DisplayUnit != 0 + if (ti->AV.Video.DisplayUnit != 0) { + if (!dW) + ti->AV.Video.DisplayWidth = 0; + if (!dH) + ti->AV.Video.DisplayHeight = 0; + } } static void parseAudioInfo(MatroskaFile *mf,ulonglong toplen,struct TrackInfo *ti) { @@ -1268,7 +1381,7 @@ static void parseAudioInfo(MatroskaFile *mf,ulonglong toplen,struct TrackInfo *t case 0x9f: // Channels v = readUInt(mf,(unsigned)len); if (v<1 || v>255) - errorjmp(mf,"Invalid Channels value"); + errorjmp(mf,"Invalid Channels value"); ti->AV.Audio.Channels = (unsigned char)v; break; case 0x7d7b: // ChannelPositions @@ -1278,7 +1391,7 @@ static void parseAudioInfo(MatroskaFile *mf,ulonglong toplen,struct TrackInfo *t v = readUInt(mf,(unsigned)len); #if 0 if ((v<1 || v>255) && !IsWritingApp(mf,"AVI-Mux GUI")) - errorjmp(mf,"Invalid BitDepth: %d",(int)v); + errorjmp(mf,"Invalid BitDepth: %d",(int)v); #endif ti->AV.Audio.BitDepth = (unsigned char)v; break; @@ -1286,6 +1399,8 @@ static void parseAudioInfo(MatroskaFile *mf,ulonglong toplen,struct TrackInfo *t if (ti->AV.Audio.Channels == 0) ti->AV.Audio.Channels = 1; + if (mkv_TruncFloat(ti->AV.Audio.SamplingFreq) == 0) + ti->AV.Audio.SamplingFreq = mkfi(8000); if (mkv_TruncFloat(ti->AV.Audio.OutputSamplingFreq)==0) ti->AV.Audio.OutputSamplingFreq = ti->AV.Audio.SamplingFreq; } @@ -1304,13 +1419,16 @@ static void CopyStr(char **src,char **dst) { static void parseTrackEntry(MatroskaFile *mf,ulonglong toplen) { struct TrackInfo t,*tp,**tpp; - ulonglong v; - char *cp = NULL, *cs = NULL; - size_t cplen = 0, cslen = 0, cpadd = 0; - unsigned CompScope, num_comp = 0; + ulonglong v; + char *cp = NULL, *cs = NULL; + size_t cplen = 0, cslen = 0, cpadd = 0; + unsigned CompScope, num_comp = 0; if (mf->nTracks >= MAX_TRACKS) - errorjmp(mf,"Too many tracks."); + { + //errorjmp(mf,"Too many tracks."); + return; + } // clear track info memset(&t,0,sizeof(t)); @@ -1318,6 +1436,7 @@ static void parseTrackEntry(MatroskaFile *mf,ulonglong toplen) { // fill default values t.Enabled = 1; t.Default = 1; + t.Forced = 0; t.Lacing = 1; t.TimecodeScale = mkfi(1); t.DecodeAll = 1; @@ -1326,7 +1445,7 @@ static void parseTrackEntry(MatroskaFile *mf,ulonglong toplen) { case 0xd7: // TrackNumber v = readUInt(mf,(unsigned)len); if (v>255) - errorjmp(mf,"Track number is >255 (%d)",(int)v); + errorjmp(mf,"Track number is >255 (%d)",(int)v); t.Number = (unsigned char)v; break; case 0x73c5: // TrackUID @@ -1335,8 +1454,15 @@ static void parseTrackEntry(MatroskaFile *mf,ulonglong toplen) { case 0x83: // TrackType v = readUInt(mf,(unsigned)len); if (v<1 || v>254) - errorjmp(mf,"Invalid track type: %d",(int)v); + errorjmp(mf,"Invalid track type: %d",(int)v); t.Type = (unsigned char)v; + + // Load type-dependent defaults + if (t.Type == TT_VIDEO) { + t.AV.Video.Colour.MatrixCoefficients = 0; + t.AV.Video.Colour.TransferCharacteristics = 0; + t.AV.Video.Colour.Primaries = 0; + } break; case 0xb9: // Enabled t.Enabled = readUInt(mf,(unsigned)len)!=0; @@ -1344,19 +1470,22 @@ static void parseTrackEntry(MatroskaFile *mf,ulonglong toplen) { case 0x88: // Default t.Default = readUInt(mf,(unsigned)len)!=0; break; + case 0x55aa: // Forced + t.Forced = readUInt(mf,(unsigned)len)!=0; + break; case 0x9c: // Lacing t.Lacing = readUInt(mf,(unsigned)len)!=0; break; case 0x6de7: // MinCache v = readUInt(mf,(unsigned)len); if (v > 0xffffffff) - errorjmp(mf,"MinCache is too large"); + errorjmp(mf,"MinCache is too large"); t.MinCache = (unsigned)v; break; case 0x6df8: // MaxCache v = readUInt(mf,(unsigned)len); if (v > 0xffffffff) - errorjmp(mf,"MaxCache is too large"); + errorjmp(mf,"MaxCache is too large"); t.MaxCache = (unsigned)v; break; case 0x23e383: // DefaultDuration @@ -1370,24 +1499,22 @@ static void parseTrackEntry(MatroskaFile *mf,ulonglong toplen) { break; case 0x536e: // Name if (t.Name) - errorjmp(mf,"Duplicate Track Name"); + errorjmp(mf,"Duplicate Track Name"); STRGETA(mf,t.Name,len); break; case 0x22b59c: // Language readLangCC(mf, len, t.Language); break; case 0x86: // CodecID - if (t.CodecID) - errorjmp(mf,"Duplicate CodecID"); STRGETA(mf,t.CodecID,len); break; case 0x63a2: // CodecPrivate if (cp) - errorjmp(mf,"Duplicate CodecPrivate"); - if (len>2097152) // 2MB - errorjmp(mf,"CodecPrivate is too large: %d",(int)len); + errorjmp(mf,"Duplicate CodecPrivate"); + if (len>33554432) // 32MB + errorjmp(mf,"CodecPrivate is too large: %d",(int)len); cplen = (unsigned)len; - cp = alloca(cplen); + mf->cpbuf = cp = mf->cache->memrealloc(mf->cache, mf->cpbuf, cplen); readbytes(mf,cp,(int)cplen); break; case 0x258688: // CodecName @@ -1408,11 +1535,14 @@ static void parseTrackEntry(MatroskaFile *mf,ulonglong toplen) { case 0x6fab: // TrackOverlay v = readUInt(mf,(unsigned)len); if (v>255) - errorjmp(mf,"Track number in TrackOverlay is too large: %d",(int)v); + errorjmp(mf,"Track number in TrackOverlay is too large: %d",(int)v); t.TrackOverlay = (unsigned char)v; break; case 0x56aa: // CodecDelay - t.CodecDelay = readUInt(mf,(unsigned)len);; + t.CodecDelay = readUInt(mf, (unsigned)len); + break; + case 0x56bb: // SeekPreRoll + t.SeekPreRoll = readUInt(mf, (unsigned)len); break; case 0xe0: // VideoInfo parseVideoInfo(mf,len,&t); @@ -1422,55 +1552,52 @@ static void parseTrackEntry(MatroskaFile *mf,ulonglong toplen) { break; case 0x6d80: // ContentEncodings FOREACH(mf,len) - case 0x6240: // ContentEncoding + case 0x6240: // ContentEncoding // fill in defaults - t.CompEnabled = 1; - t.CompMethod = COMP_ZLIB; - CompScope = 1; - if (++num_comp > 1) - return; // only one compression layer supported - FOREACH(mf,len) - case 0x5031: // ContentEncodingOrder - readUInt(mf,(unsigned)len); - break; - case 0x5032: // ContentEncodingScope - CompScope = (unsigned)readUInt(mf,(unsigned)len); - break; - case 0x5033: // ContentEncodingType - if (readUInt(mf,(unsigned)len) != 0) - return; // encryption is not supported - break; - case 0x5034: // ContentCompression - FOREACH(mf,len) - case 0x4254: // ContentCompAlgo - v = readUInt(mf,(unsigned)len); - t.CompEnabled = 1; - switch (v) { - case 0: // Zlib - t.CompMethod = COMP_ZLIB; - break; - case 1: // BZlib - t.CompMethod = COMP_BZIP; - break; - case 3: // prepend fixed data - t.CompMethod = COMP_PREPEND; - break; - default: - return; // unsupported compression, skip track - } - break; - case 0x4255: // ContentCompSettings - if (len > 256) - return; - cslen = (unsigned)len; - cs = alloca(cslen); - readbytes(mf, cs, (int)cslen); - break; - ENDFOR(mf); - break; - // TODO Implement Encryption/Signatures - ENDFOR(mf); - break; + t.CompEnabled = 1; + t.CompMethod = COMP_ZLIB; + CompScope = 1; + if (++num_comp > 1) + return; // only one compression layer supported + FOREACH(mf,len) + case 0x5031: // ContentEncodingOrder + readUInt(mf,(unsigned)len); + break; + case 0x5032: // ContentEncodingScope + CompScope = (unsigned)readUInt(mf,(unsigned)len); + break; + case 0x5033: // ContentEncodingType + if (readUInt(mf,(unsigned)len) != 0) + return; // encryption is not supported + break; + case 0x5034: // ContentCompression + FOREACH(mf,len) + case 0x4254: // ContentCompAlgo + v = readUInt(mf,(unsigned)len); + t.CompEnabled = 1; + switch (v) { + case 0: // Zlib + t.CompMethod = COMP_ZLIB; + break; + case 3: // prepend fixed data + t.CompMethod = COMP_PREPEND; + break; + default: + return; // unsupported compression, skip track + } + break; + case 0x4255: // ContentCompSettings + if (len > 256) + return; + cslen = (unsigned)len; + cs = alloca(cslen); + readbytes(mf, cs, (int)cslen); + break; + ENDFOR(mf); + break; + // TODO Implement Encryption/Signatures + ENDFOR(mf); + break; ENDFOR(mf); break; ENDFOR(mf); @@ -1483,59 +1610,78 @@ static void parseTrackEntry(MatroskaFile *mf,ulonglong toplen) { unsigned i; for (i = 0; i < mf->nTracks; ++i) if (mf->Tracks[i]->UID == t.UID) // duplicate track entry - return; + return; } -#ifdef MATROSKA_COMPRESSION_SUPPORT // handle compressed CodecPrivate - if (t.CompEnabled && t.CompMethod == COMP_ZLIB && (CompScope & 2) && cplen > 0) { - z_stream zs; - Bytef tmp[64], *ncp; - int code; - uLong ncplen; + // header removal compression + if (t.CompEnabled && (CompScope & 2)) { + if (t.CompMethod == COMP_PREPEND && cslen > 0) { + mf->cpbuf = cp = mf->cache->memrealloc(mf->cache, mf->cpbuf, cplen + cslen); + memmove(cp+cslen, cp, cplen); + memcpy(cp, cs, cslen); + cplen += cslen; + } +#ifdef MATROSKA_COMPRESSION_SUPPORT + // zlib compression + else if (t.CompMethod == COMP_ZLIB && cplen > 0) { + z_stream zs; + Bytef tmp[64], *ncp; + int code; + uLong ncplen; - memset(&zs,0,sizeof(zs)); - if (inflateInit(&zs) != Z_OK) - errorjmp(mf, "inflateInit failed"); + memset(&zs,0,sizeof(zs)); + if (inflateInit(&zs) != Z_OK) + errorjmp(mf, "inflateInit failed"); - zs.next_in = (Bytef *)cp; - zs.avail_in = (uInt)cplen; + zs.next_in = (Bytef *)cp; + zs.avail_in = (uInt)cplen; - do { - zs.next_out = tmp; - zs.avail_out = sizeof(tmp); + do { + zs.next_out = tmp; + zs.avail_out = sizeof(tmp); - code = inflate(&zs, Z_NO_FLUSH); - } while (code == Z_OK); + code = inflate(&zs, Z_NO_FLUSH); + } while (code == Z_OK); - if (code != Z_STREAM_END) - errorjmp(mf, "invalid compressed data in CodecPrivate"); + if (code != Z_STREAM_END) + errorjmp(mf, "invalid compressed data in CodecPrivate"); - ncplen = zs.total_out; - ncp = alloca(ncplen); + ncplen = zs.total_out; + ncp = mf->cache->memalloc(mf->cache, ncplen); - inflateReset(&zs); + inflateReset(&zs); - zs.next_in = (Bytef *)cp; - zs.avail_in = (uInt)cplen; - zs.next_out = ncp; - zs.avail_out = ncplen; + zs.next_in = (Bytef *)cp; + zs.avail_in = (uInt)cplen; + zs.next_out = ncp; + zs.avail_out = ncplen; - if (inflate(&zs, Z_FINISH) != Z_STREAM_END) - errorjmp(mf, "inflate failed"); + if (inflate(&zs, Z_FINISH) != Z_STREAM_END) { + mf->cache->memfree(mf->cache, ncp); + errorjmp(mf, "inflate failed"); + } - inflateEnd(&zs); + inflateEnd(&zs); - cp = (char *)ncp; - cplen = ncplen; - } + mf->cache->memfree(mf->cache, cp); + mf->cpbuf = cp = (char *)ncp; + cplen = ncplen; + } #endif + } if (t.CompEnabled && !(CompScope & 1)) { t.CompEnabled = 0; cslen = 0; } + // work-around some broken files + if (t.Type == TT_AUDIO && strcmp(t.CodecID, "A_TRUEHD")) + t.NeedKeyframes = 1; + else if (!strcmp(t.CodecID, "V_MJPEG")) + t.NeedKeyframes = 1; + // allocate new track tpp = AGET(mf,Tracks); @@ -1554,6 +1700,8 @@ static void parseTrackEntry(MatroskaFile *mf,ulonglong toplen) { tp->CodecPrivate = tp+1; tp->CodecPrivateSize = (unsigned)cplen; memcpy(tp->CodecPrivate,cp,cplen); + mf->cache->memfree(mf->cache, mf->cpbuf); + mf->cpbuf = cp = NULL; } if (cslen) { tp->CompMethodPrivate = (char *)(tp+1) + cplen; @@ -1584,7 +1732,9 @@ static void parseTracks(MatroskaFile *mf,ulonglong toplen) { static void addCue(MatroskaFile *mf,ulonglong pos,ulonglong timecode) { struct Cue *cc = AGET(mf,Cues); cc->Time = timecode; + cc->Duration = 0; cc->Position = pos; + cc->RelativePosition = 0; cc->Track = 0; cc->Block = 0; } @@ -1593,22 +1743,36 @@ static void fixupCues(MatroskaFile *mf) { // adjust cues, shift cues if file does not start at 0 unsigned i; longlong adjust = mf->firstTimecode * mf->Seg.TimecodeScale; + unsigned char nBestType = -1; + for (i=0;inCues;++i) { mf->Cues[i].Time *= mf->Seg.TimecodeScale; mf->Cues[i].Time -= adjust; + mf->Cues[i].Duration *= mf->Seg.TimecodeScale; + + + for (int n = 0; n < mf->nTracks; ++n) { + if (mf->Tracks[n]->Number == mf->Cues[i].Track) + nBestType = mf->Tracks[n]->Type; + } } + + mf->CueBestType = nBestType; } static void parseCues(MatroskaFile *mf,ulonglong toplen) { jmp_buf jb; ulonglong v; struct Cue cc; - unsigned i,j,k; + unsigned i,j,k,startCue; mf->seen.Cues = 1; mf->nCues = 0; cc.Block = 0; + cc.Duration = 0; + cc.RelativePosition = 0; + cc.Track = 0; memcpy(&jb,&mf->jb,sizeof(jb)); @@ -1621,51 +1785,74 @@ static void parseCues(MatroskaFile *mf,ulonglong toplen) { FOREACH(mf,toplen) case 0xbb: // CuePoint + startCue = mf->nCues; FOREACH(mf,len) - case 0xb3: // CueTime - cc.Time = readUInt(mf,(unsigned)len); - break; - case 0xb7: // CueTrackPositions - FOREACH(mf,len) - case 0xf7: // CueTrack - v = readUInt(mf,(unsigned)len); - if (v>255) - errorjmp(mf,"CueTrack points to an invalid track: %d",(int)v); - cc.Track = (unsigned char)v; - break; - case 0xf1: // CueClusterPosition - cc.Position = readUInt(mf,(unsigned)len); - break; - case 0x5378: // CueBlockNumber - cc.Block = readUInt(mf,(unsigned)len); - break; - case 0xea: // CodecState - readUInt(mf,(unsigned)len); - break; - case 0xdb: // CueReference - FOREACH(mf,len) - case 0x96: // CueRefTime - readUInt(mf,(unsigned)len); - break; - case 0x97: // CueRefCluster - readUInt(mf,(unsigned)len); - break; - case 0x535f: // CueRefNumber - readUInt(mf,(unsigned)len); - break; - case 0xeb: // CueRefCodecState - readUInt(mf,(unsigned)len); - break; - ENDFOR(mf); - break; - ENDFOR(mf); - break; + case 0xb3: // CueTime + cc.Time = readUInt(mf,(unsigned)len); + break; + case 0xb7: // CueTrackPositions + + // reset out everything but CueTime + cc.Position = 0; + cc.Block = 0; + cc.Duration = 0; + cc.RelativePosition = 0; + cc.Track = 0; + + FOREACH(mf,len) + case 0xf7: // CueTrack + v = readUInt(mf,(unsigned)len); + if (v>255) + errorjmp(mf,"CueTrack points to an invalid track: %d",(int)v); + cc.Track = (unsigned char)v; + break; + case 0xb2: // CueDuration + cc.Duration = readUInt(mf,(unsigned)len); + break; + case 0xf1: // CueClusterPosition + cc.Position = readUInt(mf,(unsigned)len); + break; + case 0xf0: // CueRelativePosition + cc.RelativePosition = readUInt(mf,(unsigned)len); + break; + case 0x5378: // CueBlockNumber + cc.Block = readUInt(mf,(unsigned)len); + break; + case 0xea: // CodecState + readUInt(mf,(unsigned)len); + break; + case 0xdb: // CueReference + FOREACH(mf,len) + case 0x96: // CueRefTime + readUInt(mf,(unsigned)len); + break; + case 0x97: // CueRefCluster + readUInt(mf,(unsigned)len); + break; + case 0x535f: // CueRefNumber + readUInt(mf,(unsigned)len); + break; + case 0xeb: // CueRefCodecState + readUInt(mf,(unsigned)len); + break; + ENDFOR(mf); + break; + ENDFOR(mf); + + if (mf->nCues == 0 && mf->pCluster - mf->pSegment != cc.Position) { + addCue(mf,mf->pCluster - mf->pSegment,mf->firstTimecode); + startCue = 1; + } + + memcpy(AGET(mf,Cues),&cc,sizeof(cc)); + break; ENDFOR(mf); - if (mf->nCues == 0 && mf->pCluster - mf->pSegment != cc.Position) - addCue(mf,mf->pCluster - mf->pSegment,mf->firstTimecode); + // Update time after parsing all CueTrackPositions + // The time may not have been available before + for (i = startCue; i < mf->nCues; i++) + mf->Cues[i].Time = cc.Time; - memcpy(AGET(mf,Cues),&cc,sizeof(cc)); break; ENDFOR(mf); @@ -1677,12 +1864,12 @@ static void parseCues(MatroskaFile *mf,ulonglong toplen) { if (mf->nCues > 0) for (i = mf->nCues - 1, k = 1; i > 0 && k > 0; --i) for (j = k = 0; j < i; ++j) - if (mf->Cues[j].Time > mf->Cues[j+1].Time) { - struct Cue tmp = mf->Cues[j+1]; - mf->Cues[j+1] = mf->Cues[j]; - mf->Cues[j] = tmp; - ++k; - } + if (mf->Cues[j].Time > mf->Cues[j+1].Time) { + struct Cue tmp = mf->Cues[j+1]; + mf->Cues[j+1] = mf->Cues[j]; + mf->Cues[j] = tmp; + ++k; + } } static void parseAttachment(MatroskaFile *mf,ulonglong toplen) { @@ -1734,10 +1921,10 @@ static void parseAttachments(MatroskaFile *mf,ulonglong toplen) { } static void parseChapter(MatroskaFile *mf,ulonglong toplen,struct Chapter *parent) { - struct ChapterDisplay *disp; - struct ChapterProcess *proc; - struct ChapterCommand *cmd; - struct Chapter *ch = ASGET(mf,parent,Children); + struct ChapterDisplay *disp; + struct ChapterProcess *proc; + struct ChapterCommand *cmd; + struct Chapter *ch = ASGET(mf,parent,Children); memset(ch,0,sizeof(*ch)); @@ -1749,9 +1936,9 @@ static void parseChapter(MatroskaFile *mf,ulonglong toplen,struct Chapter *paren break; case 0x6e67: // ChapterSegmentUID if (len != sizeof(ch->SegmentUID)) - skipbytes(mf, len); + skipbytes(mf, len); else - readbytes(mf, ch->SegmentUID, sizeof(ch->SegmentUID)); + readbytes(mf, ch->SegmentUID, sizeof(ch->SegmentUID)); break; case 0x91: // ChapterTimeStart ch->Start = readUInt(mf,(unsigned)len); @@ -1767,104 +1954,104 @@ static void parseChapter(MatroskaFile *mf,ulonglong toplen,struct Chapter *paren break; case 0x8f: // ChapterTrack FOREACH(mf,len) - case 0x89: // ChapterTrackNumber - *(ulonglong*)(ASGET(mf,ch,Tracks)) = readUInt(mf,(unsigned)len); - break; + case 0x89: // ChapterTrackNumber + *(ulonglong*)(ASGET(mf,ch,Tracks)) = readUInt(mf,(unsigned)len); + break; ENDFOR(mf); break; case 0x80: // ChapterDisplay disp = NULL; FOREACH(mf,len) - case 0x85: // ChapterString - if (disp==NULL) { - disp = ASGET(mf,ch,Display); - memset(disp, 0, sizeof(*disp)); - } - if (disp->String) - skipbytes(mf,len); // Ignore duplicate string - else - STRGETM(mf,disp->String,len); - break; - case 0x437c: // ChapterLanguage - if (disp==NULL) { - disp = ASGET(mf,ch,Display); - memset(disp, 0, sizeof(*disp)); - } - readLangCC(mf, len, disp->Language); - break; - case 0x437e: // ChapterCountry - if (disp==NULL) { - disp = ASGET(mf,ch,Display); - memset(disp, 0, sizeof(*disp)); - } - readLangCC(mf, len, disp->Country); - break; + case 0x85: // ChapterString + if (disp==NULL) { + disp = ASGET(mf,ch,Display); + memset(disp, 0, sizeof(*disp)); + } + if (disp->String) + skipbytes(mf,len); // Ignore duplicate string + else + STRGETM(mf,disp->String,len); + break; + case 0x437c: // ChapterLanguage + if (disp==NULL) { + disp = ASGET(mf,ch,Display); + memset(disp, 0, sizeof(*disp)); + } + readLangCC(mf, len, disp->Language); + break; + case 0x437e: // ChapterCountry + if (disp==NULL) { + disp = ASGET(mf,ch,Display); + memset(disp, 0, sizeof(*disp)); + } + readLangCC(mf, len, disp->Country); + break; ENDFOR(mf); if (disp && !disp->String) - --ch->nDisplay; + --ch->nDisplay; break; case 0x6944: // ChapProcess proc = NULL; FOREACH(mf,len) - case 0x6955: // ChapProcessCodecID - if (proc == NULL) { - proc = ASGET(mf, ch, Process); - memset(proc, 0, sizeof(*proc)); - } - proc->CodecID = (unsigned)readUInt(mf,(unsigned)len); - break; - case 0x450d: // ChapProcessPrivate - if (proc == NULL) { - proc = ASGET(mf, ch, Process); - memset(proc, 0, sizeof(*proc)); - } - if (proc->CodecPrivate) - skipbytes(mf, len); - else { - proc->CodecPrivateLength = (unsigned)len; - STRGETM(mf,proc->CodecPrivate,len); - } - break; - case 0x6911: // ChapProcessCommand - if (proc == NULL) { - proc = ASGET(mf, ch, Process); - memset(proc, 0, sizeof(*proc)); - } + case 0x6955: // ChapProcessCodecID + if (proc == NULL) { + proc = ASGET(mf, ch, Process); + memset(proc, 0, sizeof(*proc)); + } + proc->CodecID = (unsigned)readUInt(mf,(unsigned)len); + break; + case 0x450d: // ChapProcessPrivate + if (proc == NULL) { + proc = ASGET(mf, ch, Process); + memset(proc, 0, sizeof(*proc)); + } + if (proc->CodecPrivate) + skipbytes(mf, len); + else { + proc->CodecPrivateLength = (unsigned)len; + STRGETM(mf,proc->CodecPrivate,len); + } + break; + case 0x6911: // ChapProcessCommand + if (proc == NULL) { + proc = ASGET(mf, ch, Process); + memset(proc, 0, sizeof(*proc)); + } - cmd = NULL; + cmd = NULL; - FOREACH(mf,len) - case 0x6922: // ChapterCommandTime - if (cmd == NULL) { - cmd = ASGET(mf,proc,Commands); - memset(cmd, 0, sizeof(*cmd)); - } - cmd->Time = (unsigned)readUInt(mf,(unsigned)len); - break; - case 0x6933: // ChapterCommandString - if (cmd == NULL) { - cmd = ASGET(mf,proc,Commands); - memset(cmd, 0, sizeof(*cmd)); - } - if (cmd->Command) - skipbytes(mf,len); - else { - cmd->CommandLength = (unsigned)len; - STRGETM(mf,cmd->Command,len); - } - break; - ENDFOR(mf); + FOREACH(mf,len) + case 0x6922: // ChapterCommandTime + if (cmd == NULL) { + cmd = ASGET(mf,proc,Commands); + memset(cmd, 0, sizeof(*cmd)); + } + cmd->Time = (unsigned)readUInt(mf,(unsigned)len); + break; + case 0x6933: // ChapterCommandString + if (cmd == NULL) { + cmd = ASGET(mf,proc,Commands); + memset(cmd, 0, sizeof(*cmd)); + } + if (cmd->Command) + skipbytes(mf,len); + else { + cmd->CommandLength = (unsigned)len; + STRGETM(mf,cmd->Command,len); + } + break; + ENDFOR(mf); - if (cmd && !cmd->Command) - --proc->nCommands; - break; + if (cmd && !cmd->Command) + --proc->nCommands; + break; ENDFOR(mf); if (proc && !proc->nCommands) - --ch->nProcess; + --ch->nProcess; break; case 0xb6: // Nested ChapterAtom parseChapter(mf,len,ch); @@ -1883,25 +2070,25 @@ static void parseChapters(MatroskaFile *mf,ulonglong toplen) { FOREACH(mf,toplen) case 0x45b9: // EditionEntry - ch = AGET(mf,Chapters); - memset(ch, 0, sizeof(*ch)); - FOREACH(mf,len) - case 0x45bc: // EditionUID - ch->UID = readUInt(mf,(unsigned)len); - break; - case 0x45bd: // EditionFlagHidden - ch->Hidden = readUInt(mf,(unsigned)len)!=0; - break; - case 0x45db: // EditionFlagDefault - ch->Default = readUInt(mf,(unsigned)len)!=0; - break; - case 0x45dd: // EditionFlagOrdered - ch->Ordered = readUInt(mf,(unsigned)len)!=0; - break; - case 0xb6: // ChapterAtom - parseChapter(mf,len,ch); - break; - ENDFOR(mf); + ch = AGET(mf,Chapters); + memset(ch, 0, sizeof(*ch)); + FOREACH(mf,len) + case 0x45bc: // EditionUID + ch->UID = readUInt(mf,(unsigned)len); + break; + case 0x45bd: // EditionFlagHidden + ch->Hidden = readUInt(mf,(unsigned)len)!=0; + break; + case 0x45db: // EditionFlagDefault + ch->Default = readUInt(mf,(unsigned)len)!=0; + break; + case 0x45dd: // EditionFlagOrdered + ch->Ordered = readUInt(mf,(unsigned)len)!=0; + break; + case 0xb6: // ChapterAtom + parseChapter(mf,len,ch); + break; + ENDFOR(mf); break; ENDFOR(mf); } @@ -1919,61 +2106,61 @@ static void parseTags(MatroskaFile *mf,ulonglong toplen) { memset(tag,0,sizeof(*tag)); FOREACH(mf,len) - case 0x63c0: // Targets - FOREACH(mf,len) - case 0x63c5: // TrackUID - target = ASGET(mf,tag,Targets); - target->UID = readUInt(mf,(unsigned)len); - target->Type = TARGET_TRACK; - break; - case 0x63c4: // ChapterUID - target = ASGET(mf,tag,Targets); - target->UID = readUInt(mf,(unsigned)len); - target->Type = TARGET_CHAPTER; - break; - case 0x63c6: // AttachmentUID - target = ASGET(mf,tag,Targets); - target->UID = readUInt(mf,(unsigned)len); - target->Type = TARGET_ATTACHMENT; - break; - case 0x63c9: // EditionUID - target = ASGET(mf,tag,Targets); - target->UID = readUInt(mf,(unsigned)len); - target->Type = TARGET_EDITION; - break; - ENDFOR(mf); - break; - case 0x67c8: // SimpleTag - st = ASGET(mf,tag,SimpleTags); - memset(st,0,sizeof(*st)); + case 0x63c0: // Targets + FOREACH(mf,len) + case 0x63c5: // TrackUID + target = ASGET(mf,tag,Targets); + target->UID = readUInt(mf,(unsigned)len); + target->Type = TARGET_TRACK; + break; + case 0x63c4: // ChapterUID + target = ASGET(mf,tag,Targets); + target->UID = readUInt(mf,(unsigned)len); + target->Type = TARGET_CHAPTER; + break; + case 0x63c6: // AttachmentUID + target = ASGET(mf,tag,Targets); + target->UID = readUInt(mf,(unsigned)len); + target->Type = TARGET_ATTACHMENT; + break; + case 0x63c9: // EditionUID + target = ASGET(mf,tag,Targets); + target->UID = readUInt(mf,(unsigned)len); + target->Type = TARGET_EDITION; + break; + ENDFOR(mf); + break; + case 0x67c8: // SimpleTag + st = ASGET(mf,tag,SimpleTags); + memset(st,0,sizeof(*st)); - FOREACH(mf,len) - case 0x45a3: // TagName - if (st->Name) - skipbytes(mf,len); - else - STRGETM(mf,st->Name,len); - break; - case 0x4487: // TagString - if (st->Value) - skipbytes(mf,len); - else - STRGETM(mf,st->Value,len); - break; - case 0x447a: // TagLanguage - readLangCC(mf, len, st->Language); - break; - case 0x4484: // TagDefault - st->Default = readUInt(mf,(unsigned)len)!=0; - break; - ENDFOR(mf); + FOREACH(mf,len) + case 0x45a3: // TagName + if (st->Name) + skipbytes(mf,len); + else + STRGETM(mf,st->Name,len); + break; + case 0x4487: // TagString + if (st->Value) + skipbytes(mf,len); + else + STRGETM(mf,st->Value,len); + break; + case 0x447a: // TagLanguage + readLangCC(mf, len, st->Language); + break; + case 0x4484: // TagDefault + st->Default = readUInt(mf,(unsigned)len)!=0; + break; + ENDFOR(mf); - if (!st->Name || !st->Value) { - mf->cache->memfree(mf->cache,st->Name); - mf->cache->memfree(mf->cache,st->Value); - --tag->nSimpleTags; - } - break; + if (!st->Name || !st->Value) { + mf->cache->memfree(mf->cache,st->Name); + mf->cache->memfree(mf->cache,st->Value); + --tag->nSimpleTags; + } + break; ENDFOR(mf); break; ENDFOR(mf); @@ -1981,7 +2168,7 @@ static void parseTags(MatroskaFile *mf,ulonglong toplen) { static void parseContainer(MatroskaFile *mf) { ulonglong len; - int id = readID(mf); + int id = readID(mf); if (id==EOF) errorjmp(mf,"Unexpected EOF in parseContainer"); @@ -2018,7 +2205,7 @@ static void parseContainerPos(MatroskaFile *mf,ulonglong pos) { } static void parsePointers(MatroskaFile *mf) { - jmp_buf jb; + jmp_buf jb; if (mf->pSegmentInfo && !mf->seen.SegmentInfo) parseContainerPos(mf,mf->pSegmentInfo); @@ -2029,11 +2216,11 @@ static void parsePointers(MatroskaFile *mf) { memcpy(&jb,&mf->jb,sizeof(jb)); - if (setjmp(mf->jb)) + if (setjmp(mf->jb)) mf->flags &= ~MPF_ERROR; // ignore errors else { if (mf->pCues && !mf->seen.Cues) - parseContainerPos(mf,mf->pCues); + parseContainerPos(mf,mf->pCues); if (mf->pAttachments && !mf->seen.Attachments) parseContainerPos(mf,mf->pAttachments); if (mf->pChapters && !mf->seen.Chapters) @@ -2059,24 +2246,24 @@ static void parseSegment(MatroskaFile *mf,ulonglong toplen) { FOREACH2(mf,toplen,0x1f43b675) case 0x114d9b74: // SeekHead if (mf->flags & MKVF_AVOID_SEEKS) { - skipbytes(mf,len); - break; + skipbytes(mf,len); + break; } nextpos = filepos(mf) + len; do { - mf->pSeekHead = 0; - parseSeekHead(mf,len); - ++nSeekHeads; - if (mf->pSeekHead) { // this is possibly a chained SeekHead - seek(mf,mf->pSeekHead); - id = readID(mf); - if (id==EOF) // chained SeekHead points to EOF? - break; - if (id != 0x114d9b74) // chained SeekHead doesnt point to a SeekHead? - break; - len = readSize(mf); - } + mf->pSeekHead = 0; + parseSeekHead(mf,len); + ++nSeekHeads; + if (mf->pSeekHead) { // this is possibly a chained SeekHead + seek(mf,mf->pSeekHead); + id = readID(mf); + if (id==EOF) // chained SeekHead points to EOF? + break; + if (id != 0x114d9b74) // chained SeekHead doesnt point to a SeekHead? + break; + len = readSize(mf); + } } while (mf->pSeekHead && nSeekHeads < 10); seek(mf,nextpos); // resume reading segment break; @@ -2086,12 +2273,12 @@ static void parseSegment(MatroskaFile *mf,ulonglong toplen) { break; case 0x1f43b675: // Cluster if (!mf->pCluster) - mf->pCluster = cur; + mf->pCluster = cur; if (mf->seen.Cluster) { if (len != MAXU64) - skipbytes(mf,len); + skipbytes(mf,len); } else - parseFirstCluster(mf,len); + parseFirstCluster(mf,len); break; case 0x1654ae6b: // Tracks mf->pTracks = cur; @@ -2125,53 +2312,63 @@ static void parseSegment(MatroskaFile *mf,ulonglong toplen) { parsePointers(mf); } +#if 0 static void parseBlockAdditions(MatroskaFile *mf, ulonglong toplen, ulonglong timecode, unsigned track) { - ulonglong add_id = 1, add_pos, add_len; - unsigned char have_add; + ulonglong add_id = 1, add_pos, add_len; + unsigned char have_add; + void *add_data; FOREACH(mf, toplen) case 0xa6: // BlockMore have_add = 0; + add_data = NULL; FOREACH(mf, len) - case 0xee: // BlockAddId - add_id = readUInt(mf, (unsigned)len); - break; - case 0xa5: // BlockAddition - add_pos = filepos(mf); - add_len = len; - skipbytes(mf, len); - ++have_add; - break; + case 0xee: // BlockAddId + add_id = readUInt(mf, (unsigned)len); + break; + case 0xa5: // BlockAddition + add_pos = filepos(mf); + add_len = len; + add_data = mf->cache->memrealloc(mf->cache,add_data,add_len); + readbytes(mf, add_data, len); + ++have_add; + break; ENDFOR(mf); if (have_add == 1 && id > 0 && id < 255) { - struct QueueEntry *qe = QAlloc(mf); - qe->Start = qe->End = timecode; - qe->Position = add_pos; - qe->Length = (unsigned)add_len; - qe->flags = FRAME_UNKNOWN_START | FRAME_UNKNOWN_END | - (((unsigned)add_id << FRAME_STREAM_SHIFT) & FRAME_STREAM_MASK); + struct QueueEntry *qe = QAlloc(mf); + qe->Start = qe->End = timecode; + qe->Position = add_pos; + qe->Length = (unsigned)add_len; + qe->Data = (char *)add_data; + qe->flags = FRAME_UNKNOWN_START | FRAME_UNKNOWN_END | + (((unsigned)add_id << FRAME_STREAM_SHIFT) & FRAME_STREAM_MASK); + qe->DiscardPadding = 0; - QPut(&mf->Queues[track],qe); + QPut(&mf->Queues[track],qe); + } else if(add_data) { + mf->cache->memfree(mf->cache,add_data); } break; ENDFOR(mf); } +#endif static void parseBlockGroup(MatroskaFile *mf,ulonglong toplen,ulonglong timecode, int blockex) { - ulonglong v; - ulonglong duration = 0; - ulonglong dpos; + ulonglong v; + ulonglong duration = 0; + ulonglong dpos; + longlong discard = 0; struct QueueEntry *qe,*qf = NULL; - unsigned char have_duration = 0, have_block = 0; - unsigned char gap = 0; - unsigned char lacing = 0; - unsigned char ref = 0; - unsigned char trackid; - unsigned tracknum = 0; - int c; - unsigned nframes = 0,i; - unsigned *sizes; - signed short block_timecode; + unsigned char have_duration = 0, have_block = 0; + unsigned char gap = 0; + unsigned char lacing = 0; + unsigned char ref = 0; + unsigned char trackid; + unsigned tracknum = 0; + int c; + unsigned nframes = 0,i; + unsigned *sizes; + signed short block_timecode; if (blockex) goto blockex; @@ -2191,15 +2388,15 @@ blockex: v = readVLUInt(mf); if (v>255) - errorjmp(mf,"Invalid track number in Block: %d",(int)v); + errorjmp(mf,"Invalid track number in Block: %d",(int)v); trackid = (unsigned char)v; for (tracknum=0;tracknumnTracks;++tracknum) - if (mf->Tracks[tracknum]->Number == trackid) { - if (mf->trackMask & (1l<Tracks[tracknum]->Number == trackid) { + if (mf->trackMask & (ULL(1)<Tracks[tracknum]->TimecodeScale, - (timecode - mf->firstTimecode + block_timecode) * mf->Seg.TimecodeScale); + (timecode - mf->firstTimecode + block_timecode) * mf->Seg.TimecodeScale); c = readch(mf); if (c==EOF) - errorjmp(mf,"Unexpected EOF while reading Block flags"); + errorjmp(mf,"Unexpected EOF while reading Block flags"); if (blockex) - ref = (unsigned char)!(c & 0x80); + ref = (unsigned char)!(c & 0x80); gap = (unsigned char)(c & 0x1); lacing = (unsigned char)((c >> 1) & 3); if (lacing) { - c = readch(mf); - if (c == EOF) - errorjmp(mf,"Unexpected EOF while reading lacing data"); - nframes = c+1; + c = readch(mf); + if (c == EOF) + errorjmp(mf,"Unexpected EOF while reading lacing data"); + nframes = c+1; } else - nframes = 1; + nframes = 1; sizes = alloca(nframes*sizeof(*sizes)); - + switch (lacing) { - case 0: // No lacing - sizes[0] = (unsigned)(len - filepos(mf) + dpos); - break; - case 1: // Xiph lacing - sizes[nframes-1] = 0; - for (i=0;i1) - sizes[nframes-1] = (unsigned)(len - filepos(mf) + dpos) - sizes[0] - sizes[nframes-1]; - break; - case 2: // Fixed lacing - sizes[0] = (unsigned)(len - filepos(mf) + dpos)/nframes; - for (i=1;i1) + sizes[nframes-1] = (unsigned)(len - filepos(mf) + dpos) - sizes[0] - sizes[nframes-1]; + break; + case 2: // Fixed lacing + sizes[0] = (unsigned)(len - filepos(mf) + dpos)/nframes; + for (i=1;iStart = timecode; - qe->End = timecode; - qe->Position = v; - qe->Length = sizes[i]; - qe->flags = FRAME_UNKNOWN_END | FRAME_KF; - if (i == nframes-1 && gap) - qe->flags |= FRAME_GAP; - if (i > 0) - qe->flags |= FRAME_UNKNOWN_START; + qe->Start = timecode; + qe->End = timecode; + qe->Position = v; + qe->Length = sizes[i]; + qe->Data = (char *)mf->cache->memalloc(mf->cache,qe->Length + 16); + readbytes(mf, qe->Data, qe->Length); + qe->flags = FRAME_UNKNOWN_END | FRAME_KF; + if (i == nframes-1 && gap) + qe->flags |= FRAME_GAP; + if (i > 0) + qe->flags |= FRAME_UNKNOWN_START; + qe->DiscardPadding = 0; - QPut(&mf->Queues[tracknum],qe); + QPut(&mf->Queues[tracknum],qe); - v += sizes[i]; + v += sizes[i]; } // we want to still load these bytes into cache for (v = filepos(mf) & ~0x3fff; v < len + dpos; v += 0x4000) - mf->cache->read(mf->cache,v,NULL,0); // touch page + mf->cache->read(mf->cache,v,NULL,0); // touch page skipbytes(mf,len - filepos(mf) + dpos); if (blockex) - goto out; + goto out; break; case 0x9b: // BlockDuration duration = readUInt(mf,(unsigned)len); have_duration = 1; break; case 0x75a1: // BlockAdditions - if (nframes > 0) // have some frames - parseBlockAdditions(mf, len, timecode, tracknum); - else - skipbytes(mf, len); + /*if (nframes > 0) // have some frames + parseBlockAdditions(mf, len, timecode, tracknum); + else*/ + skipbytes(mf, len); + break; + case 0x75a2: // DiscardPadding + discard = readSInt(mf,(unsigned)len); break; ENDFOR(mf); @@ -2319,15 +2522,15 @@ out: if (have_duration) { duration = mul3(mf->Tracks[tracknum]->TimecodeScale, - duration * mf->Seg.TimecodeScale); + duration * mf->Seg.TimecodeScale); for (qe = qf; nframes > 1; --nframes, qe = qe->next) { - qe->Start = v; - v += defd; - duration -= defd; - qe->End = v; + qe->Start = v; + v += defd; + duration -= defd; + qe->End = v; #if 0 - qe->flags &= ~(FRAME_UNKNOWN_START|FRAME_UNKNOWN_END); + qe->flags &= ~(FRAME_UNKNOWN_START|FRAME_UNKNOWN_END); #endif } qe->Start = v; @@ -2335,23 +2538,28 @@ out: qe->flags &= ~FRAME_UNKNOWN_END; } else if (mf->Tracks[tracknum]->DefaultDuration) { for (qe = qf; nframes > 0; --nframes, qe = qe->next) { - qe->Start = v; - v += defd; - qe->End = v; - qe->flags &= ~(FRAME_UNKNOWN_START|FRAME_UNKNOWN_END); + qe->Start = v; + v += defd; + qe->End = v; + qe->flags &= ~(FRAME_UNKNOWN_START|FRAME_UNKNOWN_END); } } } else if (nframes == 1) { if (have_duration) { qf->End = qf->Start + mul3(mf->Tracks[tracknum]->TimecodeScale, - duration * mf->Seg.TimecodeScale); + duration * mf->Seg.TimecodeScale); qf->flags &= ~FRAME_UNKNOWN_END; } else if (mf->Tracks[tracknum]->DefaultDuration) { qf->End = qf->Start + mf->Tracks[tracknum]->DefaultDuration; qf->flags &= ~FRAME_UNKNOWN_END; } + qf->DiscardPadding = discard; } + // work-around for broken files which don't flag eg. audio as keyframes + if (ref && mf->Tracks[tracknum]->NeedKeyframes) + ref = 0; + if (ref) while (qf) { qf->flags &= ~FRAME_KF; @@ -2364,6 +2572,8 @@ static void ClearQueue(MatroskaFile *mf,struct Queue *q) { for (qe=q->head;qe;qe=qn) { qn = qe->next; + mf->cache->memfree(mf->cache, qe->Data); + qe->Data = NULL; qe->next = mf->QFreeList; mf->QFreeList = qe; } @@ -2373,18 +2583,18 @@ static void ClearQueue(MatroskaFile *mf,struct Queue *q) { } static void EmptyQueues(MatroskaFile *mf) { - unsigned i; + unsigned i; for (i=0;inTracks;++i) ClearQueue(mf,&mf->Queues[i]); } static int readMoreBlocks(MatroskaFile *mf) { - ulonglong toplen, cstop; - longlong cp; - int cid, ret = 0; - jmp_buf jb; - volatile unsigned retries = 0; + ulonglong toplen, cstop; + longlong cp; + int cid, ret = 0; + jmp_buf jb; + volatile unsigned retries = 0; if (mf->readPosition >= mf->pSegmentTop) return EOF; @@ -2403,26 +2613,26 @@ static int readMoreBlocks(MatroskaFile *mf) { for (;;) { if (filepos(mf) >= mf->pSegmentTop) - goto ex; + goto ex; cp = mf->cache->scan(mf->cache,filepos(mf),0x1f43b675); // cluster if (cp < 0 || (ulonglong)cp >= mf->pSegmentTop) - goto ex; + goto ex; seek(mf,cp); cid = readID(mf); if (cid == EOF) - goto ex; + goto ex; if (cid == 0x1f43b675) { - toplen = readSizeUnspec(mf); - if (toplen < MAXCLUSTER || toplen == MAXU64) { - // reset error flags - mf->flags &= ~MPF_ERROR; - ret = RBRESYNC; - break; - } + toplen = readSizeUnspec(mf); + if (toplen < MAXCLUSTER || toplen == MAXU64) { + // reset error flags + mf->flags &= ~MPF_ERROR; + ret = RBRESYNC; + break; + } } } @@ -2445,57 +2655,56 @@ static int readMoreBlocks(MatroskaFile *mf) { toplen = cid == 0x1f43b675 ? readSizeUnspec(mf) : readSize(mf); if (cid == 0x1f43b675) { // Cluster - unsigned char have_timecode = 0; + unsigned char have_timecode = 0; FOREACH2(mf,toplen,0x1f43b675) case 0x1f43b675: RESTART(); break; - case 0xe7: // Timecode - mf->tcCluster = readUInt(mf,(unsigned)len); - have_timecode = 1; - break; - case 0xa7: // Position - readUInt(mf,(unsigned)len); - break; - case 0xab: // PrevSize - readUInt(mf,(unsigned)len); - break; - case 0x5854: { // SilentTracks - unsigned stmask = 0, i, trk; - FOREACH(mf, len) - case 0x58d7: // SilentTrackNumber - trk = (unsigned)readUInt(mf, (unsigned)len); - for (i = 0; i < mf->nTracks; ++i) - if (mf->Tracks[i]->Number == trk) { - stmask |= 1 << i; - break; - } - break; - ENDFOR(mf); - // TODO pass stmask to reading app - break; } - case 0xa0: // BlockGroup - if (!have_timecode) - errorjmp(mf,"Found BlockGroup before cluster TimeCode"); - parseBlockGroup(mf,len,mf->tcCluster, 0); - goto out; - case 0xa3: // BlockEx - if (!have_timecode) - errorjmp(mf,"Found BlockGroup before cluster TimeCode"); - parseBlockGroup(mf, len, mf->tcCluster, 1); - goto out; + case 0xe7: // Timecode + mf->tcCluster = readUInt(mf,(unsigned)len); + have_timecode = 1; + break; + case 0xa7: // Position + readUInt(mf,(unsigned)len); + break; + case 0xab: // PrevSize + readUInt(mf,(unsigned)len); + break; + case 0x5854: { // SilentTracks + ulonglong stmask = 0; + unsigned i, trk; + FOREACH(mf, len) + case 0x58d7: // SilentTrackNumber + trk = (unsigned)readUInt(mf, (unsigned)len); + for (i = 0; i < mf->nTracks; ++i) + if (mf->Tracks[i]->Number == trk) { + stmask |= ULL(1) << i; + break; + } + break; + ENDFOR(mf); + // TODO pass stmask to reading app + break; } + case 0xa0: // BlockGroup + if (!have_timecode) + errorjmp(mf,"Found BlockGroup before cluster TimeCode"); + parseBlockGroup(mf,len,mf->tcCluster, 0); + goto out; + case 0xa3: // BlockEx + if (!have_timecode) + errorjmp(mf,"Found BlockGroup before cluster TimeCode"); + parseBlockGroup(mf, len, mf->tcCluster, 1); + goto out; ENDFOR(mf); out:; } else { - if (toplen > MAXFRAME) - errorjmp(mf,"Element in a cluster is too large around %llu, %X [%u]",filepos(mf),cid,(unsigned)toplen); if (cid == 0xa0) // BlockGroup - parseBlockGroup(mf,toplen,mf->tcCluster, 0); + parseBlockGroup(mf,toplen,mf->tcCluster, 0); else if (cid == 0xa3) // BlockEx - parseBlockGroup(mf, toplen, mf->tcCluster, 1); + parseBlockGroup(mf, toplen, mf->tcCluster, 1); else - skipbytes(mf,toplen); + skipbytes(mf,toplen); } if ((mf->readPosition = filepos(mf)) > cstop) @@ -2512,16 +2721,16 @@ ex: // this is almost the same as readMoreBlocks, except it ensures // there are no partial frames queued, however empty queues are ok -static int fillQueues(MatroskaFile *mf,unsigned int mask) { +static int fillQueues(MatroskaFile *mf,ulonglong mask) { unsigned i,j; - int ret = 0; + int ret = 0; for (;;) { j = 0; for (i=0;inTracks;++i) - if (mf->Queues[i].head && !(mask & (1<Queues[i].head && !(mask & (ULL(1)<0) // have at least some frames return ret; @@ -2529,10 +2738,10 @@ static int fillQueues(MatroskaFile *mf,unsigned int mask) { if ((ret = readMoreBlocks(mf)) < 0) { j = 0; for (i=0;inTracks;++i) - if (mf->Queues[i].head && !(mask & (1<Queues[i].head && !(mask & (ULL(1)<= mf->pSegmentTop) @@ -2603,14 +2812,14 @@ static void reindex(MatroskaFile *mf) { while (filepos(mf) < (ulonglong)next_cluster + 1024) { id = readID(mf); if (id == EOF) - break; + break; isize = readVLUInt(mf); if (id == 0xe7) { // cluster timecode - tc = readUInt(mf,(unsigned)isize); - have_tc = 1; - break; + tc = readUInt(mf,(unsigned)isize); + have_tc = 1; + break; } skipbytes(mf,isize); @@ -2670,9 +2879,9 @@ static void fixupChapter(ulonglong adj, struct Chapter *ch) { fixupChapter(adj,&ch->Children[i]); } -static longlong findLastTimecode(MatroskaFile *mf) { +static longlong findLastTimecode(MatroskaFile *mf) { ulonglong nd = 0; - unsigned n,vtrack; + unsigned n,vtrack,retry=0; if (mf->nTracks == 0) return -1; @@ -2688,25 +2897,36 @@ ok: EmptyQueues(mf); - if (mf->nCues == 0) { - mf->readPosition = mf->pCluster + 13000000 > mf->pSegmentTop ? mf->pCluster : mf->pSegmentTop - 13000000; - mf->tcCluster = 0; - } else { - mf->readPosition = mf->Cues[mf->nCues - 1].Position + mf->pSegment; - mf->tcCluster = mf->Cues[mf->nCues - 1].Time / mf->Seg.TimecodeScale; - } - mf->trackMask = ~(1l << vtrack); + mf->trackMask = ~(ULL(1) << vtrack); - do - while (mf->Queues[vtrack].head) - { - ulonglong tc = mf->Queues[vtrack].head->flags & FRAME_UNKNOWN_END ? - mf->Queues[vtrack].head->Start : mf->Queues[vtrack].head->End; - if (nd < tc) - nd = tc; - QFree(mf,QGet(&mf->Queues[vtrack])); + while (nd == 0 && retry < MAXDURATIONRETRY) { + if (mf->nCues == 0) { + mf->readPosition = mf->pCluster + (MAXDURATIONREAD << retry) > mf->pSegmentTop ? mf->pCluster : mf->pSegmentTop - (MAXDURATIONREAD << retry); + mf->tcCluster = 0; + + if (retry > 0 && (mf->pCluster + (MAXDURATIONREAD << retry) > mf->pSegmentTop) && (mf->pCluster + (MAXDURATIONREAD << (retry - 1)) > mf->pSegmentTop)) + break; + } else { + if (retry >= mf->nCues) + break; + + mf->readPosition = mf->Cues[mf->nCues - (1 + retry)].Position + mf->pSegment; + mf->tcCluster = mf->Cues[mf->nCues - (1 + retry)].Time / mf->Seg.TimecodeScale; } - while (fillQueues(mf,0) != EOF); + + do + while (mf->Queues[vtrack].head) + { + ulonglong tc = mf->Queues[vtrack].head->flags & FRAME_UNKNOWN_END ? + mf->Queues[vtrack].head->Start : mf->Queues[vtrack].head->End; + if (nd < tc) + nd = tc; + QFree(mf, QGet(&mf->Queues[vtrack])); + } + while (fillQueues(mf, 0) != EOF); + + retry++; + } mf->trackMask = 0; @@ -2725,7 +2945,7 @@ ok: static void parseFile(MatroskaFile *mf) { ulonglong len = filepos(mf), adjust; unsigned i; - int id = readID(mf); + int id = readID(mf); if (id==EOF) errorjmp(mf,"Unexpected EOF at start of file"); @@ -2761,7 +2981,7 @@ segment: if (mf->cache->getfilesize) { longlong seglen = mf->cache->getfilesize(mf->cache); if (seglen > 0) - mf->pSegmentTop = seglen; + mf->pSegmentTop = seglen; } } else mf->pSegmentTop = mf->pSegment + len; @@ -2801,6 +3021,61 @@ segment: mf->tcCluster = mf->firstTimecode; } +static void parseFileSparse(MatroskaFile *mf) { + ulonglong len = filepos(mf); + int id = readID(mf); + + if (id==EOF) + errorjmp(mf,"Unexpected EOF at start of file"); + + // files with multiple concatenated segments can have only + // one EBML prolog + if (len > 0 && id == 0x18538067) + goto segment; + + if (id!=0x1a45dfa3) + errorjmp(mf,"First element in file is not EBML"); + + parseEBML(mf,readSize(mf)); + + // next we need to find the first segment + for (;;) { + id = readID(mf); + if (id==EOF) + errorjmp(mf,"No segments found in the file"); +segment: + len = readSizeUnspec(mf); + if (id == 0x18538067) // Segment + break; + if (len == MAXU64) + errorjmp(mf,"No segments found in the file"); + skipbytes(mf,len); + } + + // found it + mf->pSegment = filepos(mf); + + // we want to read data until we find a seekhead or a trackinfo + FOREACH2(mf,len,0x1f43b675) + case 0x1549a966: // SegmentInfo + mf->pSegmentInfo = cur; + FOREACH(mf,len) + case 0x73a4: // SegmentUID + if (len != sizeof(mf->Seg.UID)) + errorjmp(mf,"SegmentUID size is not %d bytes",mf->Seg.UID); + readbytes(mf,mf->Seg.UID,sizeof(mf->Seg.UID)); + return; + ENDFOR(mf); + break; + ENDFOR1(mf); + // if we found our segment info + if (mf->pSegmentInfo) + break; + ENDFOR2(); + + errorjmp(mf,"Couldn't find SegmentInfo"); +} + static void DeleteChapter(MatroskaFile *mf,struct Chapter *ch) { unsigned i,j; @@ -2822,14 +3097,143 @@ static void DeleteChapter(MatroskaFile *mf,struct Chapter *ch) { mf->cache->memfree(mf->cache,ch->Children); } +// Precondition: we are currently right at the start of a Block +// or SimpleBlock or BlockGroup element and the Queues are all empty. +// +// Parse the block at relative position cueRelativePosition within the +// cluster at absolute offset clusterOffset and return a pointer to a QueueEntry +// storing its data. (This only parses the block and not sibling +// elements so the start timecode will equal the end timecode.) +// If we are not right at the start of something resembling a block, +// returns NULL. The caller is responsible for ensuring eventual disposal +// of the QueueEntry via the QFree function. This function gurantees mf queues +// are empty after completing. +// +// The returned QueueEntry may have garbage Start and End values +static struct QueueEntry* seekAndReadLoneBlock(MatroskaFile *mf, ulonglong clusterOffset, ulonglong cueRelativePosition) { + jmp_buf jb; + int ebmlID; + ulonglong toplen; + int nTracks = mf->nTracks; + struct QueueEntry *ret = NULL; + ulonglong clusterRelZero; + + memcpy(&jb, &mf->jb, sizeof(jb)); + if (setjmp(mf->jb) != 0) + goto out; + + seek(mf, clusterOffset + 4); // seek to right after the ebml id of the cluster + readSizeUnspec(mf); // move to right after the end of the encoding of the cluster size (relative position 0) + clusterRelZero = filepos(mf); // absolute offset corresponding to relative position 0 within the cluster + seek(mf, clusterRelZero + cueRelativePosition); // seek to start of BlockGroup/Block/SimpleBlock + + // the spec is unclear on whether CueRelativePositoin should be the position of a Block's BlockGroup + // or the Block itself, so we handle both possibilities. + ebmlID = readID(mf); + if (ebmlID == 0xa0 || ebmlID == 0xa1 || ebmlID == 0xa3) { // BlockGroup or Block or SimpleBlock + toplen = readSize(mf); + + if (ebmlID == 0xa0) { // BlockGroup + parseBlockGroup(mf, toplen, 0, 0); // parses block into a queue in mf + } else { + parseBlockGroup(mf, toplen, 0, 1); // parses block into a queue in mf + } + + // find the block and return it + for (int i = 0; i < nTracks; ++i) { + ret = QGet(&mf->Queues[i]); + if (ret) + break; + } + } + +out: + // if for some reason a file tried to use lacing + // for subtitle blocks, we might have a nonempty queue. + EmptyQueues(mf); + memcpy(&mf->jb, &jb, sizeof(jb)); + return ret; +} + +// get index in mf->Tracks corresponding to trackNum +// returns -1 if track number is invalid +static int TrackNumToIndex(MatroskaFile *mf, unsigned char trackNum) { + int nTracks = mf->nTracks; + for (int i = 0; i < nTracks; ++i) + if (mf->Tracks[i]->Number == trackNum) + return i; + + return -1; +} + +// returns the index of the next cue at index >= startIdx that corresponds +// to a pre-existing subtitle at timecode timecode. If no such cue exists, +// returns -1. All cues corresponding to indices returned by this function are +// guaranteed to have valid track numbers. +// +static int NextPESubtitleIdx(MatroskaFile *mf, ulonglong timecode, int startIdx) { + int nCues = mf->nCues; + Cue cue; + + for (int i = startIdx; i < nCues; ++i) { + cue = mf->Cues[i]; + + if (cue.Time > timecode) { + break; + } else { + int trackIndex = TrackNumToIndex(mf, cue.Track); + + if (trackIndex >= 0 && mf->Tracks[trackIndex]->Type == TT_SUB && !(mf->trackMask & (ULL(1) << trackIndex)) + && cue.Duration && cue.RelativePosition && cue.Time + cue.Duration >= timecode) { + + return i; + } + } + } + + return -1; +} + +static void GetSubtitlePreroll(MatroskaFile *mf, ulonglong timecode, struct Queue *subPreQueues) { + struct QueueEntry *qe; + Cue cue; + ulonglong prevPosition = 0, prevRelativePosition = 0; + + EmptyQueues(mf); + + // for each cue that overlaps with timecode in a subtitle track, add it to the corresponding + // queue in subPreQueues + for (int i = NextPESubtitleIdx(mf, timecode, 0); i != -1; i = NextPESubtitleIdx(mf, timecode, i+1)) { + cue = mf->Cues[i]; + + // skip to next cue if we are going to read same block as previous + if (cue.Position == prevPosition && cue.RelativePosition == prevRelativePosition) + continue; + + // read the block contents into a QueueEntry and insert it + qe = seekAndReadLoneBlock(mf, mf->pSegment + cue.Position, cue.RelativePosition); + + if (qe) { + int trackIndex = TrackNumToIndex(mf, cue.Track); + qe->Start = mul3(mf->Tracks[trackIndex]->TimecodeScale, cue.Time); + qe->End = qe->Start + cue.Duration; + QPut(&subPreQueues[trackIndex], qe); + } + + // save present Position and RelativePosition for future comparisons + prevPosition = cue.Position; + prevRelativePosition = cue.RelativePosition; + } +} + /////////////////////////////////////////////////////////////////////////// // public interface MatroskaFile *mkv_OpenEx(InputStream *io, - ulonglong base, - unsigned flags, - char *err_msg,unsigned msgsize) + ulonglong base, + unsigned flags, + char *err_msg,unsigned msgsize) { - MatroskaFile *mf = io->memalloc(io,sizeof(*mf)); + MatroskaFile *mf = io->memalloc(io,sizeof(*mf)); if (mf == NULL) { mystrlcpy(err_msg,"Out of memory",msgsize); return NULL; @@ -2853,13 +3257,40 @@ MatroskaFile *mkv_OpenEx(InputStream *io, return mf; } +MatroskaFile *mkv_OpenSparse(InputStream *io, + char *err_msg,unsigned msgsize) +{ + MatroskaFile *mf = io->memalloc(io,sizeof(*mf)); + if (mf == NULL) { + mystrlcpy(err_msg,"Out of memory",msgsize); + return NULL; + } + + memset(mf,0,sizeof(*mf)); + + mf->cache = io; + mf->flags = MKVF_AVOID_SEEKS; + io->progress(io,0,0); + + if (setjmp(mf->jb)==0) { + seek(mf,0); + parseFileSparse(mf); + } else { // parser error + mystrlcpy(err_msg,mf->errmsg,msgsize); + mkv_Close(mf); + return NULL; + } + + return mf; +} + MatroskaFile *mkv_Open(InputStream *io, - char *err_msg,unsigned msgsize) + char *err_msg,unsigned msgsize) { return mkv_OpenEx(io,0,0,err_msg,msgsize); } -void mkv_Close(MatroskaFile *mf) { +void mkv_Close(MatroskaFile *mf) { unsigned i,j; if (mf==NULL) @@ -2869,8 +3300,11 @@ void mkv_Close(MatroskaFile *mf) { mf->cache->memfree(mf->cache,mf->Tracks[i]); mf->cache->memfree(mf->cache,mf->Tracks); - for (i=0;inQBlocks;++i) + for (i=0;inQBlocks;++i) { + for (j=0;jcache->memfree(mf->cache, mf->QBlocks[i][j].Data); mf->cache->memfree(mf->cache,mf->QBlocks[i]); + } mf->cache->memfree(mf->cache,mf->QBlocks); mf->cache->memfree(mf->cache,mf->Queues); @@ -2905,6 +3339,7 @@ void mkv_Close(MatroskaFile *mf) { } mf->cache->memfree(mf->cache,mf->Tags); + mf->cache->memfree(mf->cache, mf->cpbuf); mf->cache->memfree(mf->cache,mf); } @@ -2927,17 +3362,22 @@ TrackInfo *mkv_GetTrackInfo(MatroskaFile *mf,unsigned track) { return mf->Tracks[track]; } -void mkv_GetAttachments(MatroskaFile *mf,Attachment **at,unsigned *count) { +void mkv_GetAttachments(MatroskaFile *mf,Attachment **at,unsigned *count) { *at = mf->Attachments; *count = mf->nAttachments; } -void mkv_GetChapters(MatroskaFile *mf,Chapter **ch,unsigned *count) { +void mkv_GetChapters(MatroskaFile *mf,Chapter **ch,unsigned *count) { *ch = mf->Chapters; *count = mf->nChapters; } -void mkv_GetTags(MatroskaFile *mf,Tag **tag,unsigned *count) { +void mkv_GetCues(MatroskaFile *mf,Cue **cue,unsigned *count) { + *cue = mf->Cues; + *count = mf->nCues; +} + +void mkv_GetTags(MatroskaFile *mf,Tag **tag,unsigned *count) { *tag = mf->Tags; *count = mf->nTags; } @@ -2946,13 +3386,80 @@ ulonglong mkv_GetSegmentTop(MatroskaFile *mf) { return mf->pSegmentTop; } -#define IS_DELTA(f) (!((f)->flags & FRAME_KF) || ((f)->flags & FRAME_UNKNOWN_START)) +#define IS_DELTA(f) (!((f)->flags & FRAME_KF) || ((f)->flags & FRAME_UNKNOWN_START)) + +static inline ulonglong mkv_time_diff(ulonglong one, ulonglong two) +{ + if (one > two) + return one-two; + else + return two-one; +} + +void mkv_Seek_CueAware(MatroskaFile *mf, ulonglong timecode, unsigned flags, unsigned fuzzy) +{ + if (timecode > 0 && (flags & (MKVF_SEEK_TO_PREV_KEYFRAME|MKVF_SEEK_TO_PREV_KEYFRAME_STRICT))) { + unsigned int count, i; + unsigned char track = 0; + ulonglong default_duration = 10000000; + Cue *cue; + + for (i=0;inTracks;++i) { + if (mf->Tracks[i]->Type == TT_VIDEO && !(mf->trackMask & (ULL(1)<Tracks[i]->Number; + if (mf->Tracks[i]->DefaultDuration) + default_duration = mf->Tracks[i]->DefaultDuration; + break; + } + } + + mkv_GetCues(mf, &cue, &count); + if (count > 0) { + ulonglong prevDiff = ULLONG_MAX; + ulonglong newTimecode = timecode; + for (i = 0; i < count; i++) { + ulonglong tcDiff = mkv_time_diff(cue[i].Time, timecode); + if ((!track || !cue[i].Track || cue[i].Track == track) && (tcDiff == 0 || (fuzzy && tcDiff <= default_duration))) { + flags &= ~(MKVF_SEEK_TO_PREV_KEYFRAME|MKVF_SEEK_TO_PREV_KEYFRAME_STRICT); + if (tcDiff < prevDiff) { + newTimecode = cue[i].Time; + prevDiff = tcDiff; + } + } + } + timecode = newTimecode; + } + } + mkv_Seek(mf, timecode, flags); +} + +static inline int CueSuitableForSeeking(MatroskaFile *mf, int nCue) { + int nTrack = -1, n; + unsigned char nBestTrackType = TT_SUB; + + if (nCue < 0 || nCue >= mf->nCues) + return 0; + + for (n = 0; n < mf->nTracks; ++n) { + if (!(mf->trackMask & (ULL(1)<Tracks[n]->Type < nBestTrackType) + nBestTrackType = mf->Tracks[n]->Type; + + if (mf->Tracks[n]->Number == mf->Cues[nCue].Track) + nTrack = n; + } + + if (nTrack >= 0 && nTrack < mf->nTracks && mf->Tracks[nTrack]->Type > FFMAX(mf->CueBestType, nBestTrackType)) + return 0; + + return 1; +} void mkv_Seek(MatroskaFile *mf,ulonglong timecode,unsigned flags) { - int i,j,m,ret; - unsigned n,z,mask; - ulonglong m_kftime[MAX_TRACKS]; - unsigned char m_seendf[MAX_TRACKS]; + int i,j,m,ret; + unsigned n,z; + ulonglong mask,m_kftime[MAX_TRACKS]; + unsigned char m_seendf[MAX_TRACKS]; + struct Queue *subPreQueues = NULL; if (mf->flags & MKVF_AVOID_SEEKS) return; @@ -2966,10 +3473,10 @@ void mkv_Seek(MatroskaFile *mf,ulonglong timecode,unsigned flags) { return; } - if (mf->nCues==0) + if (mf->nCues == 0) reindex(mf); - if (mf->nCues==0) + if (mf->nCues == 0) return; mf->flags &= ~MPF_ERROR; @@ -2977,85 +3484,95 @@ void mkv_Seek(MatroskaFile *mf,ulonglong timecode,unsigned flags) { i = 0; j = mf->nCues - 1; - for (;;) { - if (i>j) { - j = j>=0 ? j : 0; + // get pre-existing subtitles that should be displayed at timecode + subPreQueues = QsStructAlloc(mf); + GetSubtitlePreroll(mf, timecode, subPreQueues); - if (setjmp(mf->jb)!=0) - return; + for (;;) { + if (i > j) { + j = j >= 0 ? j : 0; + + if (setjmp(mf->jb) != 0) + goto dealloc; mkv_SetTrackMask(mf,mf->trackMask); if (flags & (MKVF_SEEK_TO_PREV_KEYFRAME | MKVF_SEEK_TO_PREV_KEYFRAME_STRICT)) { - // we do this in two stages - // a. find the last keyframes before the require position - // b. seek to them + // we do this in two stages + // a. find the last keyframes before the require position + // b. seek to them - // pass 1 - for (;;) { - for (n=0;nnTracks;++n) { - m_kftime[n] = MAXU64; - m_seendf[n] = 0; - } + // pass 1 + for (;;) { + if (!CueSuitableForSeeking(mf, j)) { + // skip this Cue, re-start from previous + --j; + goto again; + } - EmptyQueues(mf); + for (n = 0; n < mf->nTracks; ++n) { + m_kftime[n] = MAXU64; + m_seendf[n] = 0; + } - mf->readPosition = mf->Cues[j].Position + mf->pSegment; - mf->tcCluster = mf->Cues[j].Time; + EmptyQueues(mf); - for (;;) { - if ((ret = fillQueues(mf,0)) < 0 || ret == RBRESYNC) - return; + mf->readPosition = mf->Cues[j].Position + mf->pSegment; + mf->tcCluster = mf->Cues[j].Time; - // drain queues until we get to the required timecode - for (n=0;nnTracks;++n) { - if (mf->Queues[n].head && (mf->Queues[n].head->StartQueues[n].head)) - m_seendf[n] = 1; - else - m_kftime[n] = mf->Queues[n].head->Start; - } + for (;;) { + if ((ret = fillQueues(mf,0)) < 0 || ret == RBRESYNC) + goto dealloc; - while (mf->Queues[n].head && mf->Queues[n].head->StartQueues[n].head)) - m_seendf[n] = 1; - else - m_kftime[n] = mf->Queues[n].head->Start; - QFree(mf,QGet(&mf->Queues[n])); - } + // drain queues until we get to the required timecode + for (n = 0; n < mf->nTracks; ++n) { + if (mf->Queues[n].head && (mf->Queues[n].head->StartQueues[n].head)) + m_seendf[n] = 1; + else + m_kftime[n] = mf->Queues[n].head->Start; + } + + while (mf->Queues[n].head && mf->Queues[n].head->Start < timecode) + { + if (IS_DELTA(mf->Queues[n].head)) + m_seendf[n] = 1; + else + m_kftime[n] = mf->Queues[n].head->Start; + QFree(mf,QGet(&mf->Queues[n])); + } // We've drained the queue, so the frame at head is the next one past the requered point. // In strict mode we are done, but when seeking is not strict we use the head frame // if it's not an audio track (we accept preroll within a frame for audio), and the head frame // is a keyframe if (!(flags & MKVF_SEEK_TO_PREV_KEYFRAME_STRICT)) - if (mf->Queues[n].head && (mf->Tracks[n]->Type != TT_AUDIO || mf->Queues[n].head->Start<=timecode)) - if (!IS_DELTA(mf->Queues[n].head)) - m_kftime[n] = mf->Queues[n].head->Start; - } + if (mf->Queues[n].head && (mf->Tracks[n]->Type != TT_AUDIO || mf->Queues[n].head->Start <= timecode)) + if (!IS_DELTA(mf->Queues[n].head)) + m_kftime[n] = mf->Queues[n].head->Start; + } - for (n=0;nnTracks;++n) - if (mf->Queues[n].head && mf->Queues[n].head->Start>=timecode) - goto found; - } + for (n = 0; n < mf->nTracks; ++n) + if (mf->Queues[n].head && mf->Queues[n].head->Start >= timecode) + goto found; + } found: - - for (n=0;nnTracks;++n) - if (!(mf->trackMask & (1l<0) - { - // we need to restart the search from prev cue - --j; - goto again; - } - break; + for (n = 0; n < mf->nTracks; ++n) + if (!(mf->trackMask & (ULL(1) << n)) && m_kftime[n] == MAXU64 && + m_seendf[n] && j > 0 && (mf->Tracks[n]->Type == TT_VIDEO || mf->Tracks[n]->Type == TT_AUDIO)) + { + // we need to restart the search from prev cue + --j; + goto again; + } + + break; again:; - } + } } else - for (n=0;nnTracks;++n) - m_kftime[n] = timecode; + for (n = 0; n < mf->nTracks; ++n) + m_kftime[n] = timecode; // now seek to this timecode EmptyQueues(mf); @@ -3063,35 +3580,69 @@ again:; mf->readPosition = mf->Cues[j].Position + mf->pSegment; mf->tcCluster = mf->Cues[j].Time; - for (mask=0;;) { - if ((ret = fillQueues(mf,mask)) < 0 || ret == RBRESYNC) - return; + // no timecodes for ignored streams + for (n = 0; n < mf->nTracks; ++n) + if (mf->trackMask & (ULL(1) << n)) + m_kftime[n] = MAXU64; - // drain queues until we get to the required timecode - for (n=0;nnTracks;++n) { - struct QueueEntry *qe; - for (qe = mf->Queues[n].head;qe && qe->StartQueues[n].head) - QFree(mf,QGet(&mf->Queues[n])); - } + for (mask = mf->trackMask;;) { + if ((ret = fillQueues(mf,mask)) < 0 || ret == RBRESYNC) + goto dealloc; - for (n=z=0;nnTracks;++n) - if (m_kftime[n]==MAXU64 || (mf->Queues[n].head && mf->Queues[n].head->Start>=m_kftime[n])) { - ++z; - mask |= 1<nTracks; ++n) { + struct QueueEntry *qe; + for (qe = mf->Queues[n].head; qe && qe->StartQueues[n].head) + QFree(mf,QGet(&mf->Queues[n])); + } - if (z==mf->nTracks) - return; + for (n = z = 0; n < mf->nTracks; ++n) + if (m_kftime[n] == MAXU64 || (mf->Queues[n].head && mf->Queues[n].head->Start >= m_kftime[n])) { + ++z; + mask |= ULL(1) << n; + } else if (!(mf->Tracks[n]->Type == TT_VIDEO || mf->Tracks[n]->Type == TT_AUDIO)) { + ++z; + } + + if (z == mf->nTracks) { + for (int i = 0; i < mf->nTracks; ++i) { + if (subPreQueues[i].head) { // if the subPreQueues are not empty + ulonglong fp = filepos(mf); + struct QueueEntry *qe; + struct Queue tmpQ = { .head = NULL, .tail = NULL }; + + // remove any subtitles from queues that are duplicates of stuff in subPreQueues + if (mf->Tracks[i]->Type == TT_SUB) + while (mf->Queues[i].head && mf->Queues[i].head->Start <= timecode) + QFree(mf, QGet(&mf->Queues[i])); + + // from subPreQueues, filter out any subtitle blocks that we'll see later on in the file + // (prevents the occasional case of having a subtitle displayed twice) + while (qe = subPreQueues[i].head) + if (qe->Position < fp) + QPut(&tmpQ, QGet(&subPreQueues[i])); + else + QFree(mf, QGet(&subPreQueues[i])); + subPreQueues[i] = tmpQ; + } + } + QsDumpHead(mf->Queues, subPreQueues, mf->nTracks); // add pre-existing subtitles to the queues + goto dealloc; + } } } - m = (i+j)>>1; + m = (i + j) >> 1; if (timecode < mf->Cues[m].Time) - j = m-1; + j = m - 1; else - i = m+1; + i = m + 1; } + +dealloc: + if (subPreQueues) + QsStructFree(mf, subPreQueues); } void mkv_SkipToKeyframe(MatroskaFile *mf) { @@ -3110,8 +3661,8 @@ void mkv_SkipToKeyframe(MatroskaFile *mf) { for (n=0;nnTracks;++n) if (mf->Queues[n].head && !(mf->Queues[n].head->flags & FRAME_KF)) { - ++wait; - QFree(mf,QGet(&mf->Queues[n])); + ++wait; + QFree(mf,QGet(&mf->Queues[n])); } } while (wait); @@ -3129,11 +3680,11 @@ void mkv_SkipToKeyframe(MatroskaFile *mf) { for (n=0;nnTracks;++n) while (mf->Queues[n].head && mf->Queues[n].head->next && - (mf->Queues[n].head->next->flags & FRAME_KF) && - ht - mf->Queues[n].head->Start > 100000000) + (mf->Queues[n].head->next->flags & FRAME_KF) && + ht - mf->Queues[n].head->Start > 100000000) { - ++wait; - QFree(mf,QGet(&mf->Queues[n])); + ++wait; + QFree(mf,QGet(&mf->Queues[n])); } } while (wait); @@ -3151,7 +3702,7 @@ ulonglong mkv_GetLowestQTimecode(MatroskaFile *mf) { return seen ? t : (ulonglong)LL(-1); } -int mkv_TruncFloat(MKFLOAT f) { +int mkv_TruncFloat(MKFLOAT f) { #ifdef MATROSKA_INTEGER_ONLY return (int)(f.v >> 32); #else @@ -3159,10 +3710,10 @@ int mkv_TruncFloat(MKFLOAT f) { #endif } -#define FTRACK 0xFFFFFFFFFFFFFFFF +#define FTRACK 0xffffffff -void mkv_SetTrackMask(MatroskaFile *mf,unsigned long mask) { - unsigned int i; +void mkv_SetTrackMask(MatroskaFile *mf,ulonglong mask) { + unsigned int i; if (mf->flags & MPF_ERROR) return; @@ -3170,18 +3721,17 @@ void mkv_SetTrackMask(MatroskaFile *mf,unsigned long mask) { mf->trackMask = mask; for (i=0;inTracks;++i) - if (mask & (1l<Queues[i]); } -int mkv_ReadFrame(MatroskaFile *mf, - unsigned int mask,unsigned int *track, - ulonglong *StartTime,ulonglong *EndTime, - ulonglong *FilePos,unsigned int *FrameSize, - unsigned int *FrameFlags) +int mkv_ReadFrame(MatroskaFile *mf, + ulonglong mask,unsigned int *track, + ulonglong *StartTime,ulonglong *EndTime, + ulonglong *FilePos,unsigned int *FrameSize, + char **FrameData,unsigned int *FrameFlags, longlong *FrameDiscard) { - unsigned int i; - unsigned long j; + unsigned int i,j; struct QueueEntry *qe; if (setjmp(mf->jb)!=0) @@ -3190,16 +3740,16 @@ int mkv_ReadFrame(MatroskaFile *mf, do { // extract required frame, use block with the lowest timecode for (j=FTRACK,i=0;inTracks;++i) - if (!(mask & (1l<Queues[i].head) { - j = i; - ++i; - break; + if (!(mask & (ULL(1)<Queues[i].head) { + j = i; + ++i; + break; } for (;inTracks;++i) - if (!(mask & (1<Queues[i].head && - mf->Queues[j].head->Start > mf->Queues[i].head->Start) - j = i; + if (!(mask & (ULL(1)<Queues[i].head && + mf->Queues[j].head->Start > mf->Queues[i].head->Start) + j = i; if (j != FTRACK) { qe = QGet(&mf->Queues[j]); @@ -3209,8 +3759,11 @@ int mkv_ReadFrame(MatroskaFile *mf, *EndTime = qe->End; *FilePos = qe->Position; *FrameSize = qe->Length; + *FrameData = qe->Data; *FrameFlags = qe->flags; + *FrameDiscard = qe->DiscardPadding; + qe->Data = NULL; QFree(mf,qe); return 0; @@ -3229,31 +3782,30 @@ int mkv_ReadFrame(MatroskaFile *mf, * Compressed streams support ************************************************************************/ struct CompressedStream { - MatroskaFile *mf; - z_stream zs; + MatroskaFile *mf; + z_stream zs; /* current compressed frame */ - ulonglong frame_pos; - unsigned frame_size; - char frame_buffer[2048]; + unsigned frame_size; + char *frame_buffer; /* decoded data buffer */ - char decoded_buffer[2048]; - unsigned decoded_ptr; - unsigned decoded_size; + char decoded_buffer[2048]; + unsigned decoded_ptr; + unsigned decoded_size; /* error handling */ - char errmsg[128]; + char errmsg[128]; }; -CompressedStream *cs_Create(/* in */ MatroskaFile *mf, - /* in */ unsigned tracknum, - /* out */ char *errormsg, - /* in */ unsigned msgsize) +CompressedStream *cs_Create(/* in */ MatroskaFile *mf, + /* in */ unsigned tracknum, + /* out */ char *errormsg, + /* in */ unsigned msgsize) { CompressedStream *cs; - TrackInfo *ti; - int code; + TrackInfo *ti; + int code; ti = mkv_GetTrackInfo(mf, tracknum); if (ti == NULL) { @@ -3292,7 +3844,7 @@ CompressedStream *cs_Create(/* in */ MatroskaFile *mf, return cs; } -void cs_Destroy(/* in */ CompressedStream *cs) { +void cs_Destroy(/* in */ CompressedStream *cs) { if (cs == NULL) return; @@ -3302,32 +3854,32 @@ void cs_Destroy(/* in */ CompressedStream *cs) { /* advance to the next frame in matroska stream, you need to pass values returned * by mkv_ReadFrame */ -void cs_NextFrame(/* in */ CompressedStream *cs, - /* in */ ulonglong pos, - /* in */ unsigned size) +void cs_NextFrame(/* in */ CompressedStream *cs, + /* in */ unsigned size, + /* in */ char *frame_data) { cs->zs.avail_in = 0; inflateReset(&cs->zs); - cs->frame_pos = pos; cs->frame_size = size; + cs->frame_buffer = frame_data; cs->decoded_ptr = cs->decoded_size = 0; } /* read and decode more data from current frame, return number of bytes decoded, * 0 on end of frame, or -1 on error */ -int cs_ReadData(CompressedStream *cs,char *buffer,unsigned bufsize) +int cs_ReadData(CompressedStream *cs,char *buffer,unsigned bufsize) { - char *cp = buffer; + char *cp = buffer; unsigned rd = 0; unsigned todo; - int code; - + int code; + do { /* try to copy data from decoded buffer */ if (cs->decoded_ptr < cs->decoded_size) { todo = cs->decoded_size - cs->decoded_ptr;; if (todo > bufsize - rd) - todo = bufsize - rd; + todo = bufsize - rd; memcpy(cp, cs->decoded_buffer + cs->decoded_ptr, todo); @@ -3341,32 +3893,24 @@ int cs_ReadData(CompressedStream *cs,char *buffer,unsigned bufsize) /* try to read more data */ if (cs->zs.avail_in == 0 && cs->frame_size > 0) { - todo = cs->frame_size; - if (todo > sizeof(cs->frame_buffer)) - todo = sizeof(cs->frame_buffer); + todo = cs->frame_size; - if (cs->mf->cache->read(cs->mf->cache, cs->frame_pos, cs->frame_buffer, todo) != (int)todo) { - mystrlcpy(cs->errmsg, "File read failed", sizeof(cs->errmsg)); - return -1; - } + cs->zs.next_in = (Bytef *)cs->frame_buffer; + cs->zs.avail_in = todo; - cs->zs.next_in = (Bytef *)cs->frame_buffer; - cs->zs.avail_in = todo; - - cs->frame_pos += todo; - cs->frame_size -= todo; + cs->frame_size = 0; } /* try to decode more data */ code = inflate(&cs->zs,Z_NO_FLUSH); if (code != Z_OK && code != Z_STREAM_END) { - mystrlcpy(cs->errmsg, "ZLib error.", sizeof(cs->errmsg)); - return -1; + mystrlcpy(cs->errmsg, "ZLib error.", sizeof(cs->errmsg)); + return -1; } /* handle decoded data */ if (cs->zs.avail_out == sizeof(cs->decoded_buffer)) /* EOF */ - break; + break; cs->decoded_ptr = 0; cs->decoded_size = sizeof(cs->decoded_buffer) - cs->zs.avail_out; @@ -3377,7 +3921,7 @@ int cs_ReadData(CompressedStream *cs,char *buffer,unsigned bufsize) } /* return error message for the last error */ -const char *cs_GetLastError(CompressedStream *cs) +const char *cs_GetLastError(CompressedStream *cs) { if (!cs->errmsg[0]) return NULL; diff --git a/MP42/muxer/MatroskaParser.h b/MP42/muxer/MatroskaParser.h index 94a7426..6b15422 100644 --- a/MP42/muxer/MatroskaParser.h +++ b/MP42/muxer/MatroskaParser.h @@ -24,13 +24,13 @@ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * + * * $Id: MatroskaParser.h,v 1.22 2008/04/29 21:03:09 mike Exp $ - * + * */ #ifndef MATROSKA_PARSER_H -#define MATROSKA_PARSER_H +#define MATROSKA_PARSER_H /* Random notes: * @@ -42,7 +42,7 @@ */ #ifdef MPDLLBUILD -#define X __declspec(dllexport) +#define X __declspec(dllexport) #else #ifdef MPDLL #define X __declspec(dllimport) @@ -53,7 +53,7 @@ #endif #define MATROSKA_COMPRESSION_SUPPORT -#define MATROSKA_INTEGER_ONLY +//#define MATROSKA_INTEGER_ONLY #ifdef __cplusplus extern "C" { @@ -61,7 +61,7 @@ extern "C" { /* 64-bit integers */ #ifdef _WIN32_WCE -typedef signed __int64 longlong; +typedef signed __int64 longlong; typedef unsigned __int64 ulonglong; #else typedef signed long long longlong; @@ -71,16 +71,16 @@ typedef unsigned long long ulonglong; /* MKFLOATing point */ #ifdef MATROSKA_INTEGER_ONLY typedef struct { - longlong v; + longlong v; } MKFLOAT; #else -typedef double MKFLOAT; +typedef double MKFLOAT; #endif /* generic I/O */ struct InputStream { /* read bytes from stream */ - int (*read)(struct InputStream *cc,ulonglong pos,void *buffer,int count); + int (*read)(struct InputStream *cc,ulonglong pos,void *buffer,int count); /* scan for a four byte signature, bytes must be nonzero */ longlong (*scan)(struct InputStream *cc,ulonglong start,unsigned signature); /* get cache size, this is used to cap readahead */ @@ -88,11 +88,11 @@ struct InputStream { /* fetch last error message */ const char *(*geterror)(struct InputStream *cc); /* memory allocation */ - void *(*memalloc)(struct InputStream *cc,size_t size); - void *(*memrealloc)(struct InputStream *cc,void *mem,size_t newsize); - void (*memfree)(struct InputStream *cc,void *mem); + void *(*memalloc)(struct InputStream *cc,size_t size); + void *(*memrealloc)(struct InputStream *cc,void *mem,size_t newsize); + void (*memfree)(struct InputStream *cc,void *mem); /* zero return causes parser to abort open */ - int (*progress)(struct InputStream *cc,ulonglong cur,ulonglong max); + int (*progress)(struct InputStream *cc,ulonglong cur,ulonglong max); /* get file size, optional, can be NULL or return -1 if filesize is unknown */ longlong (*getfilesize)(struct InputStream *cc); }; @@ -104,34 +104,36 @@ struct MatroskaFile; /* opaque */ typedef struct MatroskaFile MatroskaFile; -#define COMP_ZLIB 0 -#define COMP_BZIP 1 -#define COMP_LZO1X 2 -#define COMP_PREPEND 3 +#define COMP_ZLIB 0 +#define COMP_BZIP 1 +#define COMP_LZO1X 2 +#define COMP_PREPEND 3 -#define TT_VIDEO 1 -#define TT_AUDIO 2 -#define TT_SUB 17 +#define TT_VIDEO 1 +#define TT_AUDIO 2 +#define TT_SUB 17 struct TrackInfo { - unsigned char Number; - unsigned char Type; - unsigned char TrackOverlay; - ulonglong UID; - ulonglong MinCache; - ulonglong MaxCache; - ulonglong DefaultDuration; - MKFLOAT TimecodeScale; - void *CodecPrivate; - unsigned CodecPrivateSize; - unsigned int CodecDelay; - unsigned CompMethod; - void *CompMethodPrivate; - unsigned CompMethodPrivateSize; - unsigned MaxBlockAdditionID; + unsigned char Number; + unsigned char Type; + unsigned char TrackOverlay; + ulonglong UID; + ulonglong MinCache; + ulonglong MaxCache; + ulonglong DefaultDuration; + ulonglong CodecDelay; + ulonglong SeekPreRoll; + MKFLOAT TimecodeScale; + void *CodecPrivate; + unsigned CodecPrivateSize; + unsigned CompMethod; + void *CompMethodPrivate; + unsigned CompMethodPrivateSize; + unsigned MaxBlockAdditionID; unsigned int Enabled:1; unsigned int Default:1; + unsigned int Forced:1; unsigned int Lacing:1; unsigned int DecodeAll:1; unsigned int CompEnabled:1; @@ -147,129 +149,162 @@ struct TrackInfo { unsigned int DisplayHeight; unsigned int CropL, CropT, CropR, CropB; unsigned int ColourSpace; - MKFLOAT GammaValue; - + MKFLOAT GammaValue; struct { - unsigned int MatrixCoefficients; - unsigned int BitsPerChannel; - unsigned int TransferCharacteristics; - unsigned int Primaries; + unsigned int MatrixCoefficients; + unsigned int BitsPerChannel; + unsigned int ChromaSubsamplingHorz; + unsigned int ChromaSubsamplingVert; + unsigned int CbSubsamplingHorz; + unsigned int CbSubsamplingVert; + unsigned int ChromaSitingHorz; + unsigned int ChromaSitingVert; + unsigned int Range; + unsigned int TransferCharacteristics; + unsigned int Primaries; + unsigned int MaxCLL; + unsigned int MaxFALL; + struct { + float PrimaryRChromaticityX; + float PrimaryRChromaticityY; + float PrimaryGChromaticityX; + float PrimaryGChromaticityY; + float PrimaryBChromaticityX; + float PrimaryBChromaticityY; + float WhitePointChromaticityX; + float WhitePointChromaticityY; + float LuminanceMax; + float LuminanceMin; + } MasteringMetadata; } Colour; unsigned int Interlaced:1; } Video; struct { - MKFLOAT SamplingFreq; - MKFLOAT OutputSamplingFreq; + MKFLOAT SamplingFreq; + MKFLOAT OutputSamplingFreq; unsigned char Channels; unsigned char BitDepth; } Audio; } AV; /* various strings */ - char *Name; - char Language[4]; - char *CodecID; + char *Name; + char Language[4]; + char *CodecID; + + unsigned int NeedKeyframes; }; typedef struct TrackInfo TrackInfo; struct SegmentInfo { - char UID[16]; - char PrevUID[16]; - char NextUID[16]; - char *Filename; - char *PrevFilename; - char *NextFilename; - char *Title; - char *MuxingApp; - char *WritingApp; - ulonglong TimecodeScale; - ulonglong Duration; - longlong DateUTC; - char DateUTCValid; + char UID[16]; + char PrevUID[16]; + char NextUID[16]; + char *Filename; + char *PrevFilename; + char *NextFilename; + char *Title; + char *MuxingApp; + char *WritingApp; + ulonglong TimecodeScale; + ulonglong Duration; + longlong DateUTC; + char DateUTCValid; }; typedef struct SegmentInfo SegmentInfo; struct Attachment { - ulonglong Position; - ulonglong Length; - ulonglong UID; - char *Name; - char *Description; - char *MimeType; + ulonglong Position; + ulonglong Length; + ulonglong UID; + char *Name; + char *Description; + char *MimeType; }; typedef struct Attachment Attachment; struct ChapterDisplay { - char *String; - char Language[4]; - char Country[4]; + char *String; + char Language[4]; + char Country[4]; }; struct ChapterCommand { - unsigned Time; - unsigned CommandLength; - void *Command; + unsigned Time; + unsigned CommandLength; + void *Command; }; struct ChapterProcess { - unsigned CodecID; - unsigned CodecPrivateLength; - void *CodecPrivate; - unsigned nCommands,nCommandsSize; - struct ChapterCommand *Commands; + unsigned CodecID; + unsigned CodecPrivateLength; + void *CodecPrivate; + unsigned nCommands,nCommandsSize; + struct ChapterCommand *Commands; }; struct Chapter { - ulonglong UID; - ulonglong Start; - ulonglong End; + ulonglong UID; + ulonglong Start; + ulonglong End; - unsigned nTracks,nTracksSize; - ulonglong *Tracks; - unsigned nDisplay,nDisplaySize; - struct ChapterDisplay *Display; - unsigned nChildren,nChildrenSize; - struct Chapter *Children; - unsigned nProcess,nProcessSize; - struct ChapterProcess *Process; + unsigned nTracks,nTracksSize; + ulonglong *Tracks; + unsigned nDisplay,nDisplaySize; + struct ChapterDisplay *Display; + unsigned nChildren,nChildrenSize; + struct Chapter *Children; + unsigned nProcess,nProcessSize; + struct ChapterProcess *Process; - char SegmentUID[16]; + char SegmentUID[16]; - unsigned int Hidden:1; - unsigned int Enabled:1; + unsigned int Hidden:1; + unsigned int Enabled:1; // Editions - unsigned int Default:1; - unsigned int Ordered:1; + unsigned int Default:1; + unsigned int Ordered:1; }; -typedef struct Chapter Chapter; +typedef struct Chapter Chapter; -#define TARGET_TRACK 0 -#define TARGET_CHAPTER 1 -#define TARGET_ATTACHMENT 2 -#define TARGET_EDITION 3 +struct Cue { + ulonglong Time; + ulonglong Duration; + ulonglong Position; + ulonglong RelativePosition; + ulonglong Block; + unsigned char Track; +}; + +typedef struct Cue Cue; + +#define TARGET_TRACK 0 +#define TARGET_CHAPTER 1 +#define TARGET_ATTACHMENT 2 +#define TARGET_EDITION 3 struct Target { - ulonglong UID; - unsigned Type; + ulonglong UID; + unsigned Type; }; struct SimpleTag { - char *Name; - char *Value; - char Language[4]; - unsigned Default:1; + char *Name; + char *Value; + char Language[4]; + unsigned Default:1; }; struct Tag { - unsigned nTargets,nTargetsSize; - struct Target *Targets; + unsigned nTargets,nTargetsSize; + struct Target *Targets; - unsigned nSimpleTags,nSimpleTagsSize; + unsigned nSimpleTags,nSimpleTagsSize; struct SimpleTag *SimpleTags; }; @@ -279,21 +314,26 @@ typedef struct Tag Tag; * io pointer is recorded inside MatroskaFile */ X MatroskaFile *mkv_Open(/* in */ InputStream *io, - /* out */ char *err_msg, - /* in */ unsigned msgsize); + /* out */ char *err_msg, + /* in */ unsigned msgsize); -#define MKVF_AVOID_SEEKS 1 /* use sequential reading only */ +#define MKVF_AVOID_SEEKS 1 /* use sequential reading only */ X MatroskaFile *mkv_OpenEx(/* in */ InputStream *io, - /* in */ ulonglong base, - /* in */ unsigned flags, - /* out */ char *err_msg, - /* in */ unsigned msgsize); + /* in */ ulonglong base, + /* in */ unsigned flags, + /* out */ char *err_msg, + /* in */ unsigned msgsize); + +/* Open the file and only parse enough information to find the segment uid */ +X MatroskaFile *mkv_OpenSparse(/* in */ InputStream *io, + /* out */ char *err_msg, + /* in */ unsigned msgsize); /* Close and deallocate mf * NULL pointer is ok and is simply ignored */ -X void mkv_Close(/* in */ MatroskaFile *mf); +X void mkv_Close(/* in */ MatroskaFile *mf); /* Fetch the error message of the last failed operation */ X const char *mkv_GetLastError(/* in */ MatroskaFile *mf); @@ -306,15 +346,17 @@ X unsigned int mkv_GetNumTracks(/* in */ MatroskaFile *mf); X TrackInfo *mkv_GetTrackInfo(/* in */ MatroskaFile *mf,/* in */ unsigned track); /* chapters, tags and attachments */ -X void mkv_GetAttachments(/* in */ MatroskaFile *mf, - /* out */ Attachment **at, - /* out */ unsigned *count); -X void mkv_GetChapters(/* in */ MatroskaFile *mf, - /* out */ Chapter **ch, - /* out */ unsigned *count); -X void mkv_GetTags(/* in */ MatroskaFile *mf, - /* out */ Tag **tag, - /* out */ unsigned *count); +X void mkv_GetAttachments(/* in */ MatroskaFile *mf, + /* out */ Attachment **at, + /* out */ unsigned *count); +X void mkv_GetChapters(/* in */ MatroskaFile *mf, + /* out */ Chapter **ch, + /* out */ unsigned *count); +X void mkv_GetTags(/* in */ MatroskaFile *mf, + /* out */ Tag **tag, + /* out */ unsigned *count); + +X void mkv_GetCues(MatroskaFile *mf, Cue **cue, unsigned *count); X ulonglong mkv_GetSegmentTop(MatroskaFile *mf); @@ -323,51 +365,55 @@ X ulonglong mkv_GetSegmentTop(MatroskaFile *mf); * all tracks are set to return EOF * on next read */ -#define MKVF_SEEK_TO_PREV_KEYFRAME 1 -#define MKVF_SEEK_TO_PREV_KEYFRAME_STRICT 2 +#define MKVF_SEEK_TO_PREV_KEYFRAME 1 +#define MKVF_SEEK_TO_PREV_KEYFRAME_STRICT 2 -X void mkv_Seek(/* in */ MatroskaFile *mf, - /* in */ ulonglong timecode /* in ns */, - /* in */ unsigned flags); +X void mkv_Seek(/* in */ MatroskaFile *mf, + /* in */ ulonglong timecode /* in ns */, + /* in */ unsigned flags); -X void mkv_SkipToKeyframe(MatroskaFile *mf); +X void mkv_Seek_CueAware(MatroskaFile *mf, ulonglong timecode, unsigned flags, unsigned fuzzy); + +X void mkv_SkipToKeyframe(MatroskaFile *mf); X ulonglong mkv_GetLowestQTimecode(MatroskaFile *mf); -X int mkv_TruncFloat(MKFLOAT f); +X int mkv_TruncFloat(MKFLOAT f); /************************************************************************* * reading data, pull model */ /* frame flags */ -#define FRAME_UNKNOWN_START 0x00000001 -#define FRAME_UNKNOWN_END 0x00000002 -#define FRAME_KF 0x00000004 -#define FRAME_GAP 0x00800000 -#define FRAME_STREAM_MASK 0xff000000 -#define FRAME_STREAM_SHIFT 24 +#define FRAME_UNKNOWN_START 0x00000001 +#define FRAME_UNKNOWN_END 0x00000002 +#define FRAME_KF 0x00000004 +#define FRAME_GAP 0x00800000 +#define FRAME_STREAM_MASK 0xff000000 +#define FRAME_STREAM_SHIFT 24 /* This sets the masking flags for the parser, * masked tracks [with 1s in their bit positions] * will be ignored when reading file data. * This call discards all parsed and queued frames */ -X void mkv_SetTrackMask(/* in */ MatroskaFile *mf,/* in */ unsigned long mask); +X void mkv_SetTrackMask(/* in */ MatroskaFile *mf,/* in */ ulonglong mask); /* Read one frame from the queue. * mask specifies what tracks to ignore. * Returns -1 if there are no more frames in the specified * set of tracks, 0 on success */ -X int mkv_ReadFrame(/* in */ MatroskaFile *mf, - /* in */ unsigned int mask, - /* out */ unsigned int *track, - /* out */ ulonglong *StartTime /* in ns */, - /* out */ ulonglong *EndTime /* in ns */, - /* out */ ulonglong *FilePos /* in bytes from start of file */, - /* out */ unsigned int *FrameSize /* in bytes */, - /* out */ unsigned int *FrameFlags); +X int mkv_ReadFrame(/* in */ MatroskaFile *mf, + /* in */ ulonglong mask, + /* out */ unsigned int *track, + /* out */ ulonglong *StartTime /* in ns */, + /* out */ ulonglong *EndTime /* in ns */, + /* out */ ulonglong *FilePos /* in bytes from start of file */, + /* out */ unsigned int *FrameSize /* in bytes */, + /* out */ char **FrameData, + /* out */ unsigned int *FrameFlags, + /* out */ longlong *FrameDiscard); #ifdef MATROSKA_COMPRESSION_SUPPORT /* Compressed streams support */ @@ -375,24 +421,24 @@ struct CompressedStream; typedef struct CompressedStream CompressedStream; -X CompressedStream *cs_Create(/* in */ MatroskaFile *mf, - /* in */ unsigned tracknum, - /* out */ char *errormsg, - /* in */ unsigned msgsize); -X void cs_Destroy(/* in */ CompressedStream *cs); +X CompressedStream *cs_Create(/* in */ MatroskaFile *mf, + /* in */ unsigned tracknum, + /* out */ char *errormsg, + /* in */ unsigned msgsize); +X void cs_Destroy(/* in */ CompressedStream *cs); /* advance to the next frame in matroska stream, you need to pass values returned * by mkv_ReadFrame */ -X void cs_NextFrame(/* in */ CompressedStream *cs, - /* in */ ulonglong pos, - /* in */ unsigned size); +X void cs_NextFrame(/* in */ CompressedStream *cs, + /* in */ unsigned size, + /* in */ char *frame_data); /* read and decode more data from current frame, return number of bytes decoded, * 0 on end of frame, or -1 on error */ -X int cs_ReadData(CompressedStream *cs,char *buffer,unsigned bufsize); +X int cs_ReadData(CompressedStream *cs,char *buffer,unsigned bufsize); /* return error message for the last error */ -X const char *cs_GetLastError(CompressedStream *cs); +X const char *cs_GetLastError(CompressedStream *cs); #endif #ifdef __cplusplus