0

I am trying to start recording a video at an exact timestamp.

I have managed to get the timestamp of each frame by using the methods found: here and here.

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection{ 
    CMTime time = CMSampleBufferGetPresentationTimeStamp(sampleBuffer);
    ...
    // check if time > timestampToStart, use these frames

}

By doing this I can use only frames that come after the timestamp I specify.

The issue is that the first frame used won't be exactly at timstampToStart but timstampToStart plus a small interval that can be between 0-1/fps (fps = 24 usually).

How can I make sure that the first frame used is exactly (or very close) to the timestamp that I want

Community
  • 1
  • 1
Nilsymbol
  • 515
  • 1
  • 9
  • 25

1 Answers1

0

When you need time-critical functions, use NSThread:

- (IBAction)startCapture:(id) sender
 {
    NSDate * startTime = [now dateByAddingTimeInterval: 10.12345];

    NSThread * thread = [[NSThread alloc] initWithTarget:self selector:@selector(capture:) object:startTime];
    [thread start];
}

- (void)capture:(id) context
{
    NSDate * startTime = (NSDate *) context;
    [NSThread sleepUntilDate:startTime];

    // Do your things...
}

The thread will wake up within a few nanoseconds of the set time unless you CPU is incredibly busy. However, it takes some time to create a thread so don't set the start time so closely. The thread creation time is about ~90 microseconds on OS X. Apple doesn't say how long on iOS.

Code Different
  • 90,614
  • 16
  • 144
  • 163
  • Thanks for your answer. However, in my case the "do your things" is what takes time and starting it this way wont make the first frame of my recorded video be exactly on the timestamp that I want – Nilsymbol Aug 27 '16 at 00:25
  • Then do it before the `sleepUntilDate` call – Code Different Aug 27 '16 at 02:27
  • the buffer stream comes from the avcapturesession and is not "pausable" in this way unfortunately – Nilsymbol Aug 27 '16 at 13:51