一次“Error Domain=AVFoundationErrorDomain Code=-11841”的调试

起因

最近在重构视频输出模块的时候,调试碰到AVAssetReader 调用开始方法总是返回NO而失败,代码如下:

if ([reader startReading] == NO)
{
NSLog(@"Error reading from file at URL: %@", self.url);
return;
}

reader的创建代码如下,主要用的是GPUImageMovieCompostion.

- (AVAssetReader*)createAssetReader
{
NSError *error = nil;
AVAssetReader *assetReader = [AVAssetReader assetReaderWithAsset:self.compositon error:&error]; NSDictionary *outputSettings = @{(id)kCVPixelBufferPixelFormatTypeKey: @(kCVPixelFormatType_420YpCbCr8BiPlanarFullRange)};
AVAssetReaderVideoCompositionOutput *readerVideoOutput = [AVAssetReaderVideoCompositionOutput assetReaderVideoCompositionOutputWithVideoTracks:[_compositon tracksWithMediaType:AVMediaTypeVideo]
videoSettings:outputSettings];
readerVideoOutput.videoComposition = self.videoComposition;
readerVideoOutput.alwaysCopiesSampleData = NO;
if ([assetReader canAddOutput:readerVideoOutput]) {
[assetReader addOutput:readerVideoOutput];
} NSArray *audioTracks = [_compositon tracksWithMediaType:AVMediaTypeAudio];
BOOL shouldRecordAudioTrack = (([audioTracks count] > 0) && (self.audioEncodingTarget != nil) );
AVAssetReaderAudioMixOutput *readerAudioOutput = nil; if (shouldRecordAudioTrack)
{
[self.audioEncodingTarget setShouldInvalidateAudioSampleWhenDone:YES];
NSDictionary *audioReaderSetting = @{AVFormatIDKey: @(kAudioFormatLinearPCM),
AVLinearPCMIsBigEndianKey: @(NO),
AVLinearPCMIsFloatKey: @(NO),
AVLinearPCMBitDepthKey: @(16)};
readerAudioOutput = [AVAssetReaderAudioMixOutput assetReaderAudioMixOutputWithAudioTracks:audioTracks audioSettings:audioReaderSetting];
readerAudioOutput.audioMix = self.audioMix;
readerAudioOutput.alwaysCopiesSampleData = NO;
[assetReader addOutput:readerAudioOutput];
} return assetReader;
}

然后在该处断点,查看reader的status和error,显示Error Domain=AVFoundationErrorDomain Code=-11841。查了一下文档发现如下:

AVErrorInvalidVideoComposition = -11841

You attempted to perform a video composition operation that is not supported.

应该就是readerVideoOutput.videoComposition = self.videoComposition; 这个videoCompostion有问题了。AVMutableVideoComposition这个类在视频编辑里面非常重要,包含对AVComposition中的各个视频track如何融合的信息,我做的是两个视频的融合小demo,就需要用到它,设置这个类稍微有点复杂,比较容易出错,特别是设置AVMutableVideoCompositionInstruction这个类的timeRange属性,我的这次错误就是因为这个。

开始调试

马上调用AVMutableVideoComposition的如下方法:


BOOL isValid = [self.videoComposition isValidForAsset:self.compositon timeRange:CMTimeRangeMake(kCMTimeZero, self.compositon.duration) validationDelegate:self];

这个时候isValid为No,确定就是这个videoCompostion问题了,添加了AVVideoCompositionValidationHandling协议四个方法打印一下,这个协议太贴心了,估计知道这个地方出错概率比较高,所以特地弄的吧。代码如下:


- (BOOL)videoComposition:(AVVideoComposition *)videoComposition shouldContinueValidatingAfterFindingInvalidValueForKey:(NSString *)key
{
NSLog(@"%s===%@",__func__,key);
return YES;
} - (BOOL)videoComposition:(AVVideoComposition *)videoComposition shouldContinueValidatingAfterFindingEmptyTimeRange:(CMTimeRange)timeRange
{
NSLog(@"%s===%@",__func__,CFBridgingRelease(CMTimeRangeCopyDescription(kCFAllocatorDefault, timeRange)));
return YES;
} - (BOOL)videoComposition:(AVVideoComposition *)videoComposition shouldContinueValidatingAfterFindingInvalidTimeRangeInInstruction:(id<AVVideoCompositionInstruction>)videoCompositionInstruction
{
NSLog(@"%s===%@",__func__,videoCompositionInstruction);
return YES;
} - (BOOL)videoComposition:(AVVideoComposition *)videoComposition shouldContinueValidatingAfterFindingInvalidTrackIDInInstruction:(id<AVVideoCompositionInstruction>)videoCompositionInstruction layerInstruction:(AVVideoCompositionLayerInstruction *)layerInstruction asset:(AVAsset *)asset
{
NSLog(@"%s===%@===%@",__func__,layerInstruction,asset);
return YES;
}

重新运行一下发现第三个方法打印输出,就是instruction的timeRange问题了,又重新看了一下两个instruction的设置问题,感觉又没什么问题,代码如下:


- (void)buildCompositionWithAssets:(NSArray *)assetsArray
{
for (int i = 0; i < assetsArray.count; i++) {
AVURLAsset *asset = assetsArray[i];
NSArray *videoTracks = [asset tracksWithMediaType:AVMediaTypeVideo];
NSArray *audioTracks = [asset tracksWithMediaType:AVMediaTypeAudio]; AVAssetTrack *videoTrack = videoTracks[0];
AVAssetTrack *audioTrack = audioTracks[0];
NSError *error = nil;
AVMutableCompositionTrack *videoT = [self.avcompostions.mutableComps addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];
AVMutableCompositionTrack *audioT = [self.avcompostions.mutableComps addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
[videoT insertTimeRange:videoTrack.timeRange ofTrack:videoTrack atTime:self.offsetTime error:&error];
[audioT insertTimeRange:audioTrack.timeRange ofTrack:audioTrack atTime:self.offsetTime error:nil];
NSAssert(!error, @"insert error = %@",error);
AVMutableVideoCompositionInstruction *instruction = [AVMutableVideoCompositionInstruction videoCompositionInstruction];
AVMutableVideoCompositionLayerInstruction *layerInstruction = [AVMutableVideoCompositionLayerInstruction videoCompositionLayerInstructionWithAssetTrack:videoT];
instruction.layerInstructions = @[layerInstruction];
instruction.timeRange = CMTimeRangeMake(self.offsetTime, asset.duration);
[self.instrucionArray addObject:instruction];
self.offsetTime = CMTimeAdd(self.offsetTime,asset.duration);
}
}

这个数组里面会有两个加载好的AVAsset对象,加载AVAsset的代码如下:


- (void)loadAssetFromPath:(NSArray *)paths
{
NSMutableArray *assetsArray = [NSMutableArray arrayWithCapacity:paths.count];
dispatch_group_t dispatchGroup = dispatch_group_create();
for (int i = 0; i < paths.count; i++) {
NSString *path = paths[i];
//first find from cache
AVAsset *asset = [self.assetsCache objectForKey:path];
if (!asset) {
NSDictionary *inputOptions = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
asset = [AVURLAsset URLAssetWithURL:[NSURL fileURLWithPath:path] options:inputOptions];
// cache asset
NSAssert(asset != nil, @"Can't create asset from path", path);
NSArray *loadKeys = @[@"tracks", @"duration", @"composable"];
[self loadAsset:asset withKeys:loadKeys usingDispatchGroup:dispatchGroup];
[self.assetsCache setObject:asset forKey:path];
}else {
}
[assetsArray addObject:asset];
}
dispatch_group_notify(dispatchGroup, dispatch_get_main_queue(), ^{
!self.assetLoadBlock?:self.assetLoadBlock(assetsArray); });
} - (void)loadAsset:(AVAsset *)asset withKeys:(NSArray *)assetKeysToLoad usingDispatchGroup:(dispatch_group_t)dispatchGroup
{
dispatch_group_enter(dispatchGroup);
[asset loadValuesAsynchronouslyForKeys:assetKeysToLoad completionHandler:^(){
for (NSString *key in assetKeysToLoad) {
NSError *error; if ([asset statusOfValueForKey:key error:&error] == AVKeyValueStatusFailed) {
NSLog(@"Key value loading failed for key:%@ with error: %@", key, error);
goto bail;
}
}
if (![asset isComposable]) {
NSLog(@"Asset is not composable");
goto bail;
}
bail:
dispatch_group_leave(dispatchGroup);
}];
}

按照正常来说,应该不会有什么问题的,但是问题还是来了。打印出创建的两个AVMutableVideoCompositionInstruction的信息,发现他们的timeRange确实有重合的地方。AVMutableVideoCompositionInstruction的timeRange必须对应AVMutableCompositionTrack里面的一段段插入的track的timeRange。开发文档是这么说的:

to report a video composition instruction with a timeRange that's invalid, that overlaps with the timeRange of a prior instruction, or that contains times earlier than the timeRange of a prior instruction

我在插入的时候使用的是videoTrack.timeRange,而设置instruction.timeRange = CMTimeRangeMake(self.offsetTime, asset.duration);使用的是asset.duration。这个两个竟然是不一样的。asset.duration是{59885/1000 = 59.885},videoTrack.timeRange是{{0/1000 = 0.000}, {59867/1000 = 59.867}}

这两个时长有细微差别,到底哪个是比较准确一点的呢?

视频文件时长的计算

笔者在demo中使用的是mp4格式的文件,mp4文件是若干个不同的类型box组成的,box可以理解为装有数据的容器。其中有一种moov类型的box里面装有视频播放的元数据(metadata),这里面有视频的时长信息:timescale和duration。 duration / timescale = 可播放时长(s)。从mvhd中读到timescal为0x03e8,duration为0xe9ed,也就是59885 / 1000,为59.885。再看看tkhd box里面的内容,这里面是包含单一track的信息。如下图:

从上图可以看出videotrack和audiotrack两个的时长是不一样的,videotrack为0xe9db,也就是59.867,audiotrack为0xe9ed,就是59.885。所以我们在计算timeRange的时候最好统一使用相对精确一点的videotrack,而不要AVAsset的duration,尽量避免时间上的误差,视频精细化的编辑,对这些误差敏感。

一次“Error Domain=AVFoundationErrorDomain Code=-11841”的调试的更多相关文章

  1. Error Domain=AVFoundationErrorDomain Code=-11800 "这项操作无法完成"

    在iOS上开发视频操作的时候,出现错误: 录制视频错误:Error Domain=AVFoundationErrorDomain Code=-11800 "这项操作无法完成" Us ...

  2. iOS json 解析遇到error: Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed.

    Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 38 ...

  3. [ios] 定位报错Error Domain=kCLErrorDomain Code=0 "The operation couldn’t be completed. (kCLErrorDomain error 0.)"

    Error Domain=kCLErrorDomain Code=0 "The operation couldn’t be completed. (kCLErrorDomain error ...

  4. IOS8解决获取位置坐标信息出错(Error Domain=kCLErrorDomain Code=0)(转)

    标题:IOS8解决获取位置坐标信息出错(Error Domain=kCLErrorDomain Code=0) 前几天解决了在ios8上无法使用地址位置服务的问题,最近在模拟器上调试发现获取位置坐标信 ...

  5. ShareSDK 集成 Google+ 登录 400. Error:redirect_uri_mismatch 和 Error Domain=ShareSDKErrorDomain Code=204

    最近在集成ShareSDK中 Google+ 登录授权时候 出现了如下几个问题 1.    400.  Error:redirect_uri_mismatch 出现这种情况, redirectUri应 ...

  6. Error Domain=ASIHTTPRequestErrorDomain Code=8 "Failed to move file from"xxx/xxx"to"xxx/xxx"

    今天真的好高兴呀 我解决了一个折磨了我一周的问题,真的是激动地要哭出来了,为了这个问题,我嘴也烂了,头发抓了一地啊.虽然解决方法,最后还是展现出了“百度”的伟大,但是我还是很开心,在这里我展示一下我的 ...

  7. iOS解析JSON字符串报错Error Domain=NSCocoaErrorDomain Code=3840 "Invalid escape sequence around character 586."

    将服务器返回的JSON string转化成字典时报错: Error Domain=NSCocoaErrorDomain Code=3840 "Invalid escape sequence ...

  8. 关于https的Error:Error Domain=NSURLErrorDomain Code=-1012

    昨天闲着没事就随便搞点demo,随便找了一个https的接口,运行之后,一直发现Error Domain=NSURLErrorDomain Code=-1012.好奇怪,请求https的配置我基本都配 ...

  9. IOS8解决获取位置坐标信息出错(Error Domain=kCLErrorDomain Code=0)

    最近在模拟器上调试发现获取位置坐标信息的时候会报错,错误信息: didFailWithError: Error Domain=kCLErrorDomain Code=0 “The operation ...

随机推荐

  1. 伪元素::before与::after的用法

    ::before与::after两个伪元素其实是CSS3中的内容,然而实际上在CSS2中就已经有了这两者的身影,只不过CSS2中是前面加一个冒号来表示(:before和:after).今天主要讲讲这两 ...

  2. H5前端正则验证插件

    最近学习了一个新的关于前端正则验证的插件,‘jQuery.validate.js ’ 要用这个插件 首先得有插件,下载jquery.validate.min.js 和jq文件并引入. 我把它简单的通俗 ...

  3. Java设计模式—享元模式

    享元模式:是池技术的重要实现方式. 定义如下: 使用共享对象可有效地支持大量的细粒度的对象. 个人理解:享元模式利用共享对象的技术,解决了Java中内存溢出的问题. 享元模式的定义为我们提出了两个要求 ...

  4. Linux修改Oracle用戶

    Linux下SSH登陆后: su - Oracle; sqlplus /nolog; conn system/密码; 或者 connect/as sysdba; alter user 用户名 iden ...

  5. 购买 In-app Billing 商品

    购买 In-app Billing 商品 一旦你的应用连接上了 Google Play,你就可以初始化内购商品的购买请求了.Google Play 提供了结算接口,可以让用户进入使用他们的支付方式,所 ...

  6. Effective C++(20) 继承与面向对象设计

    本文主要参考<Effective C++ 3rd>中的第六章部分章节的内容. 关注的问题集中在继承.派生.virtual函数等.如: virtual? non-virtual? pure ...

  7. Python学习---函数的学习1209[all]

    1.基础函数 2.高阶函数 3.递归函数 4.内置函数 5.匿名函数和闭包

  8. 附加进程找不到w3wp.exe进程解决方案

    在进程列表的下面,有个show processes in all sessions(显示所有用户的进程(U)),把它勾上就能看到了 ,就是这么简单.

  9. composer随笔

    composer dump-autoload 生成autoload.php文件

  10. 彻底解密 Spark 的 HashShuffle

    本课主题 Shuffle 是分布式系统的天敌 Spark HashShuffle介绍 Spark Consolidated HashShuffle介绍 Shuffle 是如何成为 Spark 性能杀手 ...