SlideShare a Scribd company logo
1 of 46
Download to read offline
Composing &
Editing Media with
    AV Foundation




          http://bobmccune.com
About...
Bob McCune
‣ MN Developer and Instructor
‣ Owner of TapHarmonic, LLC.
‣ Founded Minnesota CocoaHeads in 2008
Agenda
What will I learn?
 ‣ AV Foundation Overview

 ‣ Media Playback

 ‣ Media Editing

   ‣   Composing Media
   ‣   Mixing Audio
   ‣   Building Video Transitions
   ‣   Layering Visual Content
AV Foundation
Overview
 ‣   Apple’s advanced Objective-C framework for
     working with timed-media
     ‣   High performance, asynchronous processing
     ‣   Hardware accelerated handling of AV media
 ‣   Available in its current form since iOS 4
     ‣   Significant additions and enhancements iOS 5 and 6
     ‣   Default media framework on Mac OS X since 10.7 Lion
 ‣   Apple’s focus for media apps on both iOS and Mac
Where does it fit?
iOS Media Options
    Simple           Awesome         Complex

   MediaPlayer                      CoreAudio

      UIKit                         CoreMedia
                    AVFoundation
                                    CoreVideo


                                   CoreAnimation
AV Essentials
Media Assets
Understanding Assets
‣   AVAsset is an abstract representation of media resource
    modeling the static aspects of the media.
    ‣   Abstracts away the type and location
‣   AVAssetTrack models the static aspects of the
    individual media streams within an asset
    ‣   Tracks are of a uniform type (video, audio, etc.)



AVAssetTrack (Video)


AVAssetTrack (Audio)
Using AVAssets
What can I do with an asset?
 ‣ Inspect
 ‣ Generate Images

 ‣ Transcode and Export

 ‣ Playback
Media Playback
AVPlayer
Playback Controller
‣   AVPlayer is a controller for managing playback
    ‣   play
    ‣   pause
    ‣   rate
    ‣   seekToTime:

‣   Use KVO to observe playback readiness and state
    ‣   status

‣   Timed Observations
    ‣   addPeriodicTimeObserverForInterval:queue:usingBlock
    ‣   addBoundaryTimeObserverForInterval:queue:usingBlock
Playing Media
Static vs Dynamic Models
 ‣ AV Foundation distinguishes between static
   and dynamic aspects of media


                                       AVAsset
        AVAsset                          AVAsset
                                         AVAssetTrack

                       St ati c


                                   AVPlayerItemTrack
       AVPlayerItem                  AVPlayerItemTrack
                                        AVPlayerItemTrack

                      D y n amic
Understanding Time
Core Media Essentials
CMTime
‣   Rational number representing time
    ‣   64-bit integer time value (numerator)
    ‣   32-bit integer time scale (denominator)

        CMTime fiveSeconds = CMTimeMake(5, 1);
        CMTime oneSample = CMTimeMake(1, 44100);
        CMTime zeroTime = kCMTimeZero;


‣   Large number of utility functions in Core Media:
    ‣   CMTimeAdd,CMTimeSubtract,CMTimeCompare, etc.
Understanding Time
Core Media Essentials
CMTimeRange
‣ Core Media struct containing start time and duration


    CMTimeRange assetRange = CMTimeRangeMake(kCMTimeZero, asset.duration);
    CMTimeRange zeroRange = kCMTimeRangeZero;



‣   Like CMTime, there are many Core Media functions:
    ‣   CMTimeRangeEqual, CMTimeRangeContainsTime,
        CMTimeRangeGetEnd, CMTIMERANGE_ISVALID, etc.
Video Playback
AVPlayerLayer

   AVAsset          AVPlayerItem        AVPlayer




   AVAsset
    AVAsset       AVPlayerItemTrack
                   AVPlayerItemTrack
   AVAssetTrack     AVPlayerItemTrack
Video Playback
AVPlayerLayer

   AVPlayerItem        AVPlayer   AVPlayerLayer




 AVPlayerItemTrack
  AVPlayerItemTrack
   AVPlayerItemTrack
Demo
Composing Media
Composing Assets
AVComposition
‣ Concrete extension of AVAsset
‣ Composes asset segments on a timeline
Composing Assets
Tracks and Segments

AVMutableComposition *composition = [AVMutableComposition composition];




                          AVComposition
Composing Assets
Tracks and Segments
CMPersistentTrackID trackID = kCMPersistentTrackID_Invalid;

AVMutableCompositionTrack *videoTrack =
    [composition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:trackID];

AVMutableCompositionTrack *audioTrack =
    [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:trackID];



                               AVComposition
                          AVCompositionTrack (Video)




                          AVCompositionTrack (Audio)
Composing Assets
Tracks and Segments
AVAssetTrack *srcVideoTrack1 = // source video track 1
[videoTrack insertTimeRange:timeRange ofTrack:srcVideoTrack1 atTime:startTime error:&error];

AVAssetTrack *srcVideoTrack2 = // source video track 2
[videoTrack insertTimeRange:timeRange ofTrack:srcVideoTrack2 atTime:startTime error:&error];

AVAssetTrack *srcAudioTrack = // source audio track
[audioTrack insertTimeRange:timeRange ofTrack:srcAudioTrack atTime:startTime error:&error];


                                      AVComposition
                             AVCompositionTrack (Video)

    AVCompositionTrackSegment                       AVCompositionTrackSegment
    Seconds 10-30 of “redpanda.m4v”                   Seconds 20-60 of “waves.m4v”



                             AVCompositionTrack (Audio)
                                AVCompositionTrackSegment
                               Seconds 0-60 of “soundtrack.mp3”
