Использование AVAssetWriter для создания фильма QuickTime из необработанных файлов H.264/AAC

Используя Mac OSX Objective -C, я пытаюсь создать инструмент командной строки, который принимает один файл H.264 и один файл AAC в качестве входных данных -, закодированных из одного и того же исходного материала -, и, используя AVAssetWriter, создать один совместимый с QuickTime -файл mov (и/или m4v )для дальнейшего редактирования/распространения.

Что я сделал до сих пор :1 )Использование компонентов AVFoundation Framework, т. е. AVAssetWriter, AVAssetWriterInput и т. д., и компонентов Core Media Framework, т. е. CMSampleBufferCreate, CMBlockBufferReplaceDataBytes, и т. д. -Я создал прототип инструмента CL. 2 )Я подключил URL-адреса входных/выходных файлов, создал AVAssetWriter и AVAssetWriterInput, CMBlockBuffer и т. д. 3 )Когда я запускаю свой runLoop, AVAssetWriter создает файл m4v, но, хотя он -правильно сформирован, это всего лишь 136-байтовый файл, представляющий атомы заголовка фильма без данных видеодорожки. 4 )Я провел поиск в StackOverflow -, а также на форумах Apple и в Интернете в целом -, чтобы найти ответ на свой конкретный набор вопросов.

Используя проверку ошибок в моем коде, а также отладчик Xcode,Я обнаружил, что AVAssetWriter настроен правильно -, он начинает создавать файл фильма -, но CMBlockBufferReplaceDataBytes НЕ записывает данные H.264 NAL в CMBlockBuffer (, как я считаю, должен делать ). Итак, что мне не хватает?

Вот соответствующая часть моего кода runLoop:

// Create the videoFile.m4v AVAssetWriter.
AVAssetWriter *videoFileWriter = [[AVAssetWriter alloc] initWithURL:destinationURL fileType:AVFileTypeQuickTimeMovie error:&error];
NSParameterAssert(videoFileWriter);
if (error) {
    NSLog(@"AVAssetWriter initWithURL failed with error= %@", [error localizedDescription]);
}

// Create the video file settings dictionary.
NSDictionary *videoSettings = [NSDictionary dictionaryWithObjectsAndKeys: AVVideoCodecH264, AVVideoCodecKey, [NSNumber numberWithInt:1280],
                               AVVideoWidthKey, [NSNumber numberWithInt:720], AVVideoHeightKey, nil];

// Perform video settings check.
if ([videoFileWriter canApplyOutputSettings:videoSettings forMediaType:AVMediaTypeVideo]) {
    NSLog(@"videoFileWriter can apply videoSettings...");    
}

// Create the input to the videoFileWriter AVAssetWriter.
AVAssetWriterInput *videoFileWriterInput = [[AVAssetWriterInput alloc] initWithMediaType:AVMediaTypeVideo outputSettings:videoSettings];
videoFileWriterInput.expectsMediaDataInRealTime = YES;
NSParameterAssert(videoFileWriterInput);
NSParameterAssert([videoFileWriter canAddInput:videoFileWriterInput]);

// Connect the videoFileWriterInput to the videoFileWriter.
if ([videoFileWriter canAddInput:videoFileWriterInput]) {
   [videoFileWriter addInput:videoFileWriterInput]; 
}

// Get the contents of videoFile.264 (using current Mac OSX methods).
NSData *sourceData = [NSData dataWithContentsOfURL:sourceURL];
const char *videoFileData = [sourceData bytes];
size_t sourceDataLength = [sourceData length];
NSLog(@"The value of 'sourceDataLength' is: %ld", sourceDataLength);

// Set up to create the videoSampleBuffer.
int32_t videoWidth = 1280;
int32_t videoHeight = 720;
CMBlockBufferRef videoBlockBuffer = NULL;
CMFormatDescriptionRef videoFormat = NULL;
CMSampleBufferRef videoSampleBuffer = NULL;
CMItemCount numberOfSampleTimeEntries = 1;
CMItemCount numberOfSamples = 1;

// More set up to create the videoSampleBuffer.
CMVideoFormatDescriptionCreate(kCFAllocatorDefault, kCMVideoCodecType_H264, videoWidth, videoHeight, NULL, &videoFormat);
result = CMBlockBufferCreateWithMemoryBlock(kCFAllocatorDefault, NULL, 150000, kCFAllocatorDefault, NULL, 0, 150000, kCMBlockBufferAssureMemoryNowFlag,
                                            &videoBlockBuffer);
NSLog(@"After 'CMBlockBufferCreateWithMemoryBlock', 'result' is: %d", result);

// The CMBlockBufferReplaceDataBytes method is supposed to write videoFile.264 data bytes into the videoSampleBuffer.
result = CMBlockBufferReplaceDataBytes(videoFileData, videoBlockBuffer, 0, 150000);
NSLog(@"After 'CMBlockBufferReplaceDataBytes', 'result' is: %d", result);

CMSampleTimingInfo videoSampleTimingInformation = {CMTimeMake(1, 30)};
result = CMSampleBufferCreate(kCFAllocatorDefault, videoBlockBuffer, TRUE, NULL, NULL, videoFormat, numberOfSamples, numberOfSampleTimeEntries,
                              &videoSampleTimingInformation, 0, NULL, &videoSampleBuffer);
NSLog(@"After 'CMSampleBufferCreate', 'result' is: %d", result);

// Set the videoSampleBuffer to ready (is this needed?).
result = CMSampleBufferMakeDataReady(videoSampleBuffer);
NSLog(@"After 'CMSampleBufferMakeDataReady', 'result' is: %d", result);

// Start writing...
if ([videoFileWriter startWriting]) {
    [videoFileWriter startSessionAtSourceTime:kCMTimeZero];
}

// Start the first while loop (DEBUG)...

Приветствуются все идеи, комментарии и предложения.

Благодарю вас!

7
задан Community 9 August 2012 в 16:36
поделиться