Giter Site home page Giter Site logo

piemonte / pbjvision Goto Github PK

View Code? Open in Web Editor NEW
1.9K 77.0 325.0 2.16 MB

📸 iOS Media Capture – features touch-to-record video, slow motion, and photography

License: MIT License

Objective-C 99.25% Ruby 0.40% GLSL 0.34%
video photography camera ios capture media objective-c avfoundation vine snapchat

pbjvision's Introduction

PBJVision

PBJVision

PBJVision is a camera library for iOS that enables easy integration of special capture features and camera interface customizations in your iOS app. Next Level is the Swift counterpart.

Build Status Pod Version GitHub license

Features

  • touch-to-record video capture
  • slow motion capture (120 fps on supported hardware)
  • photo capture
  • customizable user interface and gestural interactions
  • ghosting (onion skinning) of last recorded segment
  • flash/torch support
  • white balance, focus, and exposure adjustment support
  • mirroring support

Capture is also possible without having to use the touch-to-record gesture interaction as the sample project provides.

About

This library was originally created at DIY as a fun means for kids to author video and share their skills. The touch-to-record interaction was pioneered by Vine and Instagram.

Thanks to everyone who has contributed and helped make this a fun project and community.

Quick Start

PBJVision is available and recommended for installation using the dependency manager CocoaPods.

To integrate, just add the following line to your Podfile:

pod 'PBJVision'

Usage

Import the header.

#import "PBJVision.h"

Setup the camera preview using [[PBJVision sharedInstance] previewLayer].

    // preview and AV layer
    _previewView = [[UIView alloc] initWithFrame:CGRectZero];
    _previewView.backgroundColor = [UIColor blackColor];
    CGRect previewFrame = CGRectMake(0, 60.0f, CGRectGetWidth(self.view.frame), CGRectGetWidth(self.view.frame));
    _previewView.frame = previewFrame;
    _previewLayer = [[PBJVision sharedInstance] previewLayer];
    _previewLayer.frame = _previewView.bounds;
    _previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    [_previewView.layer addSublayer:_previewLayer];

If your view controller is managed by a Storyboard, keep the previewLayer updated for device sizes

- (void)viewDidLayoutSubviews
{
    _previewLayer.frame = _previewView.bounds;
}

Setup and configure the PBJVision controller, then start the camera preview.

- (void)_setup
{
    _longPressGestureRecognizer.enabled = YES;

    PBJVision *vision = [PBJVision sharedInstance];
    vision.delegate = self;
    vision.cameraMode = PBJCameraModeVideo;
    vision.cameraOrientation = PBJCameraOrientationPortrait;
    vision.focusMode = PBJFocusModeContinuousAutoFocus;
    vision.outputFormat = PBJOutputFormatSquare;

    [vision startPreview];
}

Start/pause/resume recording.

- (void)_handleLongPressGestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
{
    switch (gestureRecognizer.state) {
      case UIGestureRecognizerStateBegan:
        {
            if (!_recording)
                [[PBJVision sharedInstance] startVideoCapture];
            else
                [[PBJVision sharedInstance] resumeVideoCapture];
            break;
        }
      case UIGestureRecognizerStateEnded:
      case UIGestureRecognizerStateCancelled:
      case UIGestureRecognizerStateFailed:
        {
            [[PBJVision sharedInstance] pauseVideoCapture];
            break;
        }
      default:
        break;
    }
}

End recording.

    [[PBJVision sharedInstance] endVideoCapture];

Handle the final video output or error accordingly.

- (void)vision:(PBJVision *)vision capturedVideo:(NSDictionary *)videoDict error:(NSError *)error
{   
    if (error && [error.domain isEqual:PBJVisionErrorDomain] && error.code == PBJVisionErrorCancelled) {
        NSLog(@"recording session cancelled");
        return;
    } else if (error) {
        NSLog(@"encounted an error in video capture (%@)", error);
        return;
    }

    _currentVideo = videoDict;
    
    NSString *videoPath = [_currentVideo  objectForKey:PBJVisionVideoPathKey];
    [_assetLibrary writeVideoAtPathToSavedPhotosAlbum:[NSURL URLWithString:videoPath] completionBlock:^(NSURL *assetURL, NSError *error1) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle: @"Video Saved!" message: @"Saved to the camera roll."
                                                       delegate:self
                                              cancelButtonTitle:nil
                                              otherButtonTitles:@"OK", nil];
        [alert show];
    }];
}

To specify an automatic end capture maximum duration, set the following property on the 'PBJVision' controller.

    [[PBJVision sharedInstance] setMaximumCaptureDuration:CMTimeMakeWithSeconds(5, 600)]; // ~ 5 seconds