Demo
Mixing Audio
Audio Mixing
AVAudioMix
‣   Composition tracks play at their natural volume
‣   AVAudioMix applies track-level volume adjustments
    ‣   Composed of AVAudioMixInputParameters
    ‣   Parameters control individual track volume over time




              CMTime                    CMTimeRange
AVAudioMix
Example
CMTime fadeTime = CMTimeMake(5, 1);
CMTime fadeInStartTime = kCMTimeZero;
CMTime fadeOutStartTime = CMTimeSubtract(asset.duration, fadeTime);

CMTimeRange fadeInRange = CMTimeRangeMake(fadeInStartTime, fadeTime);
CMTimeRange fadeOutRange = CMTimeRangeMake(fadeOutStartTime, fadeTime);

AVMutableAudioMixInputParameters *parameters =
	   [AVMutableAudioMixInputParameters audioMixInputParameters];
parameters.trackID = assetTrack.trackID;
[parameters setVolumeRampFromStartVolume:0.0 toEndVolume:1.0 timeRange:fadeInRange];
[parameters setVolumeRampFromStartVolume:1.0 toEndVolume:0.0 timeRange:fadeOutRange];

AVMutableAudioMix *audioMix = [AVMutableAudioMix audioMix];
audioMix.inputParameters = @[parameters];
playerItem.audioMix = audioMix;
Demo
Video Transitions
Video Transitions
AVVideoComposition

     AVVideoComposition
                                   Defines how two or more video
                                   tracks are composited together


 AVVideoCompositionInstruction
                                   Configured through collection of
  AVVideoCompositionInstruction
   AVVideoCompositionInstruction   composition instructions describing
                                   compositing behavior
Video Transitions
AVVideoCompositionInstruction

      AVVideoComposition




  AVVideoCompositionInstruction
   AVVideoCompositionInstruction
    AVVideoCompositionInstruction
                                      Defines the time range of
                                      compositing behavior

                                      Composed of layer instructions
          AVAsset
           AVAsset
 AVVideoCompositionLayerInstruction   describing compositing behavior
Video Transitions
AVVideoCompositionLayerInstruction

      AVVideoComposition




  AVVideoCompositionInstruction
   AVVideoCompositionInstruction
    AVVideoCompositionInstruction




          AVAsset
           AVAsset                    Defines the transform and
 AVVideoCompositionLayerInstruction
                                      opacity ramps of input layers
                                      Transform and opacity changes
                                      modified over given time range
Building Transitions
Conceptual Steps
Building Transitions   1
Stagger Layout


A

B
Building Transitions         2
Define Overlapping Regions


A

B
Building Transitions                                     3
Define Time Ranges


A
           Passthrough     Passthrough     Passthrough



B
                    Transition     Transition


      * Time ranges must not have gaps or overlap
 * Total duration must not be shorter than composition
Building Transitions                                          4
Configure Instructions
// Build transition instructions
AVMutableVideoCompositionInstruction *transitionInstruction = ...;
transitionInstruction.timeRange = transitionTimeRange;

AVMutableVideoCompositionLayerInstruction *fromLayerInstruction = ...;
AVMutableVideoCompositionLayerInstruction *toLayerInstruction = ...;

// Cross Disolve
[fromLayerInstruction setOpacityRampFromStartOpacity:1.0
                                        toEndOpacity:0.0
                                           timeRange:transitionTimeRange];

NSArray *instructions = @[fromLayerInstruction, toLayerInstruction];
transitionInstruction.layerInstructions = instructions;
[instructions addObject:transitionInstruction];
Building Transitions                                    5
Set sizes and apply
#define FRAME_RATE CMTimeMake(1, 30)
#define RENDER_SIZE CGSizeMake(1280, 720)


AVMutableVideoComposition *videoComposition =
    [AVMutableVideoComposition videoComposition];

// Set instructions on AVVideoComposition instance
videoComposition.instructions = instructions;
videoComposition.frameDuration = FRAME_RATE;
videoComposition.renderSize = RENDER_SIZE;

AVPlayerItem *playerItem =
   [AVPlayerItem playerItemWithAsset:[composition copy]];
playerItem.videoComposition = videoComposition;
New in iOS 6
AVVideoComposition


 videoCompositionWithPropertiesOfAsset:

 Automagic Setup:
• Calculates all required passthrough and transition time ranges
• Builds appropriate composition and layer instructions for time ranges
• Sets the appropriate render size
• Sets the appropriate frame rate
Demo
Layering Content
Layering Content
Core Animation
Core Animation a natural choice
  ‣ High performance, inherently time-based

  ‣ CALayer subclasses used for all video rendering



  CALayer: used to layer images and text

  CAAnimation: used to animate layered content


   CABasicAnimation


                                   CAKeyframeAnimation
Animation Timing
AVSynchronizedLayer
‣   Core Animation operates on host time
    ‣   Starts at boot, marches towards infinity
‣   Timeline animations need to use movie time
    ‣   Starts at kCMTimeZero and runs to duration
    ‣   Can be started, stopped, rewound, etc.
‣   Use AVSynchronizedLayer to use movie time
    ‣   Confers player item timing on to its sublayer tree

         AVPlayerItem         AVSynchronizedLayer



                                 CATextLayer            CABasicAnimation
Core Animation
 Timeline vs Realtime Animations
‣ Exactly    the same, but different:
  ‣   Animations with zero beginTime won’t be seen
      ‣   Set beginTime = AVCoreAnimationBeginTimeZero
  ‣   Animations removed by default
      ‣   Set removedOnCompletion = NO
      ‣   Unable to use CAAnimationGroup?
