我正在使用一些技巧来尝试在将 AVAssetWriter 写入磁盘时读取其原始输出。当我通过连接各个文件来重新组装它们时,生成的文件与 AVAssetWriter 的输出文件的字节数完全相同。但是,重新组装的文件将无法在 QuickTime 中播放或被 FFmpeg 解析,因为存在数据损坏。一些字节已被更改,导致生成的文件无法使用。我假设这发生在每次读取的 EOF 边界上,但它不是一致的损坏。
我计划最终使用与此类似的代码从编码器中解析出各个 H.264 NAL 单元,将它们打包并通过 RTP 发送它们,但是如果我不能信任从磁盘读取的数据,我可能不得不使用其他解决方案。
对于此数据损坏有解释/修复吗?您是否找到了有关如何解析 NAL 单元以通过 RTP 进行打包的任何其他资源/链接?
完整代码在这里:AVAppleEncoder.m
// Modified from
// http://www.davidhamrick.com/2011/10/13/Monitoring-Files-With-GCD-Being-Edited-With-A-Text-Editor.html
- (void)watchOutputFileHandle
{
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
int fildes = open([[movieURL path] UTF8String], O_EVTONLY);
source = dispatch_source_create(DISPATCH_SOURCE_TYPE_VNODE,fildes,
DISPATCH_VNODE_DELETE | DISPATCH_VNODE_WRITE | DISPATCH_VNODE_EXTEND | DISPATCH_VNODE_ATTRIB | DISPATCH_VNODE_LINK | DISPATCH_VNODE_RENAME | DISPATCH_VNODE_REVOKE,
queue);
dispatch_source_set_event_handler(source, ^
{
unsigned long flags = dispatch_source_get_data(source);
if(flags & DISPATCH_VNODE_DELETE)
{
dispatch_source_cancel(source);
//[blockSelf watchStyleSheet:path];
}
if(flags & DISPATCH_VNODE_EXTEND)
{
//NSLog(@"File size changed");
NSError *error = nil;
NSFileHandle *fileHandle = [NSFileHandle fileHandleForReadingFromURL:movieURL error:&error];
if (error) {
[self showError:error];
}
[fileHandle seekToFileOffset:fileOffset];
NSData *newData = [fileHandle readDataToEndOfFile];
if ([newData length] > 0) {
NSLog(@"newData (%lld): %d bytes", fileOffset, [newData length]);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
NSString *movieName = [NSString stringWithFormat:@"%d.%lld.%d.mp4", fileNumber, fileOffset, [newData length]];
NSString *path = [NSString stringWithFormat:@"%@/%@", basePath, movieName];
[newData writeToFile:path atomically:NO];
fileNumber++;
fileOffset = [fileHandle offsetInFile];
}
}
});
dispatch_source_set_cancel_handler(source, ^(void)
{
close(fildes);
});
dispatch_resume(source);
}
以下是我发现的一些类似问题,但不能完全回答我的问题:
- 从 iOS AVAssetWriter 生成的原始 H264 mdat 中获取 PTS
- 从 iPhone 传输视频
- 从 QuickTime MOV 文件解析 h.264 NAL 单元
- 从 iPhone 到另一台设备(浏览器或 iPhone)的实时音频/视频流
当我最终弄清楚这一点时,我将发布一个开源库来帮助将来尝试这样做的人。
谢谢你!
Update:损坏不会发生在 EOF 边界处。看起来文件的某些部分在之后被重写了finishWriting
叫做。第一个文件的分块大小为 4KB,因此更改的区域不在 EOF 边界附近。当新的“moov”元素附近它似乎也被损坏了movieFragmentInterval
已启用。
Correct file on the left, broken file on the right.