SlideShare uma empresa Scribd logo
1 de 22
Baixar para ler offline
Utilizing AVFoundation at Dubsmash
● First off - Gasper
● Funded my own mobile dev company back in Slovenia
● Past half a year driving the crazy train that is Dubsmash’s iOS app
● Dubsmash is aiming to revolutionize the way we do video communication
Unavoidable intro
Who the fu*k am I?
● Video capture
● Stitching together several video parts
● Merging sound with video
● Rendering additional layers on top of the video
Video creation process in Dubsmash app
Overview
Video capture
Video capture
It all starts here...
Key components
● Audio player
● Video camera object
Obstacles to overcome
● Different screen sizes and aspect ratios
● Keeping video capture in sync with sound
● Make the video personal by maintaining eye contact
Video capture
VideoCamera class
Just a few publicly exposed functions
● Able to initialize a new AVCaptureMovieFileOutput
● Rotate camera
● Start and stop capture
Video capture
VideoCamera class
func initializeNewMovieFileOutput() -> AVCaptureMovieFileOutput {
resetCurrentMovieFileOutput()
captureSession .beginConfiguration()
let newMovieFileOutput = AVCaptureMovieFileOutput()
if captureSession .canAddOutput(newMovieFileOutput) {
captureSession .addOutput(newMovieFileOutput)
}
captureSession .commitConfiguration()
return newMovieFileOutput
}
Title of the slide
Initial video rendering
Initial video rendering
RenderEngine class
RenderEngine class with several video rendering capabilities
● Merging video files
● Adding sound to a video object
● Drawing addition layers on top of video
● Compressing video
Initial video rendering
Merging video parts
● Length of the output video is constrained to audio asset’s duration
● Stitching the video parts together using AVMutableComposition
○ Leads to possible discrepancies between the video and audio length, so we
need to make sure to scale video parts to appropriate lengths
● Using AVMutableVideoCompositionInstruction which contains an
AVMutableVideoCompositionLayerInstruction for every video part in
its layerInstructions property
● In the end export through AVAssetExportSession
Initial video rendering
Merging video parts
do {
let mutableComposition = AVMutableComposition()
for videoAsset in videoAssets {
let videoTrack = mutableComposition.addMutableTrackWithMediaType
(AVMediaTypeVideo, preferredTrackID: kCMPersistentTrackID_Invalid)
guard let videoAssetTrack = videoAsset.tracksWithMediaType(AVMediaTypeVideo).first
else { throw NSError(...) }
...
1. Wrapping everything in a do - catch statement
2. Creating a AVMutableComposition
3. Extracting an AVAssetTrack for every video part
Initial video rendering
Merging video parts
let adjustedDuration = CMTime(seconds: videoAsset.duration.seconds +
durationDifferencePerClip, preferredTimescale: videoAsset.duration.timescale)
try videoTrack.insertTimeRange(
CMTimeRange(start: kCMTimeZero, duration: videoAsset.duration),
ofTrack: videoAssetTrack,
atTime: timeOffset)
videoTrack.scaleTimeRange(CMTimeRange(start: timeOffset, duration: videoAsset.duration),
toDuration: adjustedDuration)
4. Scaling AVAssetTrack to appropriate length
Initial video rendering
Merging video parts
let layerInstruction = AVMutableVideoCompositionLayerInstruction(assetTrack: videoTrack)
mainInstruction.layerInstructions.append(layerInstruction)
layerInstruction.setOpacity(
mainInstruction.layerInstructions.count < videoAssets.count ? 0 : 1,
atTime: timeOffset + adjustedDuration)
var layerTransform = videoAssetTrack.preferredTransform
// ... stuff with transforms
layerInstruction.setTransform(layerTransform, atTime: kCMTimeZero)
5. Setting appropriate layer instruction
Initial video rendering
Merging video parts
exportSession = AVAssetExportSession(asset: asset, presetName: exportPreset)
exportSession?.videoComposition = videoComposition
exportSession?.outputFileType = AVFileTypeMPEG4
exportSession?.shouldOptimizeForNetworkUse = true
taskCompletion = BFTaskCompletionSource()
let appEnteredBackgroundSignal = // Signal for UIApplicationDidEnterBackgroundNotification
appEnteredBackgroundSignal.subscribeNext { _ in
cancelExport()
}
exportSession?.exportAsynchronouslyWithCompletionHandler { … }
6. Exporting through AVAssetExportSession
Initial video rendering
Adding sound to video
● Sound and video playing together from different sources results in apparent lack
of synchronization between the two
● To mitigate this problem we add sound to the video through creating an
AVMutableComposition object with two AVAssetTracks
let audioAssetTrack = audioAsset.tracksWithMediaType(AVMediaTypeAudio).first
let videoAssetTrack = videoAsset.tracksWithMediaType(AVMediaTypeVideo).first
Rendering additional layers
Rendering additional layers
Rendering text on top of video
● Users have the ability to enrich the video through text, filters and stickers
● Code snippet for rendering text:
let textImage = textField.screenshot()
videoContainer .convertRect(textField.frame, fromView: textField.superview))
let videoLayer = addLayerOverlayToVideoComposition( videoComposition )
let textLayer = CALayer()
textLayer.bounds = CGRect(x: 0, y: 0,
width: textImage.size.width, height: textImage.size.height)
textLayer.contents = textImage.CGImage
videoLayer.addSublayer(textLayer)
Rendering additional layers
Rendering text on top of video
let parentLayer = CALayer()
parentLayer.bounds = CGRect(origin: CGPointZero, size: exportSize)
parentLayer.anchorPoint = CGPointZero
parentLayer.position = CGPointZero
let videoLayer = CALayer()
videoLayer.bounds = parentLayer.bounds
parentLayer.addSublayer(videoLayer)
videoLayer.position = CGPoint(x: parentLayer.bounds.width / 2,
y: parentLayer.bounds.height / 2)
let layer = CALayer()
layer.frame = parentLayer.bounds
parentLayer.addSublayer(layer)
videoComposition.animationTool = AVVideoCompositionCoreAnimationTool(
postProcessingAsVideoLayer: videoLayer, inLayer: parentLayer)
return layer
Common pitfalls
Common pitfalls
Love / hate relationship with AVFoundation
● Doing practically anything AV related on a background thread → Crash
○ Your best friend is now:
UIApplication.sharedApplication().applicationState == .Active
● Setting max recorded duration on a AVCaptureMovieFileOutput? Who
cares! AVFoundation certainly doesn’t…
● Something is bound to go wrong at a certain time, thankfully we have these
descriptive errors popping up:
Error Domain=NSOSStatusErrorDomain Code=-12780
"The operation couldn’t be completed. (OSStatus error -12780.)"
Shameless plug
Looking for mobile devs, iOS & Android
Questions

Mais conteúdo relacionado

Semelhante a Utilizing AVFoundation at dubsmash

Understanding Our Editing Software
Understanding Our Editing SoftwareUnderstanding Our Editing Software
Understanding Our Editing Software
jamsjamsjams
 
Cam Studio Introduction
Cam Studio IntroductionCam Studio Introduction
Cam Studio Introduction
barrymacd
 
Screenflow Podcampaz
Screenflow PodcampazScreenflow Podcampaz
Screenflow Podcampaz
Terry Lee
 
Veronica's Comparison
Veronica's ComparisonVeronica's Comparison
Veronica's Comparison
Veronica
 
adobe premiere pro.ppt
adobe premiere pro.pptadobe premiere pro.ppt
adobe premiere pro.ppt
VeronicGomez
 
Manual after effects us
Manual after effects usManual after effects us
Manual after effects us
miacademy
 

Semelhante a Utilizing AVFoundation at dubsmash (20)

[@NaukriEngineering] Video handlings on apple platforms
[@NaukriEngineering] Video handlings on apple platforms[@NaukriEngineering] Video handlings on apple platforms
[@NaukriEngineering] Video handlings on apple platforms
 
Unit 3 Lesson 09
Unit 3 Lesson 09Unit 3 Lesson 09
Unit 3 Lesson 09
 
Understanding Our Editing Software
Understanding Our Editing SoftwareUnderstanding Our Editing Software
Understanding Our Editing Software
 
Cam Studio Introduction
Cam Studio IntroductionCam Studio Introduction
Cam Studio Introduction
 
Screenflow Podcampaz
Screenflow PodcampazScreenflow Podcampaz
Screenflow Podcampaz
 
Adobe Session on Flash Online Conference #12
Adobe Session on Flash Online Conference #12Adobe Session on Flash Online Conference #12
Adobe Session on Flash Online Conference #12
 
Advanced AV Foundation (CocoaConf, Aug '11)
Advanced AV Foundation (CocoaConf, Aug '11)Advanced AV Foundation (CocoaConf, Aug '11)
Advanced AV Foundation (CocoaConf, Aug '11)
 
Studio gsg
Studio gsgStudio gsg
Studio gsg
 
Studio gsg
Studio gsgStudio gsg
Studio gsg
 
Video editing Course
Video editing CourseVideo editing Course
Video editing Course
 
Moviemaker
MoviemakerMoviemaker
Moviemaker
 
How to implement camera recording for USB webcam or IP camera in C#.NET
How to implement camera recording for USB webcam or IP camera in C#.NETHow to implement camera recording for USB webcam or IP camera in C#.NET
How to implement camera recording for USB webcam or IP camera in C#.NET
 
WebRTC Standards & Implementation Q&A - getDisplayMedia 1.0
WebRTC Standards & Implementation Q&A - getDisplayMedia 1.0WebRTC Standards & Implementation Q&A - getDisplayMedia 1.0
WebRTC Standards & Implementation Q&A - getDisplayMedia 1.0
 
Veronica's Comparison
Veronica's ComparisonVeronica's Comparison
Veronica's Comparison
 
Veronica V
Veronica VVeronica V
Veronica V
 
adobe premiere pro.ppt
adobe premiere pro.pptadobe premiere pro.ppt
adobe premiere pro.ppt
 
create-netflix-clone-01-introduction.pdf
create-netflix-clone-01-introduction.pdfcreate-netflix-clone-01-introduction.pdf
create-netflix-clone-01-introduction.pdf
 
voip2day 2016: mediasoup, powerful WebRTC SFU for Node.js
voip2day 2016: mediasoup, powerful WebRTC SFU for Node.jsvoip2day 2016: mediasoup, powerful WebRTC SFU for Node.js
voip2day 2016: mediasoup, powerful WebRTC SFU for Node.js
 
Pinnacle Video Project 2
Pinnacle Video Project 2Pinnacle Video Project 2
Pinnacle Video Project 2
 
Manual after effects us
Manual after effects usManual after effects us
Manual after effects us
 

Último

Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Dr.Costas Sachpazis
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Christo Ananth
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
ankushspencer015
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
rknatarajan
 

Último (20)

UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSIS
 
Glass Ceramics: Processing and Properties
Glass Ceramics: Processing and PropertiesGlass Ceramics: Processing and Properties
Glass Ceramics: Processing and Properties
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
 
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
 
chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineering
 
Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...
 
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELLPVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
 

Utilizing AVFoundation at dubsmash

  • 2. ● First off - Gasper ● Funded my own mobile dev company back in Slovenia ● Past half a year driving the crazy train that is Dubsmash’s iOS app ● Dubsmash is aiming to revolutionize the way we do video communication Unavoidable intro Who the fu*k am I?
  • 3. ● Video capture ● Stitching together several video parts ● Merging sound with video ● Rendering additional layers on top of the video Video creation process in Dubsmash app Overview
  • 5. Video capture It all starts here... Key components ● Audio player ● Video camera object Obstacles to overcome ● Different screen sizes and aspect ratios ● Keeping video capture in sync with sound ● Make the video personal by maintaining eye contact
  • 6. Video capture VideoCamera class Just a few publicly exposed functions ● Able to initialize a new AVCaptureMovieFileOutput ● Rotate camera ● Start and stop capture
  • 7. Video capture VideoCamera class func initializeNewMovieFileOutput() -> AVCaptureMovieFileOutput { resetCurrentMovieFileOutput() captureSession .beginConfiguration() let newMovieFileOutput = AVCaptureMovieFileOutput() if captureSession .canAddOutput(newMovieFileOutput) { captureSession .addOutput(newMovieFileOutput) } captureSession .commitConfiguration() return newMovieFileOutput }
  • 8. Title of the slide Initial video rendering
  • 9. Initial video rendering RenderEngine class RenderEngine class with several video rendering capabilities ● Merging video files ● Adding sound to a video object ● Drawing addition layers on top of video ● Compressing video
  • 10. Initial video rendering Merging video parts ● Length of the output video is constrained to audio asset’s duration ● Stitching the video parts together using AVMutableComposition ○ Leads to possible discrepancies between the video and audio length, so we need to make sure to scale video parts to appropriate lengths ● Using AVMutableVideoCompositionInstruction which contains an AVMutableVideoCompositionLayerInstruction for every video part in its layerInstructions property ● In the end export through AVAssetExportSession
  • 11. Initial video rendering Merging video parts do { let mutableComposition = AVMutableComposition() for videoAsset in videoAssets { let videoTrack = mutableComposition.addMutableTrackWithMediaType (AVMediaTypeVideo, preferredTrackID: kCMPersistentTrackID_Invalid) guard let videoAssetTrack = videoAsset.tracksWithMediaType(AVMediaTypeVideo).first else { throw NSError(...) } ... 1. Wrapping everything in a do - catch statement 2. Creating a AVMutableComposition 3. Extracting an AVAssetTrack for every video part
  • 12. Initial video rendering Merging video parts let adjustedDuration = CMTime(seconds: videoAsset.duration.seconds + durationDifferencePerClip, preferredTimescale: videoAsset.duration.timescale) try videoTrack.insertTimeRange( CMTimeRange(start: kCMTimeZero, duration: videoAsset.duration), ofTrack: videoAssetTrack, atTime: timeOffset) videoTrack.scaleTimeRange(CMTimeRange(start: timeOffset, duration: videoAsset.duration), toDuration: adjustedDuration) 4. Scaling AVAssetTrack to appropriate length
  • 13. Initial video rendering Merging video parts let layerInstruction = AVMutableVideoCompositionLayerInstruction(assetTrack: videoTrack) mainInstruction.layerInstructions.append(layerInstruction) layerInstruction.setOpacity( mainInstruction.layerInstructions.count < videoAssets.count ? 0 : 1, atTime: timeOffset + adjustedDuration) var layerTransform = videoAssetTrack.preferredTransform // ... stuff with transforms layerInstruction.setTransform(layerTransform, atTime: kCMTimeZero) 5. Setting appropriate layer instruction
  • 14. Initial video rendering Merging video parts exportSession = AVAssetExportSession(asset: asset, presetName: exportPreset) exportSession?.videoComposition = videoComposition exportSession?.outputFileType = AVFileTypeMPEG4 exportSession?.shouldOptimizeForNetworkUse = true taskCompletion = BFTaskCompletionSource() let appEnteredBackgroundSignal = // Signal for UIApplicationDidEnterBackgroundNotification appEnteredBackgroundSignal.subscribeNext { _ in cancelExport() } exportSession?.exportAsynchronouslyWithCompletionHandler { … } 6. Exporting through AVAssetExportSession
  • 15. Initial video rendering Adding sound to video ● Sound and video playing together from different sources results in apparent lack of synchronization between the two ● To mitigate this problem we add sound to the video through creating an AVMutableComposition object with two AVAssetTracks let audioAssetTrack = audioAsset.tracksWithMediaType(AVMediaTypeAudio).first let videoAssetTrack = videoAsset.tracksWithMediaType(AVMediaTypeVideo).first
  • 17. Rendering additional layers Rendering text on top of video ● Users have the ability to enrich the video through text, filters and stickers ● Code snippet for rendering text: let textImage = textField.screenshot() videoContainer .convertRect(textField.frame, fromView: textField.superview)) let videoLayer = addLayerOverlayToVideoComposition( videoComposition ) let textLayer = CALayer() textLayer.bounds = CGRect(x: 0, y: 0, width: textImage.size.width, height: textImage.size.height) textLayer.contents = textImage.CGImage videoLayer.addSublayer(textLayer)
  • 18. Rendering additional layers Rendering text on top of video let parentLayer = CALayer() parentLayer.bounds = CGRect(origin: CGPointZero, size: exportSize) parentLayer.anchorPoint = CGPointZero parentLayer.position = CGPointZero let videoLayer = CALayer() videoLayer.bounds = parentLayer.bounds parentLayer.addSublayer(videoLayer) videoLayer.position = CGPoint(x: parentLayer.bounds.width / 2, y: parentLayer.bounds.height / 2) let layer = CALayer() layer.frame = parentLayer.bounds parentLayer.addSublayer(layer) videoComposition.animationTool = AVVideoCompositionCoreAnimationTool( postProcessingAsVideoLayer: videoLayer, inLayer: parentLayer) return layer
  • 20. Common pitfalls Love / hate relationship with AVFoundation ● Doing practically anything AV related on a background thread → Crash ○ Your best friend is now: UIApplication.sharedApplication().applicationState == .Active ● Setting max recorded duration on a AVCaptureMovieFileOutput? Who cares! AVFoundation certainly doesn’t… ● Something is bound to go wrong at a certain time, thankfully we have these descriptive errors popping up: Error Domain=NSOSStatusErrorDomain Code=-12780 "The operation couldn’t be completed. (OSStatus error -12780.)"
  • 21. Shameless plug Looking for mobile devs, iOS & Android