Core Animation
Natural Choice, Awkward Implementation
‣   Different conceptual models for timeline editing
    ‣   CMTime and CMTimeRange for asset items
    ‣   Seconds and milliseconds for layers
    ‣   Build abstraction to help bridge the gap
‣   Usage differs in playback and export scenarios
    ‣   AVSynchronizedLayer for playback
        ‣   Attach to player’s view hierarchy/layer tree
    ‣   AVVideoCompositionCoreAnimationTool for export
Demo
Summary
AV Foundation Rocks!
‣ Powerful tools for audio and video playback

    ‣   AVPlayer, AVPlayerItem, AVPlayerLayer
‣   Powerful tools for composing/editing media:
    ‣   AVComposition, AVAudioMix,
        AVVideoComposition, AVSynchronizedLayer
‣   Powerful utility classes:
    ‣   AVAssetImageGenerator
    ‣   AVExportSession
‣   Steep learning curve, but worth the investment!
Resources
Presentation Materials
http://www.speakerdeck.com/bobmccune/
http://www.slideshare.net/bobmccune/
https://github.com/tapharmonic/AVFoundationEditor

Learning AV Foundation
http://www.speakerdeck.com/bobmccune/
https://github.com/tapharmonic/AVFoundationDemos

WWDC 2011: Exploring AV Foundation
https://developer.apple.com/videos/wwdc/2011/?id=405

WWDC 2011: Working with Media in AV Foundation
https://developer.apple.com/videos/wwdc/2011/?id=415

    BobMcCune.com                                      @bobmccune

More Related Content

What's hot

Implementing Early Hints in Chrome - Approaches and Challenges
Implementing Early Hints in Chrome - Approaches and ChallengesImplementing Early Hints in Chrome - Approaches and Challenges
Implementing Early Hints in Chrome - Approaches and ChallengesViet-Hoang Tran
 
A Practical Introduction to git
A Practical Introduction to gitA Practical Introduction to git
A Practical Introduction to gitEmanuele Olivetti
 
Build your own embedded linux distributions by yocto project
Build your own embedded linux distributions by yocto projectBuild your own embedded linux distributions by yocto project
Build your own embedded linux distributions by yocto projectYen-Chin Lee
 
MediaPlayer Playing Flow
MediaPlayer Playing FlowMediaPlayer Playing Flow
MediaPlayer Playing FlowJavid Hsu
 
Userfaultfd: Current Features, Limitations and Future Development
Userfaultfd: Current Features, Limitations and Future DevelopmentUserfaultfd: Current Features, Limitations and Future Development
Userfaultfd: Current Features, Limitations and Future DevelopmentKernel TLV
 
Custom SRP and graphics workflows - Unite Copenhagen 2019
Custom SRP and graphics workflows - Unite Copenhagen 2019Custom SRP and graphics workflows - Unite Copenhagen 2019
Custom SRP and graphics workflows - Unite Copenhagen 2019Unity Technologies
 
Introduce fuego
Introduce fuegoIntroduce fuego
Introduce fuegos60030
 