To adjust the video quality and compression bit rate, modify the following properties on the PBJVision controller.

    @property (nonatomic, copy) NSString *captureSessionPreset;

    @property (nonatomic) CGFloat videoBitRate;
    @property (nonatomic) NSInteger audioBitRate;
    @property (nonatomic) NSDictionary *additionalCompressionProperties;

Community

Contributions and discussions are welcome!

Project

Related Projects

Resources

License

PBJVision is available under the MIT license, see the LICENSE file for more information.

pbjvision's People

Contributors

adampro13 avatar amarcadet avatar autresphere avatar bcherry avatar cacheflowe avatar camobap avatar despinoza avatar ethanjdiamond avatar felix8888 avatar finbarr avatar jeffaburt avatar jhk115 avatar lexmiln avatar maxrandom avatar mhdemiroz avatar n-studio avatar nolegirl avatar paultaykalo avatar petec avatar piemonte avatar readmecritic avatar riosc avatar rromanchuk avatar wilg avatar wvteijlingen avatar yunarta avatar yury avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pbjvision's Issues

Memory warning upon taking photo

Is there anyway to adjust the size/quality of the raw image to decrease memory usage upon capture?

p.s. the max resolution i require is 640x640, could you point me in the right direction on how to cater to this size with optimal memory usage?

edit: I also make adjustments to the image immediately after capture

Much thanks!

asset writer is in an unknown state, wasn't recording

The above error gets called in endCaptureVideo if the audio session is manually set to ambient (i do this to replay the video immediately after capture via: [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryAmbient error:nil] )

Delay/lag when starting a recording in landscape mode

First of all thanks a lot for PBJVision. It has really helped me speed up the development of my app.

When my app opens, it starts in Portrait mode. Turning the iPhone sideways sets it to Landscape mode.
The problem I have is that when it's turned to Landscape, starting a recording makes the app 'freeze' for a short moment. After the freeze it starts recording like normal.
When I open the app and just start recording in Portrait mode I don't experience the freeze.

The only thing that is changed before the freeze happens is this:

    [vision setCameraOrientation:cameraOrientation];
    [vision setOutputFormat:PBJOutputFormatWidescreen];
    [vision setFocusMode:PBJFocusModeContinuousAutoFocus];

Chaning the OutputFormat to PBJOutputFormatWidescreen causes the freeze when a new recording is started. If I remove that line it records without the freeze.

Is this a known problem? Or might I be doing something wrong?

Recorded video path file upload only .mov format not .mp4 format

Mr.Piemonte,

This is Ramanathan.

In Your SDK, the recorded path file only upload in .mov format. But doesn't upload in .mp4 format.

In Your SDK, I changed only store the recorded video in NSDocumentDirectory on PBJVision.m file using the below line,

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

NSDateFormatter *dateFormat = [[[NSDateFormatter alloc] init] autorelease];
[dateFormat setDateFormat:@"dd-MM-yyyy HH:mm:SS"];
NSDate *now = [[[NSDate alloc] init] autorelease];
NSString *theDate = [dateFormat stringFromDate:now];

NSString *outputPath= [[[NSString alloc] initWithString:[NSString stringWithFormat:@"%@/%@.mov",documentsDirectory,theDate]] autorelease];
_outputURL = [NSURL fileURLWithPath:outputPath];

It's uploading the .mov file format but why doesn't upload .mp4 format.

Here below I pasted the url path and output from web service. That is,

Nov 21 01:49:46 Lion-Users-iPod SedioiOS[1177] : after triming = /var/mobile/Applications/2C14E79B-4910-446D-A794-16434E28098C/Documents/21-11-2013 01:49:35.mov

��Nov 21 01:49:46 Lion-Users-iPod SedioiOS[1177] : after triming = /var/mobile/Applications/2C14E79B-4910-446D-A794-16434E28098C/Documents/21-11-2013 01:49:35.mov

Nov 21 01:49:46 Lion-Users-iPod SedioiOS[1177] : The urlvalue is = file://localhost/var/mobile/Applications/2C14E79B-4910-446D-A794-16434E28098C/Documents/21-11-2013%2001:49:35.mov

Nov 21 01:49:46 Lion-Users-iPod SedioiOS[1177] : String name:: Content-Disposition: form-data; name="uploadedfile"; filename="video-2013-11-21-01:49:46AM.mp4"

��Nov 21 01:49:59 Lion-Users-iPod SedioiOS[1177] : erro is = {
PBJVisionVideoPathKey = "/var/mobile/Applications/2C14E79B-4910-446D-A794-16434E28098C/Documents/21-11-2013 01:49:35.mov";
}
Nov 21 01:49:59 Lion-Users-iPod SedioiOS[1177] : return data
Nov 21 01:49:59 Lion-Users-iPod SedioiOS[1177] : response from server is=

