Advertisement
Guest User

Untitled

a guest
Aug 20th, 2014
278
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.81 KB | None | 0 0
  1. -(void) writeImagesToMovieAtPath:(NSString *) path withSize:(CGSize) size
  2. {
  3. if ([[NSFileManager defaultManager] fileExistsAtPath:path])
  4. {
  5. [[NSFileManager defaultManager]removeItemAtPath:path error:nil];
  6. }
  7.  
  8. NSLog(@"Started");
  9. NSError *error = nil;
  10. AVAssetWriter *videoWriter = [[AVAssetWriter alloc] initWithURL:
  11. [NSURL fileURLWithPath:path] fileType:AVFileTypeMPEG4
  12. error:&error];
  13. NSParameterAssert(videoWriter);
  14. NSDictionary *videoSettings = [NSDictionary dictionaryWithObjectsAndKeys:
  15. AVVideoCodecH264, AVVideoCodecKey,
  16. [NSNumber numberWithInt:size.width], AVVideoWidthKey,
  17. [NSNumber numberWithInt:size.height], AVVideoHeightKey,
  18. nil];
  19. AVAssetWriterInput* videoWriterInput = [AVAssetWriterInput
  20. assetWriterInputWithMediaType:AVMediaTypeVideo
  21. outputSettings:videoSettings] ;
  22. AVAssetWriterInputPixelBufferAdaptor *adaptor = [AVAssetWriterInputPixelBufferAdaptor
  23. assetWriterInputPixelBufferAdaptorWithAssetWriterInput:videoWriterInput
  24. sourcePixelBufferAttributes:nil];
  25. NSParameterAssert(videoWriterInput);
  26. NSParameterAssert([videoWriter canAddInput:videoWriterInput]);
  27. videoWriterInput.expectsMediaDataInRealTime = YES;
  28. [videoWriter addInput:videoWriterInput];
  29. //Start a session:
  30. [videoWriter startWriting];
  31. [videoWriter startSessionAtSourceTime:kCMTimeZero];
  32. //Video encoding
  33. CVPixelBufferRef buffer = NULL;
  34. //convert uiimage to CGImage.
  35. int frameCount = 0;
  36. for(int i = 0; i<[imageArray count]; i++)
  37. {
  38. buffer = [self pixelBufferFromCGImage:[[imageArray objectAtIndex:i] CGImage] ];
  39. BOOL append_ok = NO;
  40. int j = 0;
  41. while (!append_ok && j< 30)
  42. {
  43. if (adaptor.assetWriterInput.readyForMoreMediaData)
  44. {
  45. printf("appending %d attemp %d\n", frameCount, j);
  46. CMTime frameTime = CMTimeMake(frameCount,(int32_t) 10);
  47. append_ok = [adaptor appendPixelBuffer:buffer withPresentationTime:frameTime];
  48. /* CVPixelBufferPoolRef bufferPool = adaptor.pixelBufferPool;
  49. NSParameterAssert(bufferPool != NULL);*/
  50. [NSThread sleepForTimeInterval:0.05];
  51. }
  52. else
  53. {
  54. printf("adaptor not ready %d, %d\n", frameCount, j);
  55. [NSThread sleepForTimeInterval:0.1];
  56. }
  57. j++;
  58. }
  59. if (!append_ok)
  60. {
  61. printf("error appending image %d times %d\n", frameCount, j);
  62. }
  63. frameCount++;
  64. CVBufferRelease(buffer);
  65. }
  66. [videoWriterInput markAsFinished];
  67. [videoWriter finishWriting];
  68.  
  69.  
  70. // [m_PictArray removeAllObjects];
  71. NSLog(@"Write Ended");
  72.  
  73. [self CompileFilesToMakeMovie];
  74.  
  75. }
  76.  
  77. - (CVPixelBufferRef) pixelBufferFromCGImage: (CGImageRef) image
  78. {
  79. NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
  80. [NSNumber numberWithBool:YES], kCVPixelBufferCGImageCompatibilityKey,
  81. [NSNumber numberWithBool:YES], kCVPixelBufferCGBitmapContextCompatibilityKey,
  82. nil];
  83. CVPixelBufferRef pxbuffer = NULL;
  84.  
  85. CVPixelBufferCreate(kCFAllocatorDefault, CGImageGetWidth(image),
  86. CGImageGetHeight(image), kCVPixelFormatType_32ARGB, (__bridge CFDictionaryRef) options,
  87. &pxbuffer);
  88.  
  89. CVPixelBufferLockBaseAddress(pxbuffer, 0);
  90. void *pxdata = CVPixelBufferGetBaseAddress(pxbuffer);
  91.  
  92. CGColorSpaceRef rgbColorSpace = CGColorSpaceCreateDeviceRGB();
  93. CGContextRef context = CGBitmapContextCreate(pxdata, CGImageGetWidth(image),
  94. CGImageGetHeight(image), 8, 4*CGImageGetWidth(image), rgbColorSpace,
  95. kCGImageAlphaNoneSkipFirst);
  96.  
  97. CGContextConcatCTM(context, CGAffineTransformMakeRotation(0));
  98.  
  99. CGAffineTransform flipVertical = CGAffineTransformMake(
  100. 1, 0, 0, -1, 0, CGImageGetHeight(image)
  101. );
  102. CGContextConcatCTM(context, flipVertical);
  103.  
  104. CGAffineTransform flipHorizontal = CGAffineTransformMake(
  105. -1.0, 0.0, 0.0, 1.0, CGImageGetWidth(image), 0.0
  106. );
  107.  
  108. CGContextConcatCTM(context, flipHorizontal);
  109.  
  110. CGContextDrawImage(context, CGRectMake(0, 0, CGImageGetWidth(image),
  111. CGImageGetHeight(image)), image);
  112. CGColorSpaceRelease(rgbColorSpace);
  113. CGContextRelease(context);
  114.  
  115. CVPixelBufferUnlockBaseAddress(pxbuffer, 0);
  116.  
  117. return pxbuffer;
  118. }
  119.  
  120. //WRITE AUDIO TO MOVIE CONTAINING IMAGE ARRAY
  121. -(void)CompileFilesToMakeMovie
  122. {
  123. AVMutableComposition* mixComposition = [AVMutableComposition composition];
  124. NSString* audio_inputFileName = @"audio.caf";
  125. NSString* audio_inputFilePath = [NSString stringWithFormat:@"%@/%@", DOCUMENTS_FOLDER,audio_inputFileName];
  126. NSURL* audio_inputFileUrl = [NSURL fileURLWithPath:audio_inputFilePath];
  127. NSString* video_inputFileName = @"video1.mov";
  128. NSString* video_inputFilePath = [NSString stringWithFormat:@"%@/%@", DOCUMENTS_FOLDER,video_inputFileName];
  129. NSURL* video_inputFileUrl = [NSURL fileURLWithPath:video_inputFilePath];
  130. NSString* outputFileName = @"outputFile.mov";
  131. NSString* outputFilePath = [NSString stringWithFormat:@"%@/%@", DOCUMENTS_FOLDER,outputFileName];
  132. NSURL* outputFileUrl = [NSURL fileURLWithPath:outputFilePath];
  133. if ([[NSFileManager defaultManager] fileExistsAtPath:outputFilePath])
  134. [[NSFileManager defaultManager] removeItemAtPath:outputFilePath error:nil];
  135. CMTime nextClipStartTime = kCMTimeZero;
  136. AVURLAsset* videoAsset = [[AVURLAsset alloc]initWithURL:video_inputFileUrl options:nil];
  137. CMTimeRange video_timeRange = CMTimeRangeMake(kCMTimeZero,videoAsset.duration);
  138. AVMutableCompositionTrack *a_compositionVideoTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];
  139. [a_compositionVideoTrack insertTimeRange:video_timeRange ofTrack:[[videoAsset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0] atTime:nextClipStartTime error:nil];
  140. //nextClipStartTime = CMTimeAdd(nextClipStartTime, a_timeRange.duration);
  141. AVURLAsset* audioAsset = [[AVURLAsset alloc]initWithURL:audio_inputFileUrl options:nil];
  142. CMTimeRange audio_timeRange = CMTimeRangeMake(kCMTimeZero, audioAsset.duration);
  143. AVMutableCompositionTrack *b_compositionAudioTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
  144. [b_compositionAudioTrack insertTimeRange:audio_timeRange ofTrack:[[audioAsset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0] atTime:nextClipStartTime error:nil];
  145. AVAssetExportSession* _assetExport = [[AVAssetExportSession alloc] initWithAsset:mixComposition presetName:AVAssetExportPresetHighestQuality];
  146. _assetExport.outputFileType = @"com.apple.quicktime-movie";
  147. _assetExport.outputURL = outputFileUrl;
  148. [_assetExport exportAsynchronouslyWithCompletionHandler:
  149. ^(void ) {
  150. [self saveVideoToAlbum:outputFilePath];
  151. }
  152. ];
  153. }
  154.  
  155. - (void) saveVideoToAlbum:(NSString *)path{
  156. NSLog(@"Saved video to the Album!");
  157.  
  158.  
  159. // Alerting the user of a successful saving and popping to the main view
  160. UIAlertView *successAlert = [[UIAlertView alloc] initWithTitle:@"Success!"
  161. message:@"Your video has been saved to your device's photo album!"
  162. delegate:nil
  163. cancelButtonTitle:@"OK"
  164. otherButtonTitles:nil];
  165. [successAlert show];
  166.  
  167. if(UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(path)){
  168. UISaveVideoAtPathToSavedPhotosAlbum (path, self, @selector(video:didFinishSavingWithError: contextInfo:), nil);
  169. }
  170.  
  171. }
  172.  
  173. - (void) video: (NSString *) videoPath didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo {
  174. NSLog(@"Finished saving video with error: %@", error);
  175. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement