From 2a75f36676d4da55cd4eb704325e5f6c2dc0782e Mon Sep 17 00:00:00 2001 From: Brian Gerfort Date: Fri, 5 May 2017 14:58:40 +0200 Subject: [PATCH 1/4] * Grab chapter previews from the middle of the chapter instead of the very beginning. --- MP42/MP42PreviewGenerator.m | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/MP42/MP42PreviewGenerator.m b/MP42/MP42PreviewGenerator.m index beb30d8..a3a4935 100644 --- a/MP42/MP42PreviewGenerator.m +++ b/MP42/MP42PreviewGenerator.m @@ -20,7 +20,7 @@ return images; } -+ (NSArray *)generatePreviewImagesAVFoundationFromChapters:(NSArray *)chapters andFile:(NSURL *)file { ++ (NSArray *)generatePreviewImagesAVFoundationFromChapters:(NSArray *)chapters andFile:(NSURL *)file { NSMutableArray *images = [[NSMutableArray alloc] initWithCapacity:[chapters count]]; AVAsset *asset = [AVAsset assetWithURL:file]; @@ -32,8 +32,13 @@ generator.requestedTimeToleranceBefore = kCMTimeZero; generator.requestedTimeToleranceAfter = kCMTimeZero; - for (MP42TextSample *chapter in chapters) { - CMTime time = CMTimeMake([chapter timestamp] + 1800, 1000); + CGFloat thumbnailPosition = 0.5; // Middle of chapter + + for (NSInteger idx = 0; idx < chapters.count; idx++) + { + MP42TextSample *chapter = chapters[idx]; + MP42Duration nextChapterTimestamp = (idx < chapters.count - 1) ? [chapters[idx+1] timestamp] : CMTimeGetSeconds(asset.duration) * 1000; + CMTime time = CMTimeMake([chapter timestamp] + ((nextChapterTimestamp - [chapter timestamp]) * thumbnailPosition), 1000); CGImageRef imgRef = [generator copyCGImageAtTime:time actualTime:NULL error:NULL]; if (imgRef) { NSSize size = NSMakeSize(CGImageGetWidth(imgRef), CGImageGetHeight(imgRef)); From 5e821d87f69baff2c6df7cd52fcabda92f9b9099 Mon Sep 17 00:00:00 2001 From: Brian Gerfort Date: Fri, 5 May 2017 15:41:25 +0200 Subject: [PATCH 2/4] * Support for DTS to AC3 + AAC conversion. If you prefer to recompile FFmpeg from scratch, make sure you include the --enable-encoder=ac3 and --disable-iconv parameters. My config: ./configure --disable-programs --disable-filters --disable-everything --disable-avdevice --disable-swscale --enable-avresample --enable-decoder=dvdsub --enable-decoder=pgssub --enable-decoder=aac --enable-decoder=mp3 --enable-decoder=mp2 --enable-decoder=mp1 --enable-decoder=ac3 --enable-decoder=eac3 --enable-decoder=truehd --enable-decoder=alac --enable-decoder=opus --enable-decoder=vorbis --enable-decoder=flac --enable-decoder=mlp --enable-decoder=dca --enable-decoder=pcm --enable-filter=aresample --enable-parser=opus --enable-muxer=opus --prefix=/Users/damians/Desktop/iffmpeg --extra-cxxflags='-mmacosx-version-min=10.9' --extra-cflags='-mmacosx-version-min=10.9' --extra-ldflags='-mmacosx-version-min=10.9' --enable-decoder=pcm_f32be --enable-decoder=pcm_f32le --enable-decoder=pcm_f64be --enable-decoder=pcm_f64le --enable-decoder=pcm_s16be --enable-decoder=pcm_s16le --enable-decoder=pcm_s16le_planar --enable-decoder=pcm_s24be --enable-decoder=pcm_daud --enable-decoder=pcm_s24le --enable-decoder=pcm_s32be --enable-decoder=pcm_s32le --enable-decoder=pcm_s8 --enable-decoder=pcm_u8 --enable-decoder=pcm_u16be --enable-decoder=pcm_u16le --enable-decoder=pcm_u24be --enable-decoder=pcm_u24le --enable-encoder=ac3 --disable-iconv --- MP42/FFmpegUtils.h | 2 + MP42/FFmpegUtils.m | 29 ++ MP42/MP42AC3AudioEncoder.h | 33 ++ MP42/MP42AC3AudioEncoder.m | 408 +++++++++++++++++++++++ MP42/MP42AudioConverter.m | 18 +- MP42/MP42AudioTrack.m | 17 + MP42/MP42ConversionSettings.h | 2 + MP42/MP42File.m | 3 +- MP42/MP42Muxer.m | 66 ++++ MP42/MP42Utilities.h | 2 + MP42/MP42Utilities.m | 35 ++ MP42Foundation.xcodeproj/project.pbxproj | 8 + 12 files changed, 617 insertions(+), 6 deletions(-) create mode 100644 MP42/MP42AC3AudioEncoder.h create mode 100644 MP42/MP42AC3AudioEncoder.m diff --git a/MP42/FFmpegUtils.h b/MP42/FFmpegUtils.h index 195934d..8676344 100644 --- a/MP42/FFmpegUtils.h +++ b/MP42/FFmpegUtils.h @@ -22,4 +22,6 @@ OSType CodecIDToFourCC(enum AVCodecID codecID); int remap_layout(AudioChannelLayout *layout, uint64_t in_layout, int count); int convert_layout_to_av(AudioChannelLayout *layout, UInt32 layoutSize); +int channel_layout_for_channels(AVCodec *codec, int channels); + #endif /* FFmpegUtils_h */ diff --git a/MP42/FFmpegUtils.m b/MP42/FFmpegUtils.m index 0fa659a..aaa0499 100644 --- a/MP42/FFmpegUtils.m +++ b/MP42/FFmpegUtils.m @@ -17,6 +17,10 @@ extern AVCodec ff_##x##_decoder; \ avcodec_register(&ff_##x##_decoder); } +#define REGISTER_ENCODER(x) { \ +extern AVCodec ff_##x##_encoder; \ +avcodec_register(&ff_##x##_encoder); } + static int ff_lockmgr_cb(void **mutex, enum AVLockOp op) { switch (op) { @@ -83,6 +87,7 @@ void FFInitFFmpeg() REGISTER_DECODER(pcm_u16le); REGISTER_DECODER(pcm_u24be); REGISTER_DECODER(pcm_u24le); + REGISTER_ENCODER(ac3); }); } @@ -327,3 +332,27 @@ done: free(layout_copy); return layout_mask; } + +int channel_layout_for_channels(AVCodec *codec, int channels) +{ + const uint64_t *p; + uint64_t best_ch_layout = 0; + int best_nb_channells = 0; + + if (!codec->channel_layouts) + return AV_CH_LAYOUT_STEREO; + + p = codec->channel_layouts; + while (*p) { + int nb_channels = av_get_channel_layout_nb_channels(*p); + + if (nb_channels == channels) return *p; + + if (nb_channels > best_nb_channells) { + best_ch_layout = *p; + best_nb_channells = nb_channels; + } + p++; + } + return best_ch_layout; +} diff --git a/MP42/MP42AC3AudioEncoder.h b/MP42/MP42AC3AudioEncoder.h new file mode 100644 index 0000000..796b6c1 --- /dev/null +++ b/MP42/MP42AC3AudioEncoder.h @@ -0,0 +1,33 @@ +// +// MP42AC3AudioEncoder.h +// MP42Foundation +// +// Created by Damiano Galassi on 23/07/2016. +// Copyright © 2016 Damiano Galassi. All rights reserved. +// + +#import + +#import "MP42AudioUnit.h" + +@class MP42SampleBuffer; + +NS_ASSUME_NONNULL_BEGIN + +@interface MP42AC3AudioEncoder : NSObject + +- (instancetype)initWithInputUnit:(id)unit bitRate:(NSUInteger)bitRate error:(NSError **)error; + +@property (nonatomic, readonly, nullable) AudioChannelLayout *inputLayout; +@property (nonatomic, readonly) UInt32 inputLayoutSize; +@property (nonatomic, readonly) AudioStreamBasicDescription inputFormat; + +@property (nonatomic, readonly, nullable) AudioChannelLayout *outputLayout; +@property (nonatomic, readonly) UInt32 outputLayoutSize; +@property (nonatomic, readonly) AudioStreamBasicDescription outputFormat; + +@property (nonatomic, readonly) NSData *magicCookie; + +@end + +NS_ASSUME_NONNULL_END diff --git a/MP42/MP42AC3AudioEncoder.m b/MP42/MP42AC3AudioEncoder.m new file mode 100644 index 0000000..0cade45 --- /dev/null +++ b/MP42/MP42AC3AudioEncoder.m @@ -0,0 +1,408 @@ +// +// MP42AC3AudioEncoder.m +// MP42Foundation +// +// Created by Damiano Galassi on 23/07/2016. +// Copyright © 2016 Damiano Galassi. All rights reserved. +// + +#import "MP42AC3AudioEncoder.h" +#import "MP42Fifo.h" +#import "MP42Sample.h" +#import "MP42PrivateUtilities.h" +#include "sfifo.h" +#include "FFmpegUtils.h" + +#define FIFO_DURATION (2.5f) + +// A struct to hold info for the data proc +typedef struct AudioFileIO +{ + sfifo_t *ringBuffer; + + float *inBuffer; + UInt32 inBufferSize; + + UInt32 outputMaxSize; + + UInt32 inSizePerPacket; + UInt32 inSamples; + UInt32 channelsPerFrame; + UInt32 numPacketsPerRead; + + AVFrame *frame; + float *samples; + + UInt64 outputPos; + + bool done; + + AudioStreamPacketDescription * _Nullable pktDescs; +} AudioFileIO; + +@interface MP42AC3AudioEncoder () +{ + AVCodecContext *_avctx; + + __unsafe_unretained id _outputUnit; + MP42AudioUnitOutput _outputType; + + NSData *_magicCookie; +} + +@property (nonatomic, readonly) NSUInteger bitrate; + +@property (nonatomic, readonly) NSThread *decoderThread; +@property (nonatomic, readonly) MP42Fifo *inputSamplesBuffer; +@property (nonatomic, readonly) MP42Fifo *outputSamplesBuffer; + +@property (nonatomic, readonly) sfifo_t *ringBuffer; +@property (nonatomic, readonly) AudioFileIO *afio; + +@property (nonatomic, readonly, unsafe_unretained) id inputUnit; + +@end + +@implementation MP42AC3AudioEncoder + +@synthesize outputUnit = _outputUnit; +@synthesize outputType = _outputType; + +@synthesize magicCookie = _magicCookie; + +- (instancetype)initWithInputUnit:(id)unit bitRate:(NSUInteger)bitRate error:(NSError **)error +{ + self = [super init]; + if (self) { + _inputUnit = unit; + _inputUnit.outputUnit = self; + _inputFormat = unit.outputFormat; + + _bitrate = bitRate; + + _inputSamplesBuffer = [[MP42Fifo alloc] initWithCapacity:100]; + _outputSamplesBuffer = [[MP42Fifo alloc] initWithCapacity:100]; + + [self start]; + } + return self; +} + +- (void)dealloc +{ + [self disposeConverter]; +} + +#pragma mark - Encoder Init + +- (BOOL)initConverterWithBitRate:(NSUInteger)bitrate +{ + AVCodec *codec = avcodec_find_encoder(AV_CODEC_ID_AC3); + if (!codec) { + if ([[NSString stringWithFormat:@"%s", avcodec_configuration()] rangeOfString:@"--enable-encoder=ac3"].location == NSNotFound) { + NSLog(@"Codec not found. Compile ffmpeg with configuration: %s --enable-encoder=ac3", avcodec_configuration()); + } + else { + NSLog(@"Codec not found. Have you registered the encoder with avcodec_register() or avcodec_register_all()?"); + } + return NO; + } + + _avctx = avcodec_alloc_context3(codec); + if (!_avctx) { + NSLog(@"Could not allocate audio codec context"); + return NO; + } + + _avctx->bit_rate = (!bitrate) ? 640000 : bitrate * 1000; + _avctx->sample_fmt = AV_SAMPLE_FMT_FLTP; + _avctx->sample_rate = 48000; + + _avctx->channel_layout = channel_layout_for_channels(codec, _inputFormat.mChannelsPerFrame); + _avctx->channels = av_get_channel_layout_nb_channels(_avctx->channel_layout); + + AudioStreamBasicDescription outputFormat; + bzero(&outputFormat, sizeof(AudioStreamBasicDescription)); + outputFormat.mFormatID = kAudioFormatAC3; + outputFormat.mSampleRate = _avctx->sample_rate; + outputFormat.mChannelsPerFrame = _avctx->channels; + outputFormat.mFramesPerPacket = 1536; + outputFormat.mBytesPerPacket = 4 * outputFormat.mChannelsPerFrame; + outputFormat.mBytesPerFrame = outputFormat.mBytesPerPacket * outputFormat.mFramesPerPacket; + outputFormat.mBitsPerChannel = 16; + outputFormat.mFormatFlags = kAudioFormatFlagIsFloat; + _outputFormat = outputFormat; + + if (avcodec_open2(_avctx, codec, NULL) < 0) { + NSLog(@"Could not open codec"); + return NO; + } + + _ringBuffer = (sfifo_t *) malloc(sizeof(sfifo_t)); + int ringbuffer_len = _inputFormat.mSampleRate * FIFO_DURATION * 4 * 23; + sfifo_init(_ringBuffer, ringbuffer_len); + + _afio = malloc(sizeof(AudioFileIO)); + bzero(_afio, sizeof(AudioFileIO)); + + _afio->inBufferSize = 1024 * 64; + _afio->inBuffer = malloc(_afio->inBufferSize); + + _afio->outputMaxSize = _afio->inBufferSize; + + _afio->inSizePerPacket = _inputFormat.mBytesPerPacket; + _afio->inSamples = _outputFormat.mFramesPerPacket; + _afio->channelsPerFrame = _inputFormat.mChannelsPerFrame; + _afio->numPacketsPerRead = _afio->inBufferSize / _afio->inSizePerPacket; + + _afio->ringBuffer = _ringBuffer; + + _afio->frame = av_frame_alloc(); + if (!_afio->frame) { + NSLog(@"Could not allocate audio frame"); + return NO; + } + + _afio->frame->nb_samples = _avctx->frame_size; + _afio->frame->format = _avctx->sample_fmt; + _afio->frame->channel_layout = _avctx->channel_layout; + _afio->frame->channels = _avctx->channels; + + int buffer_size = av_samples_get_buffer_size(NULL, _avctx->channels, _avctx->frame_size, + _avctx->sample_fmt, 0); + _afio->samples = av_malloc(buffer_size); + if (!_afio->samples) { + NSLog(@"Could not allocate %d bytes for samples buffer", buffer_size); + return NO; + } + int ret = avcodec_fill_audio_frame(_afio->frame, _avctx->channels, _avctx->sample_fmt, + (const uint8_t*)_afio->samples, buffer_size, 0); + if (ret < 0) { + NSLog(@"Could not setup audio frame"); + return NO; + } + + return YES; +} + +- (void)disposeConverter +{ + if (_afio) + { + if (_afio->samples) + { + av_freep(&_afio->samples); + } + if (_afio->frame) + { + av_frame_free(&_afio->frame); + } + } + if (_avctx) + { + avcodec_close(_avctx); + av_free(_avctx); + } +} + +- (BOOL)createMagicCookie +{ + uint64_t fscod = 0; + uint64_t bsid = 8; + uint64_t bsmod = 0; + uint64_t acmod = 7; + uint64_t lfeon = (_avctx->channel_layout & AV_CH_LOW_FREQUENCY) ? 1 : 0; + uint64_t bit_rate_code = 15; + + switch (_avctx->channels - lfeon) + { + case 1: + acmod = 1; + break; + case 2: + acmod = 2; + break; + case 3: + if (_avctx->channel_layout & AV_CH_BACK_CENTER) acmod = 3; + else acmod = 4; + break; + case 4: + if (_avctx->channel_layout & AV_CH_BACK_CENTER) acmod = 5; + else acmod = 6; + break; + case 5: + acmod = 7; + break; + default: + break; + } + + if (_avctx->sample_rate == 48000) fscod = 0; + else if (_avctx->sample_rate == 44100) fscod = 1; + else if (_avctx->sample_rate == 32000) fscod = 2; + else fscod = 3; + + NSMutableData *ac3Info = [[NSMutableData alloc] init]; + [ac3Info appendBytes:&fscod length:sizeof(uint64_t)]; + [ac3Info appendBytes:&bsid length:sizeof(uint64_t)]; + [ac3Info appendBytes:&bsmod length:sizeof(uint64_t)]; + [ac3Info appendBytes:&acmod length:sizeof(uint64_t)]; + [ac3Info appendBytes:&lfeon length:sizeof(uint64_t)]; + [ac3Info appendBytes:&bit_rate_code length:sizeof(uint64_t)]; + + _magicCookie = ac3Info; + + return YES; +} + +- (void)start +{ + _decoderThread = [[NSThread alloc] initWithTarget:self selector:@selector(threadMainRoutine) object:nil]; + [_decoderThread setName:@"AudioToolbox Audio Encoder"]; + [_decoderThread start]; +} + +#pragma mark - Public methods + +- (void)reconfigure +{ + [self disposeConverter]; + + _inputFormat = _inputUnit.outputFormat; + _inputLayoutSize = _inputUnit.outputLayoutSize; + _inputLayout = malloc(_inputLayoutSize); + memcpy(_inputLayout, _inputUnit.outputLayout, _inputLayoutSize); + + if (![self initConverterWithBitRate:_bitrate]) { + return; + } + + if (![self createMagicCookie]) { + return; + } +} + +- (NSData *)magicCookie +{ + return _magicCookie; +} + +- (void)addSample:(MP42SampleBuffer *)sample +{ + [_inputSamplesBuffer enqueue:sample]; +} + +- (nullable MP42SampleBuffer *)copyEncodedSample +{ + return [_outputSamplesBuffer dequeue]; +} + +#pragma mark - Encoder + +static MP42SampleBuffer *encode(AVCodecContext *context, AudioFileIO *afio) +{ + UInt32 availableBytes = sfifo_used(afio->ringBuffer); + if (!afio->done && + availableBytes < afio->inSamples * afio->inSizePerPacket) { + return nil; + } + + UInt32 wanted = MIN(afio->inSamples * afio->inSizePerPacket, availableBytes); + UInt32 outNumBytes = sfifo_read(afio->ringBuffer, afio->inBuffer, wanted); + if (outNumBytes == 0) + { + return nil; + } + + // Populate the AVFrame with the samples + float *pEnc = afio->samples; + float *pIn = afio->inBuffer; + int channels = afio->channelsPerFrame; + int samples = context->frame_size; + int outputChannels = context->channels; + for (int ch = 0; ch < channels; ++ch) { + for (int i = 0; i < samples; ++i) { + if (ch < outputChannels) { + *pEnc++ = pIn[channels * i + ch]; + } + } + } + + // Encode + MP42SampleBuffer *sample = nil; + if (avcodec_send_frame(context, afio->frame) == 0) + { + AVPacket *pkt = av_packet_alloc(); + if (avcodec_receive_packet(context, pkt) == 0) + { + sample = [[MP42SampleBuffer alloc] init]; + sample->size = pkt->size; + sample->duration = pkt->duration; + sample->decodeTimestamp = afio->outputPos * pkt->duration; + sample->presentationTimestamp = sample->decodeTimestamp; + sample->presentationOutputTimestamp = sample->decodeTimestamp; + sample->data = malloc(pkt->size); + memcpy(sample->data, pkt->data, pkt->size); + sample->flags |= MP42SampleBufferFlagIsSync; + afio->outputPos += 1; + } + av_packet_free(&pkt); + } + + return sample; +} + +static MP42SampleBuffer *flush(AVCodecContext *context, AudioFileIO *afio) +{ + MP42SampleBuffer *outSample = encode(context, afio); + return outSample; +} + +static inline void enqueue(MP42AC3AudioEncoder *self, MP42SampleBuffer *outSample) +{ + if (outSample) { + if (self->_outputType == MP42AudioUnitOutputPush) { + [self->_outputUnit addSample:outSample]; + } + else { + [self->_outputSamplesBuffer enqueue:outSample]; + } + } +} + +- (void)threadMainRoutine +{ + @autoreleasepool { + MP42SampleBuffer *sampleBuffer = nil; + + while ((sampleBuffer = [_inputSamplesBuffer dequeueAndWait])) { + @autoreleasepool { + + MP42SampleBuffer *outSample = nil; + + if (sampleBuffer->flags & MP42SampleBufferFlagEndOfFile) { + if (_avctx) { + _afio->done = true; + while ((outSample = flush(_avctx, _afio))) { + enqueue(self, outSample); + } + } + + enqueue(self, sampleBuffer); + return; + } + else { + if (_avctx) { + sfifo_write(_ringBuffer, sampleBuffer->data, sampleBuffer->size); + while ((outSample = encode(_avctx, _afio))) { + enqueue(self, outSample); + } + } + } + } + } + } +} + + +@end diff --git a/MP42/MP42AudioConverter.m b/MP42/MP42AudioConverter.m index c379999..3293a81 100644 --- a/MP42/MP42AudioConverter.m +++ b/MP42/MP42AudioConverter.m @@ -13,6 +13,7 @@ #import "MP42AudioDecoder.h" #import "MP42AudioEncoder.h" +#import "MP42AC3AudioEncoder.h" #import "MP42Track+Muxer.h" #import "MP42FileImporter+Private.h" @@ -22,7 +23,7 @@ @interface MP42AudioConverter () @property (nonatomic, readonly) MP42AudioDecoder *decoder; -@property (nonatomic, readonly) MP42AudioEncoder *encoder; +@property (nonatomic, readonly) id encoder; @end @@ -53,10 +54,17 @@ if (!_decoder) { return nil; } - - _encoder = [[MP42AudioEncoder alloc] initWithInputUnit:_decoder - bitRate:settings.bitRate - error:error]; + + if (settings.format == kMP42AudioCodecType_AC3 || settings.format == kMP42AudioCodecType_EnhancedAC3) { + _encoder = [[MP42AC3AudioEncoder alloc] initWithInputUnit:_decoder + bitRate:settings.bitRate + error:error]; + } + else { + _encoder = [[MP42AudioEncoder alloc] initWithInputUnit:_decoder + bitRate:settings.bitRate + error:error]; + } _encoder.outputUnit = self; _encoder.outputType = MP42AudioUnitOutputPull; diff --git a/MP42/MP42AudioTrack.m b/MP42/MP42AudioTrack.m index 210f958..f0d16d9 100644 --- a/MP42/MP42AudioTrack.m +++ b/MP42/MP42AudioTrack.m @@ -192,6 +192,23 @@ return (self.trackId > 0); } +- (void)setConversionSettings:(MP42AudioConversionSettings *)conversionSettings +{ + [super setConversionSettings:conversionSettings]; + + if (conversionSettings == nil) return; + + if ([self.name rangeOfString:@"surround" options:NSCaseInsensitiveSearch].location == NSNotFound) return; + + if ([conversionSettings.mixDown isEqualToString:SBNoneMixdown]) { + // FFmpeg encoding currently doesn't go beyond 5.1 + self.name = (self.channels > 6) ? @"Surround 5.1" : nameForChannelLayoutTag(self.channelLayoutTag); + } + else { + self.name = (self.channels == 1 || [conversionSettings.mixDown isEqualToString:SBMonoMixdown]) ? @"Mono" : @"Stereo"; + } +} + - (void)setVolume:(float)newVolume { _volume = newVolume; diff --git a/MP42/MP42ConversionSettings.h b/MP42/MP42ConversionSettings.h index bf89275..ffa4c4d 100644 --- a/MP42/MP42ConversionSettings.h +++ b/MP42/MP42ConversionSettings.h @@ -22,6 +22,8 @@ NS_ASSUME_NONNULL_BEGIN + (instancetype)audioConversionWithBitRate:(NSUInteger)bitrate mixDown:(NSString *)mixDown drc:(float)drc; +- (instancetype)initWitFormat:(FourCharCode)format bitRate:(NSUInteger)bitRate mixDown:(NSString *)mixDown drc:(float)drc; + @property (nonatomic, readonly) NSUInteger bitRate; @property (nonatomic, readonly) NSString *mixDown; diff --git a/MP42/MP42File.m b/MP42/MP42File.m index b52489b..6334940 100644 --- a/MP42/MP42File.m +++ b/MP42/MP42File.m @@ -1046,7 +1046,8 @@ static void logCallback(MP4LogLevel loglevel, const char *fmt, va_list ap) { for (MP42AudioTrack *track in [self tracksWithMediaType:kMP42MediaType_Audio] ) { if ((track.targetFormat == kMP42AudioCodecType_AC3 || - track.targetFormat == kMP42AudioCodecType_EnhancedAC3) && + track.targetFormat == kMP42AudioCodecType_EnhancedAC3 || + track.targetFormat == kMP42AudioCodecType_DTS) && track.fallbackTrack == nil) { [needFallbackTracks addObject:track]; } diff --git a/MP42/MP42Muxer.m b/MP42/MP42Muxer.m index d8ceded..ea20967 100644 --- a/MP42/MP42Muxer.m +++ b/MP42/MP42Muxer.m @@ -119,6 +119,72 @@ // so update the track timescale here. timeScale = audioConverter.sampleRate; format = track.conversionSettings.format; + + if (track.format == kMP42AudioCodecType_DTS && format == kMP42AudioCodecType_AC3) { + AudioStreamBasicDescription asbd; + bzero(&asbd, sizeof(AudioStreamBasicDescription)); + asbd.mSampleRate = [track.muxer_helper->importer timescaleForTrack:track]; + asbd.mChannelsPerFrame = [(MP42AudioTrack *)track channels]; + asbd.mFormatID = track.format; + + UInt32 channelLayoutSize = sizeof(AudioChannelLayout); + AudioChannelLayout *channelLayout = calloc(channelLayoutSize, 1); + channelLayout->mChannelLayoutTag = [(MP42AudioTrack *)track channelLayoutTag]; + + UInt32 bitmapSize = sizeof(UInt32); + UInt32 channelBitmap; + OSStatus err = AudioFormatGetProperty(kAudioFormatProperty_BitmapForLayoutTag, + sizeof(AudioChannelLayoutTag), &channelLayout->mChannelLayoutTag, + &bitmapSize, &channelBitmap); + if (err && AudioChannelLayoutTag_GetNumberOfChannels(channelLayout->mChannelLayoutTag) == 6) { + channelBitmap = 0x3F; + } + free(channelLayout); + + uint64_t fscod = 0; + uint64_t bsid = 8; + uint64_t bsmod = 0; + uint64_t acmod = 7; + uint64_t lfeon = (channelBitmap & kAudioChannelBit_LFEScreen) ? 1 : 0; + uint64_t bit_rate_code = 15; + + switch (asbd.mChannelsPerFrame - lfeon) { + case 1: + acmod = 1; + break; + case 2: + acmod = 2; + break; + case 3: + if (channelBitmap & kAudioChannelBit_CenterSurround) acmod = 3; + else acmod = 4; + break; + case 4: + if (channelBitmap & kAudioChannelBit_CenterSurround) acmod = 5; + else acmod = 6; + break; + case 5: + acmod = 7; + break; + default: + break; + } + + if (asbd.mSampleRate == 48000) fscod = 0; + else if (asbd.mSampleRate == 44100) fscod = 1; + else if (asbd.mSampleRate == 32000) fscod = 2; + else fscod = 3; + + NSMutableData *ac3Info = [NSMutableData dataWithCapacity:sizeof(uint64_t) * 6]; + [ac3Info appendBytes:&fscod length:sizeof(uint64_t)]; + [ac3Info appendBytes:&bsid length:sizeof(uint64_t)]; + [ac3Info appendBytes:&bsmod length:sizeof(uint64_t)]; + [ac3Info appendBytes:&acmod length:sizeof(uint64_t)]; + [ac3Info appendBytes:&lfeon length:sizeof(uint64_t)]; + [ac3Info appendBytes:&bit_rate_code length:sizeof(uint64_t)]; + + magicCookie = ac3Info; + } } if ([track isMemberOfClass:[MP42SubtitleTrack class]] && track.conversionSettings && (track.format == kMP42SubtitleCodecType_VobSub || track.format == kMP42SubtitleCodecType_PGS)) { diff --git a/MP42/MP42Utilities.h b/MP42/MP42Utilities.h index 8014132..cdd7d2c 100644 --- a/MP42/MP42Utilities.h +++ b/MP42/MP42Utilities.h @@ -18,4 +18,6 @@ BOOL trackNeedConversion(FourCharCode formatName); int isHdVideo(uint64_t width, uint64_t height); +NSString *nameForChannelLayoutTag(UInt32 channelLayoutTag); + NS_ASSUME_NONNULL_END diff --git a/MP42/MP42Utilities.m b/MP42/MP42Utilities.m index c9d7a55..26f1880 100644 --- a/MP42/MP42Utilities.m +++ b/MP42/MP42Utilities.m @@ -8,6 +8,7 @@ #import "MP42Utilities.h" #import "MP42SubUtilities.h" +#import NSString * StringFromTime(long long time, long timeScale) { @@ -99,3 +100,37 @@ int isHdVideo(uint64_t width, uint64_t height) return 0; } + +NSString *nameForChannelLayoutTag(UInt32 channelLayoutTag) +{ + UInt32 channelLayoutSize = sizeof(AudioChannelLayout); + AudioChannelLayout *channelLayout = calloc(channelLayoutSize, 1); + channelLayout->mChannelLayoutTag = channelLayoutTag; + + UInt32 bitmapSize = sizeof(UInt32); + UInt32 channelBitmap; + OSStatus err = AudioFormatGetProperty(kAudioFormatProperty_BitmapForLayoutTag, + sizeof(AudioChannelLayoutTag), &channelLayout->mChannelLayoutTag, + &bitmapSize, &channelBitmap); + UInt32 channels = AudioChannelLayoutTag_GetNumberOfChannels(channelLayout->mChannelLayoutTag); + if (err && channels == 6) { + channelBitmap = 0x3F; + } + free(channelLayout); + BOOL lfe = (channelBitmap & kAudioChannelBit_LFEScreen); + int mainChannels = (lfe) ? channels - 1 : channels; + NSString *desc; + switch (mainChannels) { + case 1: + desc = @"Mono"; + break; + case 2: + case 3: + desc = @"Stereo"; + break; + default: + desc = @"Surround"; + break; + } + return [NSString stringWithFormat:@"%@ %d.%d", desc, mainChannels, (lfe) ? 1 : 0]; +} diff --git a/MP42Foundation.xcodeproj/project.pbxproj b/MP42Foundation.xcodeproj/project.pbxproj index 88233ce..7742182 100644 --- a/MP42Foundation.xcodeproj/project.pbxproj +++ b/MP42Foundation.xcodeproj/project.pbxproj @@ -227,6 +227,8 @@ A9DFBDCC1960174500410060 /* MP42EditListsReconstructor.m in Sources */ = {isa = PBXBuildFile; fileRef = A9DFBDCA1960174500410060 /* MP42EditListsReconstructor.m */; }; A9E8FB851D4664E80071A5F1 /* libbz2.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = A9E8FB841D4664E80071A5F1 /* libbz2.tbd */; }; A9E8FB871D4664F70071A5F1 /* libz.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = A9E8FB861D4664F70071A5F1 /* libz.tbd */; }; + FFE849961EBCAFDF000AA078 /* MP42AC3AudioEncoder.h in Headers */ = {isa = PBXBuildFile; fileRef = FFE849941EBCAFDF000AA078 /* MP42AC3AudioEncoder.h */; }; + FFE849971EBCAFDF000AA078 /* MP42AC3AudioEncoder.m in Sources */ = {isa = PBXBuildFile; fileRef = FFE849951EBCAFDF000AA078 /* MP42AC3AudioEncoder.m */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -438,6 +440,8 @@ A9DFBDCA1960174500410060 /* MP42EditListsReconstructor.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42EditListsReconstructor.m; sourceTree = ""; }; A9E8FB841D4664E80071A5F1 /* libbz2.tbd */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.text-based-dylib-definition"; name = libbz2.tbd; path = usr/lib/libbz2.tbd; sourceTree = SDKROOT; }; A9E8FB861D4664F70071A5F1 /* libz.tbd */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.text-based-dylib-definition"; name = libz.tbd; path = usr/lib/libz.tbd; sourceTree = SDKROOT; }; + FFE849941EBCAFDF000AA078 /* MP42AC3AudioEncoder.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MP42AC3AudioEncoder.h; sourceTree = ""; }; + FFE849951EBCAFDF000AA078 /* MP42AC3AudioEncoder.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MP42AC3AudioEncoder.m; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -756,6 +760,8 @@ A908010D1D4B83A3002B6950 /* MP42AudioDecoder.m */, A908010E1D4B83A3002B6950 /* MP42AudioEncoder.h */, A908010F1D4B83A3002B6950 /* MP42AudioEncoder.m */, + FFE849941EBCAFDF000AA078 /* MP42AC3AudioEncoder.h */, + FFE849951EBCAFDF000AA078 /* MP42AC3AudioEncoder.m */, A90801101D4B83A3002B6950 /* MP42AudioUnit.h */, A9B9C21F1823923100416A4E /* MP42AudioConverter.h */, A9B9C2201823923100416A4E /* MP42AudioConverter.m */, @@ -794,6 +800,7 @@ A9B9C27D1823923200416A4E /* MP42FileImporter.h in Headers */, A9B9C27B1823923200416A4E /* MP42File.h in Headers */, A9059DCB1D870B9C000D1B9A /* MP42ConversionSettings.h in Headers */, + FFE849961EBCAFDF000AA078 /* MP42AC3AudioEncoder.h in Headers */, A9DFBDCB1960174500410060 /* MP42EditListsReconstructor.h in Headers */, A9B9C29B1823923200416A4E /* MP42Track.h in Headers */, A9B9C29F1823923200416A4E /* MP42VideoTrack.h in Headers */, @@ -1073,6 +1080,7 @@ A9B9C29C1823923200416A4E /* MP42Track.m in Sources */, A9B9C2A01823923200416A4E /* MP42VideoTrack.m in Sources */, A90801171D4B83A3002B6950 /* MP42AudioEncoder.m in Sources */, + FFE849971EBCAFDF000AA078 /* MP42AC3AudioEncoder.m in Sources */, A9B9C2981823923200416A4E /* MP42SubtitleTrack.m in Sources */, A9022A961D6F3FD9005F0920 /* MP42MetadataItem.m in Sources */, A9B9C2D0182396A100416A4E /* MP42Ratings.m in Sources */, From 414b5e559af0d0e0592fa315b93493f2c51f91d1 Mon Sep 17 00:00:00 2001 From: Brian Gerfort Date: Sat, 6 May 2017 13:37:39 +0200 Subject: [PATCH 3/4] Reverting to previous chapter preview offsets. Will make it a setting instead. --- MP42/MP42PreviewGenerator.m | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/MP42/MP42PreviewGenerator.m b/MP42/MP42PreviewGenerator.m index a3a4935..beb30d8 100644 --- a/MP42/MP42PreviewGenerator.m +++ b/MP42/MP42PreviewGenerator.m @@ -20,7 +20,7 @@ return images; } -+ (NSArray *)generatePreviewImagesAVFoundationFromChapters:(NSArray *)chapters andFile:(NSURL *)file { ++ (NSArray *)generatePreviewImagesAVFoundationFromChapters:(NSArray *)chapters andFile:(NSURL *)file { NSMutableArray *images = [[NSMutableArray alloc] initWithCapacity:[chapters count]]; AVAsset *asset = [AVAsset assetWithURL:file]; @@ -32,13 +32,8 @@ generator.requestedTimeToleranceBefore = kCMTimeZero; generator.requestedTimeToleranceAfter = kCMTimeZero; - CGFloat thumbnailPosition = 0.5; // Middle of chapter - - for (NSInteger idx = 0; idx < chapters.count; idx++) - { - MP42TextSample *chapter = chapters[idx]; - MP42Duration nextChapterTimestamp = (idx < chapters.count - 1) ? [chapters[idx+1] timestamp] : CMTimeGetSeconds(asset.duration) * 1000; - CMTime time = CMTimeMake([chapter timestamp] + ((nextChapterTimestamp - [chapter timestamp]) * thumbnailPosition), 1000); + for (MP42TextSample *chapter in chapters) { + CMTime time = CMTimeMake([chapter timestamp] + 1800, 1000); CGImageRef imgRef = [generator copyCGImageAtTime:time actualTime:NULL error:NULL]; if (imgRef) { NSSize size = NSMakeSize(CGImageGetWidth(imgRef), CGImageGetHeight(imgRef)); From 0af9487aa5fc03249ff459fb9301f3fb7afdee4e Mon Sep 17 00:00:00 2001 From: Brian Gerfort Date: Sat, 6 May 2017 21:36:20 +0200 Subject: [PATCH 4/4] Added setting to set the position of the rendered chapter previews. Default is the middle of the chapter. --- MP42/MP42File.h | 1 + MP42/MP42File.m | 9 ++++++--- MP42/MP42PreviewGenerator.h | 2 +- MP42/MP42PreviewGenerator.m | 28 +++++++++++++++++++--------- 4 files changed, 27 insertions(+), 13 deletions(-) diff --git a/MP42/MP42File.h b/MP42/MP42File.h index eb59aa3..da1b216 100644 --- a/MP42/MP42File.h +++ b/MP42/MP42File.h @@ -24,6 +24,7 @@ NS_ASSUME_NONNULL_BEGIN extern NSString * const MP4264BitData; extern NSString * const MP4264BitTime; extern NSString * const MP42GenerateChaptersPreviewTrack; +extern NSString * const MP42ChaptersPreviewPosition; extern NSString * const MP42CustomChaptersPreviewTrack; typedef void (^MP42FileProgressHandler)(double progress); diff --git a/MP42/MP42File.m b/MP42/MP42File.m index 6334940..a1aa1be 100644 --- a/MP42/MP42File.m +++ b/MP42/MP42File.m @@ -20,6 +20,7 @@ NSString * const MP4264BitData = @"MP4264BitData"; NSString * const MP4264BitTime = @"MP4264BitTime"; NSString * const MP42GenerateChaptersPreviewTrack = @"MP42ChaptersPreview"; +NSString * const MP42ChaptersPreviewPosition = @"MP42ChaptersPreviewPosition"; NSString * const MP42CustomChaptersPreviewTrack = @"MP42CustomChaptersPreview"; /** @@ -853,7 +854,7 @@ static void logCallback(MP4LogLevel loglevel, const char *fmt, va_list ap) { // Generate previews images for chapters if ([options[MP42GenerateChaptersPreviewTrack] boolValue] && self.itracks.count) { - [self createChaptersPreview]; + [self createChaptersPreviewAtPosition:[options[MP42ChaptersPreviewPosition] floatValue]]; } else if ([options[MP42CustomChaptersPreviewTrack] boolValue] && self.itracks.count) { [self customChaptersPreview]; } @@ -968,7 +969,7 @@ static void logCallback(MP4LogLevel loglevel, const char *fmt, va_list ap) { return YES; } -- (BOOL)createChaptersPreview { +- (BOOL)createChaptersPreviewAtPosition:(CGFloat)position { NSInteger decodable = 1; MP42ChapterTrack *chapterTrack = nil; MP42VideoTrack *refTrack = nil; @@ -1001,7 +1002,9 @@ static void logCallback(MP4LogLevel loglevel, const char *fmt, va_list ap) { } if (chapterTrack && decodable && (!jpegTrack)) { - NSArray *images = [MP42PreviewGenerator generatePreviewImagesFromChapters:chapterTrack.chapters fileURL:self.URL]; + NSArray *images = [MP42PreviewGenerator generatePreviewImagesFromChapters:chapterTrack.chapters + fileURL:self.URL + atPosition:position]; // If we haven't got any images, return. if (!images || !images.count) { diff --git a/MP42/MP42PreviewGenerator.h b/MP42/MP42PreviewGenerator.h index 1dbad3b..cabf1e2 100644 --- a/MP42/MP42PreviewGenerator.h +++ b/MP42/MP42PreviewGenerator.h @@ -14,7 +14,7 @@ NS_ASSUME_NONNULL_BEGIN @interface MP42PreviewGenerator : NSObject -+ (NSArray *)generatePreviewImagesFromChapters:(NSArray *)chapters fileURL:(NSURL *)url; ++ (NSArray *)generatePreviewImagesFromChapters:(NSArray *)chapters fileURL:(NSURL *)url atPosition:(CGFloat)position; @end diff --git a/MP42/MP42PreviewGenerator.m b/MP42/MP42PreviewGenerator.m index beb30d8..0202709 100644 --- a/MP42/MP42PreviewGenerator.m +++ b/MP42/MP42PreviewGenerator.m @@ -10,21 +10,23 @@ #import "MP42TextSample.h" #import +#define MINIMUM_OFFSET 1800 + @implementation MP42PreviewGenerator -+ (NSArray *)generatePreviewImagesFromChapters:(NSArray *)chapters fileURL:(NSURL *)url { ++ (NSArray *)generatePreviewImagesFromChapters:(NSArray *)chapters fileURL:(NSURL *)url atPosition:(CGFloat)position { NSArray *images = nil; - images = [MP42PreviewGenerator generatePreviewImagesAVFoundationFromChapters:chapters andFile:url]; + images = [MP42PreviewGenerator generatePreviewImagesAVFoundationFromChapters:chapters andFile:url atPosition:position]; return images; } -+ (NSArray *)generatePreviewImagesAVFoundationFromChapters:(NSArray *)chapters andFile:(NSURL *)file { ++ (NSArray *)generatePreviewImagesAVFoundationFromChapters:(NSArray *)chapters andFile:(NSURL *)file atPosition:(CGFloat)position { NSMutableArray *images = [[NSMutableArray alloc] initWithCapacity:[chapters count]]; - + AVAsset *asset = [AVAsset assetWithURL:file]; - + if ([asset tracksWithMediaCharacteristic:AVMediaCharacteristicVisual]) { AVAssetImageGenerator *generator = [AVAssetImageGenerator assetImageGeneratorWithAsset:asset]; generator.appliesPreferredTrackTransform = YES; @@ -32,16 +34,24 @@ generator.requestedTimeToleranceBefore = kCMTimeZero; generator.requestedTimeToleranceAfter = kCMTimeZero; - for (MP42TextSample *chapter in chapters) { - CMTime time = CMTimeMake([chapter timestamp] + 1800, 1000); + CGFloat offset; + + for (NSInteger idx = 0; idx < chapters.count; idx++) + { + MP42TextSample *chapter = chapters[idx]; + MP42Duration nextChapterTimestamp = (idx < chapters.count - 1) ? [chapters[idx+1] timestamp] : CMTimeGetSeconds(asset.duration) * 1000; + if (position <= 0.0) offset = MINIMUM_OFFSET; + else if (position >= 1.0) offset = ((nextChapterTimestamp - [chapter timestamp]) * position) - MINIMUM_OFFSET; + else offset = (nextChapterTimestamp - [chapter timestamp]) * position; + CMTime time = CMTimeMake([chapter timestamp] + MAX(MINIMUM_OFFSET, offset), 1000); CGImageRef imgRef = [generator copyCGImageAtTime:time actualTime:NULL error:NULL]; if (imgRef) { NSSize size = NSMakeSize(CGImageGetWidth(imgRef), CGImageGetHeight(imgRef)); NSImage *frame = [[NSImage alloc] initWithCGImage:imgRef size:size]; - + [images addObject:frame]; } - + CGImageRelease(imgRef); } }