Kindly Please give guidance where I was wrong.

Thank you,

Second Issue

Please check below code

  • (void)vision:(PBJVision *)vision capturedVideo:(NSDictionary *)videoDict error:(NSError *)error
    {
    NSString *videoPath = [_currentVideo objectForKey:PBJVisionVideoPathKey];
    // [_assetLibrary writeVideoAtPathToSavedPhotosAlbum:[NSURL //URLWithString:videoPath] completionBlock:^(NSURL *assetURL, NSError *error1) {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle: @"Saved!" message: //@"Saved to the camera roll."
    // delegate:self
    // cancelButtonTitle:nil
    // otherButtonTitles:@"OK", nil];
    // [alert show];
    // }];
    NSURL *movieURL = [NSURL URLWithString:videoPath];
    MPMoviePlayerViewController *movieController = [[MPMoviePlayerViewController alloc] initWithContentURL:movieURL];
    [self presentMoviePlayerViewControllerAnimated:movieController];
    [movieController.moviePlayer play];

}
this doesnot work properlly
What i am going to say is that when we save the movie to camera role , we can check video play well,
but i think that when you write movie , it seems that you didnt write properly .
like the timeoffset.

Please check that and advise me , i want to use your great project but currently i cannot use
Please help me
:)

Thank you
Sincerely
Buadren

Support custom video dimensions

For an app I am building I need this.

Currently only these are supported:

typedef NS_ENUM(NSInteger, PBJOutputFormat) {
    PBJOutputFormatPreset = 0,
    PBJOutputFormatSquare,
    PBJOutputFormatWidescreen
};

I also wonder if its already possible by using the Preset setting and setting the dimensions elsewhere.

I will fork and implement otherwise.

setFlashMode: not working

setFlashMode: doesn't set variable _flashMode after checking if new value is different from previous one and if _currentDevice hasFlash.

Add flag not to create thumbnail in capturePhoto

Add a flag that allows to disable thumbnail creation when capturing photo, sparing some processing time when the functionality is not needed (in iPhone4S it took consistently ~200ms to generate image thumbnails)

Recorded Video Path File doesn't upload on server

Mr.Piemonte,

This is Ramanathan.

Thanks for give the custom video record project like vine. Really it's useful for me but it was very difficult to understand and touch to me. Because I'm new for developing apps for iPhone.

Now I have one doubts from your project that is, I get the recorded video path from

  • (void)vision:(PBJVision *)vision capturedVideo:(NSDictionary *)videoDict error:(NSError *)error

    then I try to upload that video path follow the method(-(void)upload) of below instruction link

http://stackoverflow.com/questions/15518925/how-to-save-video-in-documents-folder-then-upload-to-server

Here I have only get the below response from server like below

Nov 13 05:55:41 Lion-Users-iPod Vision[17484] : return data <0909>

Nov 13 05:55:41 Lion-Users-iPod Vision[17484] : response from server is=

So I try to upload another method that is, I create another project and drag drop inside the local video like video1.mp4 to that project.

And set that video as [[NSBundle mainBundle] pathForResource:@"video1" ofType:@".mp4"];

And change NSUrl and convert NSdata. Here It was working that video upload onto the server following the above stackoverflow link method(uploadvideo).

But I can't understand and Identify why the recorded video doesn't upload and get empty response from server using your video path.

I request you to Kindly give some guidance.
Thanks..

visionDidStartVideoCapture appears to be called twice

Once here:

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection

and another here:

- (void)startVideoCapture

Why is it called twice? Is there another method I should be using?

BUG or Issue?

Hello again,
One more time I would like to thank you for your excellent Tool and for your help answering to my questions.
I want to inform you for a strange situation using your tool in an app that i am developing.
When I use it first for taking a photo and after for taking video......no video taken.
If I use it for taking FIRST video and after photo...everything works fine!!!!
All these happens either in IOS 6 or IOS 7.
Why? Can you take a look in that strange situation?

Thank you very much for your help.

George N. Gerardis

small question

Is there a way to check if the video was shot in landscape?

feedback

hello! How to add focus function? When why iOS5.0.1 debugging isVideoStabilizationSupported and finishWritingWithCompletionHandler errors? Does not support the ios 5?

Support for iPhone 4 and 4s

Hi Patrick,

Amazing work!

By the way, please can you help assist how I can get this working for iPhone 4 and 4s as well?

Thanks much.

Regards,

Manan

isRecording always returns NO

    __block BOOL isRecording = NO;
    [self _enqueueBlockInCaptureVideoQueue:^{
        isRecording = (BOOL)_flags.recording;
    }];
    return isRecording;