HTML5 Apps on AGL Platform with the Web Application Manager (Automotive Grade...
HTML5 Apps on AGL Platform with the Web Application Manager (Automotive Grade...HTML5 Apps on AGL Platform with the Web Application Manager (Automotive Grade...
HTML5 Apps on AGL Platform with the Web Application Manager (Automotive Grade...Igalia
 
Test Driven Development & CI/CD
Test Driven Development & CI/CDTest Driven Development & CI/CD
Test Driven Development & CI/CDShanmuga S Muthu
 
How we optimized our Game - Jake & Tess' Finding Monsters Adventure
How we optimized our Game - Jake & Tess' Finding Monsters AdventureHow we optimized our Game - Jake & Tess' Finding Monsters Adventure
How we optimized our Game - Jake & Tess' Finding Monsters AdventureFelipe Lira
 
Video Editing Softwares
Video Editing Softwares Video Editing Softwares
Video Editing Softwares ashraf ali
 
강좌 06 부트로더
강좌 06 부트로더강좌 06 부트로더
강좌 06 부트로더chcbaram
 

What's hot (20)

Implementing Early Hints in Chrome - Approaches and Challenges
Implementing Early Hints in Chrome - Approaches and ChallengesImplementing Early Hints in Chrome - Approaches and Challenges
Implementing Early Hints in Chrome - Approaches and Challenges
 
A Practical Introduction to git
A Practical Introduction to gitA Practical Introduction to git
A Practical Introduction to git
 
Build your own embedded linux distributions by yocto project
Build your own embedded linux distributions by yocto projectBuild your own embedded linux distributions by yocto project
Build your own embedded linux distributions by yocto project
 
Interrupts
InterruptsInterrupts
Interrupts
 
Overview of github
Overview of githubOverview of github
Overview of github
 
MediaPlayer Playing Flow
MediaPlayer Playing FlowMediaPlayer Playing Flow
MediaPlayer Playing Flow
 
Userfaultfd: Current Features, Limitations and Future Development
Userfaultfd: Current Features, Limitations and Future DevelopmentUserfaultfd: Current Features, Limitations and Future Development
Userfaultfd: Current Features, Limitations and Future Development
 
Custom SRP and graphics workflows - Unite Copenhagen 2019
Custom SRP and graphics workflows - Unite Copenhagen 2019Custom SRP and graphics workflows - Unite Copenhagen 2019
Custom SRP and graphics workflows - Unite Copenhagen 2019
 
Yocto project
Yocto projectYocto project
Yocto project
 
VIDEO CODECS
VIDEO CODECSVIDEO CODECS
VIDEO CODECS
 
Introduce fuego
Introduce fuegoIntroduce fuego
Introduce fuego
 
HTML5 Apps on AGL Platform with the Web Application Manager (Automotive Grade...
HTML5 Apps on AGL Platform with the Web Application Manager (Automotive Grade...HTML5 Apps on AGL Platform with the Web Application Manager (Automotive Grade...
HTML5 Apps on AGL Platform with the Web Application Manager (Automotive Grade...
 
BusyBox for Embedded Linux
BusyBox for Embedded LinuxBusyBox for Embedded Linux
BusyBox for Embedded Linux
 
Understanding open max il
Understanding open max ilUnderstanding open max il
Understanding open max il
 
Test Driven Development & CI/CD
Test Driven Development & CI/CDTest Driven Development & CI/CD
Test Driven Development & CI/CD
 
Binder: Android IPC
Binder: Android IPCBinder: Android IPC
Binder: Android IPC
 
Git & git hub
Git & git hubGit & git hub
Git & git hub
 
How we optimized our Game - Jake & Tess' Finding Monsters Adventure
How we optimized our Game - Jake & Tess' Finding Monsters AdventureHow we optimized our Game - Jake & Tess' Finding Monsters Adventure
How we optimized our Game - Jake & Tess' Finding Monsters Adventure
 
Video Editing Softwares
Video Editing Softwares Video Editing Softwares
Video Editing Softwares
 
강좌 06 부트로더
강좌 06 부트로더강좌 06 부트로더
강좌 06 부트로더
 

Viewers also liked

Drawing with Quartz on iOS
Drawing with Quartz on iOSDrawing with Quartz on iOS
Drawing with Quartz on iOSBob McCune
 
Creating Container View Controllers
Creating Container View ControllersCreating Container View Controllers
Creating Container View ControllersBob McCune
 
Core Animation
Core AnimationCore Animation
Core AnimationBob McCune
 
Objective-C for Java Developers
Objective-C for Java DevelopersObjective-C for Java Developers
Objective-C for Java DevelopersBob McCune
 
Building Modern Audio Apps with AVAudioEngine
Building Modern Audio Apps with AVAudioEngineBuilding Modern Audio Apps with AVAudioEngine
Building Modern Audio Apps with AVAudioEngineBob McCune
 
Quartz 2D with Swift 3
Quartz 2D with Swift 3Quartz 2D with Swift 3
Quartz 2D with Swift 3Bob McCune
 
Forward Swift 2017: Media Frameworks and Swift: This Is Fine
Forward Swift 2017: Media Frameworks and Swift: This Is FineForward Swift 2017: Media Frameworks and Swift: This Is Fine
Forward Swift 2017: Media Frameworks and Swift: This Is FineChris Adamson
 
Android程序的编译,安装和运行 | 小米科技 汪文俊
Android程序的编译,安装和运行 | 小米科技 汪文俊Android程序的编译,安装和运行 | 小米科技 汪文俊
Android程序的编译,安装和运行 | 小米科技 汪文俊imShining @DevCamp
 
Utilizing AVFoundation at dubsmash
Utilizing AVFoundation at dubsmashUtilizing AVFoundation at dubsmash
Utilizing AVFoundation at dubsmashGašper Kolenc
 
AVFoundation @ TACOW 2013 05 14
AVFoundation @ TACOW 2013 05 14AVFoundation @ TACOW 2013 05 14
AVFoundation @ TACOW 2013 05 14Ryder Mackay
 
After Effects CC with Cinema 4D Lite
After Effects CC with Cinema 4D LiteAfter Effects CC with Cinema 4D Lite
After Effects CC with Cinema 4D Liteayman diab
 
Introduction to AV Foundation
Introduction to AV FoundationIntroduction to AV Foundation
Introduction to AV FoundationChris Adamson
 
Starting Core Animation
Starting Core AnimationStarting Core Animation
Starting Core AnimationJohn Wilker
 
Open GL Animation
Open GL  AnimationOpen GL  Animation
Open GL AnimationKiran Munir
 
20 iOS developer interview questions
20 iOS developer interview questions20 iOS developer interview questions
20 iOS developer interview questionsArc & Codementor
 
iOS Developer Interview Questions
iOS Developer Interview QuestionsiOS Developer Interview Questions
iOS Developer Interview QuestionsClark Davidson
 
Audio Unit Extensions 〜オーディオエフェクトのアプリ間共有〜
Audio Unit Extensions 〜オーディオエフェクトのアプリ間共有〜Audio Unit Extensions 〜オーディオエフェクトのアプリ間共有〜
Audio Unit Extensions 〜オーディオエフェクトのアプリ間共有〜Shuichi Tsutsumi
 
Core Graphics & Core Animation
Core Graphics & Core AnimationCore Graphics & Core Animation
Core Graphics & Core AnimationAndreas Blick
 

Viewers also liked (20)

Drawing with Quartz on iOS
Drawing with Quartz on iOSDrawing with Quartz on iOS
Drawing with Quartz on iOS
 
Creating Container View Controllers
Creating Container View ControllersCreating Container View Controllers
Creating Container View Controllers
 
Core Animation
Core AnimationCore Animation
Core Animation
 
Objective-C for Java Developers
Objective-C for Java DevelopersObjective-C for Java Developers
Objective-C for Java Developers
 
Building Modern Audio Apps with AVAudioEngine
Building Modern Audio Apps with AVAudioEngineBuilding Modern Audio Apps with AVAudioEngine
Building Modern Audio Apps with AVAudioEngine
 
Quartz 2D with Swift 3
Quartz 2D with Swift 3Quartz 2D with Swift 3
Quartz 2D with Swift 3
 
Forward Swift 2017: Media Frameworks and Swift: This Is Fine
Forward Swift 2017: Media Frameworks and Swift: This Is FineForward Swift 2017: Media Frameworks and Swift: This Is Fine
Forward Swift 2017: Media Frameworks and Swift: This Is Fine
 
Android程序的编译,安装和运行 | 小米科技 汪文俊
Android程序的编译,安装和运行 | 小米科技 汪文俊Android程序的编译,安装和运行 | 小米科技 汪文俊
Android程序的编译,安装和运行 | 小米科技 汪文俊
 
Utilizing AVFoundation at dubsmash
Utilizing AVFoundation at dubsmashUtilizing AVFoundation at dubsmash
Utilizing AVFoundation at dubsmash
 
AVFoundation @ TACOW 2013 05 14
AVFoundation @ TACOW 2013 05 14AVFoundation @ TACOW 2013 05 14
AVFoundation @ TACOW 2013 05 14
 
After Effects CC with Cinema 4D Lite
After Effects CC with Cinema 4D LiteAfter Effects CC with Cinema 4D Lite
After Effects CC with Cinema 4D Lite
 
Introduction to AV Foundation
Introduction to AV FoundationIntroduction to AV Foundation
Introduction to AV Foundation
 
Starting Core Animation
Starting Core AnimationStarting Core Animation
Starting Core Animation
 
Stupid Video Tricks
Stupid Video TricksStupid Video Tricks
Stupid Video Tricks
 
Open GL Animation
Open GL  AnimationOpen GL  Animation
Open GL Animation
 
Animation in iOS
Animation in iOSAnimation in iOS
Animation in iOS
 
20 iOS developer interview questions
20 iOS developer interview questions20 iOS developer interview questions
20 iOS developer interview questions
 
iOS Developer Interview Questions
iOS Developer Interview QuestionsiOS Developer Interview Questions
iOS Developer Interview Questions
 
Audio Unit Extensions 〜オーディオエフェクトのアプリ間共有〜
Audio Unit Extensions 〜オーディオエフェクトのアプリ間共有〜Audio Unit Extensions 〜オーディオエフェクトのアプリ間共有〜
Audio Unit Extensions 〜オーディオエフェクトのアプリ間共有〜
 
Core Graphics & Core Animation
Core Graphics & Core AnimationCore Graphics & Core Animation
Core Graphics & Core Animation
 

Similar to Composing and Editing Media with AV Foundation

[@NaukriEngineering] Video handlings on apple platforms
[@NaukriEngineering] Video handlings on apple platforms[@NaukriEngineering] Video handlings on apple platforms
[@NaukriEngineering] Video handlings on apple platformsNaukri.com
 
Stupid Video Tricks, CocoaConf Las Vegas
Stupid Video Tricks, CocoaConf Las VegasStupid Video Tricks, CocoaConf Las Vegas
Stupid Video Tricks, CocoaConf Las VegasChris Adamson
 
Advanced AV Foundation (CocoaConf, Aug '11)
Advanced AV Foundation (CocoaConf, Aug '11)Advanced AV Foundation (CocoaConf, Aug '11)
Advanced AV Foundation (CocoaConf, Aug '11)Chris Adamson
 
Stupid Video Tricks, CocoaConf Seattle 2014
Stupid Video Tricks, CocoaConf Seattle 2014Stupid Video Tricks, CocoaConf Seattle 2014
Stupid Video Tricks, CocoaConf Seattle 2014Chris Adamson
 
Objective Evaluation of Video Quality
Objective Evaluation of Video QualityObjective Evaluation of Video Quality
Objective Evaluation of Video QualityAnton Venema
 
iOSDC 2018 動画をなめらかに動かす技術
iOSDC 2018 動画をなめらかに動かす技術iOSDC 2018 動画をなめらかに動かす技術
iOSDC 2018 動画をなめらかに動かす技術Yuji Hato
 
dat-Post-Producer-final
dat-Post-Producer-finaldat-Post-Producer-final
dat-Post-Producer-finalScott Matics
 
“Building Accelerated GStreamer Applications for Video and Audio AI,” a Prese...
“Building Accelerated GStreamer Applications for Video and Audio AI,” a Prese...“Building Accelerated GStreamer Applications for Video and Audio AI,” a Prese...
“Building Accelerated GStreamer Applications for Video and Audio AI,” a Prese...Edge AI and Vision Alliance
 
WebRTC Standards & Implementation Q&A - All about browser interoperability
WebRTC Standards & Implementation Q&A - All about browser interoperabilityWebRTC Standards & Implementation Q&A - All about browser interoperability
WebRTC Standards & Implementation Q&A - All about browser interoperabilityAmir Zmora
 
Web Standards for AR workshop at ISMAR13
Web Standards for AR workshop at ISMAR13Web Standards for AR workshop at ISMAR13
Web Standards for AR workshop at ISMAR13Rob Manson
 
Screenflow Podcampaz
Screenflow PodcampazScreenflow Podcampaz
Screenflow PodcampazTerry Lee
 
InduSoft VBScript Webinar
 InduSoft VBScript Webinar InduSoft VBScript Webinar
InduSoft VBScript WebinarAVEVA
 
Optimising video delivery - Brightcove PLAY 2019
Optimising video delivery - Brightcove PLAY 2019Optimising video delivery - Brightcove PLAY 2019
Optimising video delivery - Brightcove PLAY 2019Jeremy Brown
 
HTML5 Multimedia Accessibility
HTML5 Multimedia AccessibilityHTML5 Multimedia Accessibility
HTML5 Multimedia Accessibilitybrucelawson
 
[AWS Media Symposium 2019] AWS Media Services Innovation - Christer Whitehorn...
[AWS Media Symposium 2019] AWS Media Services Innovation - Christer Whitehorn...[AWS Media Symposium 2019] AWS Media Services Innovation - Christer Whitehorn...
[AWS Media Symposium 2019] AWS Media Services Innovation - Christer Whitehorn...Amazon Web Services Korea
 
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.jsIñaki Baz Castillo
 
End to-end testing from rookie to pro
End to-end testing  from rookie to proEnd to-end testing  from rookie to pro
End to-end testing from rookie to proDomenico Gemoli
 
VoLTE Testing Solution in NFV ecosystem
VoLTE Testing Solution in NFV ecosystemVoLTE Testing Solution in NFV ecosystem
VoLTE Testing Solution in NFV ecosystemDebayan Chaudhuri
 

Similar to Composing and Editing Media with AV Foundation (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
 
Stupid Video Tricks, CocoaConf Las Vegas
Stupid Video Tricks, CocoaConf Las VegasStupid Video Tricks, CocoaConf Las Vegas
Stupid Video Tricks, CocoaConf Las Vegas
 
Advanced AV Foundation (CocoaConf, Aug '11)
Advanced AV Foundation (CocoaConf, Aug '11)Advanced AV Foundation (CocoaConf, Aug '11)
Advanced AV Foundation (CocoaConf, Aug '11)
 
Stupid Video Tricks, CocoaConf Seattle 2014
Stupid Video Tricks, CocoaConf Seattle 2014Stupid Video Tricks, CocoaConf Seattle 2014
Stupid Video Tricks, CocoaConf Seattle 2014
 
Objective Evaluation of Video Quality
Objective Evaluation of Video QualityObjective Evaluation of Video Quality
Objective Evaluation of Video Quality
 
iOSDC 2018 動画をなめらかに動かす技術
iOSDC 2018 動画をなめらかに動かす技術iOSDC 2018 動画をなめらかに動かす技術
iOSDC 2018 動画をなめらかに動かす技術
 
dat-Post-Producer-final
dat-Post-Producer-finaldat-Post-Producer-final
dat-Post-Producer-final
 
FFmpeg
FFmpegFFmpeg
FFmpeg
 
“Building Accelerated GStreamer Applications for Video and Audio AI,” a Prese...
“Building Accelerated GStreamer Applications for Video and Audio AI,” a Prese...“Building Accelerated GStreamer Applications for Video and Audio AI,” a Prese...
“Building Accelerated GStreamer Applications for Video and Audio AI,” a Prese...
 
WebRTC Standards & Implementation Q&A - All about browser interoperability
WebRTC Standards & Implementation Q&A - All about browser interoperabilityWebRTC Standards & Implementation Q&A - All about browser interoperability
WebRTC Standards & Implementation Q&A - All about browser interoperability
 
Web Standards for AR workshop at ISMAR13
Web Standards for AR workshop at ISMAR13Web Standards for AR workshop at ISMAR13
Web Standards for AR workshop at ISMAR13
 
Screenflow Podcampaz
Screenflow PodcampazScreenflow Podcampaz
Screenflow Podcampaz
 
InduSoft VBScript Webinar
 InduSoft VBScript Webinar InduSoft VBScript Webinar
InduSoft VBScript Webinar
 
Optimising video delivery - Brightcove PLAY 2019
Optimising video delivery - Brightcove PLAY 2019Optimising video delivery - Brightcove PLAY 2019
Optimising video delivery - Brightcove PLAY 2019
 
HTML5 Multimedia Accessibility
HTML5 Multimedia AccessibilityHTML5 Multimedia Accessibility
HTML5 Multimedia Accessibility
 
[AWS Media Symposium 2019] AWS Media Services Innovation - Christer Whitehorn...
[AWS Media Symposium 2019] AWS Media Services Innovation - Christer Whitehorn...[AWS Media Symposium 2019] AWS Media Services Innovation - Christer Whitehorn...
[AWS Media Symposium 2019] AWS Media Services Innovation - Christer Whitehorn...
 
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
 
8
88
8
 
End to-end testing from rookie to pro
End to-end testing  from rookie to proEnd to-end testing  from rookie to pro
End to-end testing from rookie to pro
 
VoLTE Testing Solution in NFV ecosystem
VoLTE Testing Solution in NFV ecosystemVoLTE Testing Solution in NFV ecosystem
VoLTE Testing Solution in NFV ecosystem
 

Composing and Editing Media with AV Foundation

  • 1. Composing & Editing Media with AV Foundation http://bobmccune.com
  • 2. About... Bob McCune ‣ MN Developer and Instructor ‣ Owner of TapHarmonic, LLC. ‣ Founded Minnesota CocoaHeads in 2008
  • 3. Agenda What will I learn? ‣ AV Foundation Overview ‣ Media Playback ‣ Media Editing ‣ Composing Media ‣ Mixing Audio ‣ Building Video Transitions ‣ Layering Visual Content
  • 4. AV Foundation Overview ‣ Apple’s advanced Objective-C framework for working with timed-media ‣ High performance, asynchronous processing ‣ Hardware accelerated handling of AV media ‣ Available in its current form since iOS 4 ‣ Significant additions and enhancements iOS 5 and 6 ‣ Default media framework on Mac OS X since 10.7 Lion ‣ Apple’s focus for media apps on both iOS and Mac
  • 5. Where does it fit? iOS Media Options Simple Awesome Complex MediaPlayer CoreAudio UIKit CoreMedia AVFoundation CoreVideo CoreAnimation
  • 7. Media Assets Understanding Assets ‣ AVAsset is an abstract representation of media resource modeling the static aspects of the media. ‣ Abstracts away the type and location ‣ AVAssetTrack models the static aspects of the individual media streams within an asset ‣ Tracks are of a uniform type (video, audio, etc.) AVAssetTrack (Video) AVAssetTrack (Audio)
  • 8. Using AVAssets What can I do with an asset? ‣ Inspect ‣ Generate Images ‣ Transcode and Export ‣ Playback
  • 10. AVPlayer Playback Controller ‣ AVPlayer is a controller for managing playback ‣ play ‣ pause ‣ rate ‣ seekToTime: ‣ Use KVO to observe playback readiness and state ‣ status ‣ Timed Observations ‣ addPeriodicTimeObserverForInterval:queue:usingBlock ‣ addBoundaryTimeObserverForInterval:queue:usingBlock
  • 11. Playing Media Static vs Dynamic Models ‣ AV Foundation distinguishes between static and dynamic aspects of media AVAsset AVAsset AVAsset AVAssetTrack St ati c AVPlayerItemTrack AVPlayerItem AVPlayerItemTrack AVPlayerItemTrack D y n amic
  • 12. Understanding Time Core Media Essentials CMTime ‣ Rational number representing time ‣ 64-bit integer time value (numerator) ‣ 32-bit integer time scale (denominator) CMTime fiveSeconds = CMTimeMake(5, 1); CMTime oneSample = CMTimeMake(1, 44100); CMTime zeroTime = kCMTimeZero; ‣ Large number of utility functions in Core Media: ‣ CMTimeAdd,CMTimeSubtract,CMTimeCompare, etc.
  • 13. Understanding Time Core Media Essentials CMTimeRange ‣ Core Media struct containing start time and duration CMTimeRange assetRange = CMTimeRangeMake(kCMTimeZero, asset.duration); CMTimeRange zeroRange = kCMTimeRangeZero; ‣ Like CMTime, there are many Core Media functions: ‣ CMTimeRangeEqual, CMTimeRangeContainsTime, CMTimeRangeGetEnd, CMTIMERANGE_ISVALID, etc.
  • 14. Video Playback AVPlayerLayer AVAsset AVPlayerItem AVPlayer AVAsset AVAsset AVPlayerItemTrack AVPlayerItemTrack AVAssetTrack AVPlayerItemTrack
  • 15. Video Playback AVPlayerLayer AVPlayerItem AVPlayer AVPlayerLayer AVPlayerItemTrack AVPlayerItemTrack AVPlayerItemTrack
  • 16. Demo
  • 18. Composing Assets AVComposition ‣ Concrete extension of AVAsset ‣ Composes asset segments on a timeline
  • 19. Composing Assets Tracks and Segments AVMutableComposition *composition = [AVMutableComposition composition]; AVComposition
  • 20. Composing Assets Tracks and Segments CMPersistentTrackID trackID = kCMPersistentTrackID_Invalid; AVMutableCompositionTrack *videoTrack = [composition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:trackID]; AVMutableCompositionTrack *audioTrack = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:trackID]; AVComposition AVCompositionTrack (Video) AVCompositionTrack (Audio)
  • 21. Composing Assets Tracks and Segments AVAssetTrack *srcVideoTrack1 = // source video track 1 [videoTrack insertTimeRange:timeRange ofTrack:srcVideoTrack1 atTime:startTime error:&error]; AVAssetTrack *srcVideoTrack2 = // source video track 2 [videoTrack insertTimeRange:timeRange ofTrack:srcVideoTrack2 atTime:startTime error:&error]; AVAssetTrack *srcAudioTrack = // source audio track [audioTrack insertTimeRange:timeRange ofTrack:srcAudioTrack atTime:startTime error:&error]; AVComposition AVCompositionTrack (Video) AVCompositionTrackSegment AVCompositionTrackSegment Seconds 10-30 of “redpanda.m4v” Seconds 20-60 of “waves.m4v” AVCompositionTrack (Audio) AVCompositionTrackSegment Seconds 0-60 of “soundtrack.mp3”
  • 22. Demo
  • 24. Audio Mixing AVAudioMix ‣ Composition tracks play at their natural volume ‣ AVAudioMix applies track-level volume adjustments ‣ Composed of AVAudioMixInputParameters ‣ Parameters control individual track volume over time CMTime CMTimeRange
  • 25. AVAudioMix Example CMTime fadeTime = CMTimeMake(5, 1); CMTime fadeInStartTime = kCMTimeZero; CMTime fadeOutStartTime = CMTimeSubtract(asset.duration, fadeTime); CMTimeRange fadeInRange = CMTimeRangeMake(fadeInStartTime, fadeTime); CMTimeRange fadeOutRange = CMTimeRangeMake(fadeOutStartTime, fadeTime); AVMutableAudioMixInputParameters *parameters = [AVMutableAudioMixInputParameters audioMixInputParameters]; parameters.trackID = assetTrack.trackID; [parameters setVolumeRampFromStartVolume:0.0 toEndVolume:1.0 timeRange:fadeInRange]; [parameters setVolumeRampFromStartVolume:1.0 toEndVolume:0.0 timeRange:fadeOutRange]; AVMutableAudioMix *audioMix = [AVMutableAudioMix audioMix]; audioMix.inputParameters = @[parameters]; playerItem.audioMix = audioMix;
  • 26. Demo
  • 28. Video Transitions AVVideoComposition AVVideoComposition Defines how two or more video tracks are composited together AVVideoCompositionInstruction Configured through collection of AVVideoCompositionInstruction AVVideoCompositionInstruction composition instructions describing compositing behavior
  • 29. Video Transitions AVVideoCompositionInstruction AVVideoComposition AVVideoCompositionInstruction AVVideoCompositionInstruction AVVideoCompositionInstruction Defines the time range of compositing behavior Composed of layer instructions AVAsset AVAsset AVVideoCompositionLayerInstruction describing compositing behavior
  • 30. Video Transitions AVVideoCompositionLayerInstruction AVVideoComposition AVVideoCompositionInstruction AVVideoCompositionInstruction AVVideoCompositionInstruction AVAsset AVAsset Defines the transform and AVVideoCompositionLayerInstruction opacity ramps of input layers Transform and opacity changes modified over given time range
  • 32. Building Transitions 1 Stagger Layout A B
  • 33. Building Transitions 2 Define Overlapping Regions A B
  • 34. Building Transitions 3 Define Time Ranges A Passthrough Passthrough Passthrough B Transition Transition * Time ranges must not have gaps or overlap * Total duration must not be shorter than composition
  • 35. Building Transitions 4 Configure Instructions // Build transition instructions AVMutableVideoCompositionInstruction *transitionInstruction = ...; transitionInstruction.timeRange = transitionTimeRange; AVMutableVideoCompositionLayerInstruction *fromLayerInstruction = ...; AVMutableVideoCompositionLayerInstruction *toLayerInstruction = ...; // Cross Disolve [fromLayerInstruction setOpacityRampFromStartOpacity:1.0 toEndOpacity:0.0 timeRange:transitionTimeRange]; NSArray *instructions = @[fromLayerInstruction, toLayerInstruction]; transitionInstruction.layerInstructions = instructions; [instructions addObject:transitionInstruction];
  • 36. Building Transitions 5 Set sizes and apply #define FRAME_RATE CMTimeMake(1, 30) #define RENDER_SIZE CGSizeMake(1280, 720) AVMutableVideoComposition *videoComposition = [AVMutableVideoComposition videoComposition]; // Set instructions on AVVideoComposition instance videoComposition.instructions = instructions; videoComposition.frameDuration = FRAME_RATE; videoComposition.renderSize = RENDER_SIZE; AVPlayerItem *playerItem = [AVPlayerItem playerItemWithAsset:[composition copy]]; playerItem.videoComposition = videoComposition;
  • 37. New in iOS 6 AVVideoComposition videoCompositionWithPropertiesOfAsset: Automagic Setup: • Calculates all required passthrough and transition time ranges • Builds appropriate composition and layer instructions for time ranges • Sets the appropriate render size • Sets the appropriate frame rate
  • 38. Demo
  • 40. Layering Content Core Animation Core Animation a natural choice ‣ High performance, inherently time-based ‣ CALayer subclasses used for all video rendering CALayer: used to layer images and text CAAnimation: used to animate layered content CABasicAnimation CAKeyframeAnimation
  • 41. Animation Timing AVSynchronizedLayer ‣ Core Animation operates on host time ‣ Starts at boot, marches towards infinity ‣ Timeline animations need to use movie time ‣ Starts at kCMTimeZero and runs to duration ‣ Can be started, stopped, rewound, etc. ‣ Use AVSynchronizedLayer to use movie time ‣ Confers player item timing on to its sublayer tree AVPlayerItem AVSynchronizedLayer CATextLayer CABasicAnimation
  • 42. Core Animation Timeline vs Realtime Animations ‣ Exactly the same, but different: ‣ Animations with zero beginTime won’t be seen ‣ Set beginTime = AVCoreAnimationBeginTimeZero ‣ Animations removed by default ‣ Set removedOnCompletion = NO ‣ Unable to use CAAnimationGroup?
  • 43. Core Animation Natural Choice, Awkward Implementation ‣ Different conceptual models for timeline editing ‣ CMTime and CMTimeRange for asset items ‣ Seconds and milliseconds for layers ‣ Build abstraction to help bridge the gap ‣ Usage differs in playback and export scenarios ‣ AVSynchronizedLayer for playback ‣ Attach to player’s view hierarchy/layer tree ‣ AVVideoCompositionCoreAnimationTool for export
  • 44. Demo
  • 45. Summary AV Foundation Rocks! ‣ Powerful tools for audio and video playback ‣ AVPlayer, AVPlayerItem, AVPlayerLayer ‣ Powerful tools for composing/editing media: ‣ AVComposition, AVAudioMix, AVVideoComposition, AVSynchronizedLayer ‣ Powerful utility classes: ‣ AVAssetImageGenerator ‣ AVExportSession ‣ Steep learning curve, but worth the investment!
  • 46. Resources Presentation Materials http://www.speakerdeck.com/bobmccune/ http://www.slideshare.net/bobmccune/ https://github.com/tapharmonic/AVFoundationEditor Learning AV Foundation http://www.speakerdeck.com/bobmccune/ https://github.com/tapharmonic/AVFoundationDemos WWDC 2011: Exploring AV Foundation https://developer.apple.com/videos/wwdc/2011/?id=405 WWDC 2011: Working with Media in AV Foundation https://developer.apple.com/videos/wwdc/2011/?id=415 BobMcCune.com @bobmccune