title: Playing a small section of video forward, then backward, in a loop using AVPlayer
body: <p>In my app, I have an <code>AVPlayer</code> that is used to play, scrub, etc. a video file. I'm trying to implement the following functionality, but haven't come up with a good solution yet...</p>
  
  <p>Suppose the video file is 3000 frames long and the playhead is on frame 1000. When the user presses the "play around" button, I want the video to play a 10 frame section of the video centered around frame 1000, i.e., frames 995-1005. When the player reaches either frame 995 or 1005, I want the playback to reverse direction. In other words, the frame order would go:</p>
  
  <p>1000-1001-1002-1003-1004-1005-1004-1003-1002-1001-1000-999-998-997-996-995-996-997-998-999-1000</p>
  
  <p>and repeat indefinitely.</p>
  
  <p>I first attempted to use <code>-addBoundaryTimeObserverForTimes:queue:usingBlock:</code> to define the start and end points of the video section and switch the sign of the player rate in the block. This worked <em>sometimes</em>, but when the video section was small eventually one of the boundaries would get "missed" and the video would simply continuing playing in that direction until it reached the beginning or end of the file. </p>
  
  <p>I tried to mitigate this by adding another time observer with <code>–addPeriodicTimeObserverForInterval:queue:usingBlock:</code> which would check to see if a boundary had gotten missed and reset the looped playback if so. Again, this worked <em>sometimes</em> but would fail if the start or end of the playback region also happened to be the first or last frame of the video file (respectively).</p>
  
  <p>I <em>then</em> attempted to set up a callback for <code>AVPlayerItemDidPlayToEndTimeNotification</code> to again reset the playback if it hit the boundary of the video file. Once again, this worked <em>SOMETIMES</em> but would eventually stop the playback or cause the playback to play indefinitely in the direction away from the end of the file.</p>
  
  <p>I'm at a loss here of what to do. I could possibly create an <code>AVMutableComposition</code> to simulate the effect, but there's a lot of other objects dependent on the exact time of the video player that it would require a major overhaul of the app to have to implement a whole separate handling system for simulating the appropriate video player time from the composition (which I'm not super willing to do at this point). Any ideas?</p>