This is due to the fact that _enqueueBlockInCaptureVideoQueue is async and therefore isRecording will always be NO.

when switching modes/camera set flash accordingly

When switching camera/mode, the current flash mode should be set if device supports it.

Example: If I start in video mode with back camera and set flash on, then switch to front camera (which doesn't support flash), then switch again to back camera, flash is off when it should be on, and the internal _flashMode camera is still PBJFlashModeOn.

Take Photo

Hello again,

I would like to ask if you can tell me (write) how can i take photo....and write in a file.
I know how to set up the camera....but which methods do i call to shoot a photo.

Thanks a lot...

George N. Gerardis

To record the progress

Hi! Would you please tell me how to get to record the progress? For example: use UIProgressView display (0.0 ~ 1.0) corresponding (1 seconds to 15 seconds), because I want to be one of the biggest record limit function

Add video maximum duration capability

Add setter for video maximum duration, that ends capture automatically when video reaches that duration.
Currently I'm checking for video duration in - (void)visionDidCaptureVideoSample:(PBJVision *)vision delegate method and ending capture if - (Float64)capturedVideoSeconds has reached the maximum desired duration, but that allows for some extra video time.

Photo capturing memory issue

Using your excellent tools in an app for capturing photo each time using the tool the memory increases rapidly and when dismissing the conroller in which I use your tool memory does not been released. The result is that after some times ( 4-5 ) the app crashes because of memory leak.
Can you see this issue?

Thanks a lot for your help

George N. Gerardis

elapsed time

how can i access elapsed recording time? i con't find any accessible property in PBJVision interface....

_focusMode is never used

It seems _focusMode is never user (only has getter and setter), even in - (void)focusAtAdjustedPoint:(CGPoint)adjustedPoint the focus mode set is AVCaptureFocusModeAutoFocus after setting focus POI instead of setting previous focus mode.

I'm not used to git forking and making pull requests, so I'll leave sample code here:

-(void)setFocusMode:(PBJFocusMode)focusMode {
    BOOL shouldChangeFocusMode = (_focusMode != focusMode);
    if (![_currentDevice isFocusModeSupported:(AVCaptureFocusMode)focusMode] || !shouldChangeFocusMode)
        return;

    _focusMode = focusMode;

    NSError *error = nil;
    if (_currentDevice && [_currentDevice lockForConfiguration:&error]) {
        [_currentDevice setFocusMode:(AVCaptureFocusMode)focusMode];
        [_currentDevice unlockForConfiguration];

    } else if (error) {
        DLog(@"error locking device for focus mode change (%@)", error);
    }
}

in - (void)focusAtAdjustedPoint:(CGPoint)adjustedPoint:

if (isFocusAtPointSupported && [_currentDevice isFocusModeSupported:AVCaptureFocusModeAutoFocus]) {
            //is it really necessary to reset focus mode???
            AVCaptureFocusMode fm = [_currentDevice focusMode];
            [_currentDevice setFocusPointOfInterest:adjustedPoint];
            [_currentDevice setFocusMode:fm];
}

Also the focus mode should be set when changing device.

`visionDidStartVideoCapture:` is called twice

Once on line 1283 by - (void)startVideoCapture and once on line 1817 by - (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection

Add PBJVisionSessionPreset (compression and resolution settings)

Should we add a sessionPreset property to manage video/photo quality?

NSString *const AVCaptureSessionPresetPhoto;
NSString *const AVCaptureSessionPresetHigh;
NSString *const AVCaptureSessionPresetMedium;
NSString *const AVCaptureSessionPresetLow;
NSString *const AVCaptureSessionPreset352x288;
NSString *const AVCaptureSessionPreset640x480;
NSString *const AVCaptureSessionPreset1280x720;
NSString *const AVCaptureSessionPreset1920x1080;
NSString *const AVCaptureSessionPresetiFrame960x540;
NSString *const AVCaptureSessionPresetiFrame1280x720;

cannnot compile

PBJStrobeView.m:89:6: Receiver type 'CALayer' for instance message is a forward declaration

Complete Example Project

Hello,
You have made an exellent work with PBJVISION.
You help all of us a lot!
But, I would like to kindly ask from you, If it is possible to have a more complete example project using all your features, e.g. Set flash on/off, set camera front/rear,
grab video/photo etc.
You will help all of us that happens to be start beginners with objective c and IOS!
Thank you in advance.

George N. Gerardis

Higher Resolution Output

If I have a preview view at 320x320, is there a way I can get it to record at double the resolution? Vine and Instagram seem to generate videos at 600x600 and I'd like to have that kind of resolution for viewing on the web. Can't seem to find that anywhere.

Thanks! Love the library.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.