PCSBaseViewController.m 104 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637
  1. //
  2. // PCSBaseViewController.m
  3. // PanoramicCameraSDK
  4. //
  5. // Created by 王昭威 on 2023/1/14.
  6. //
  7. #import "PCSBaseViewController.h"
  8. #import <AVFoundation/AVFoundation.h>
  9. #import "Masonry.h"
  10. #import "CameraManager.h"
  11. #import "AVCapturePhotoOutput+VersionAdaptor.h"
  12. #import "PCSRoundButton.h"
  13. #import "PCSModeList.h"
  14. #import "UIImage+ext.h"
  15. #import "PCSTools.h"
  16. #import "OperationNodeProtocol.h"
  17. #import "OperationNodeSingle.h"
  18. #import "OperationNodeMultiple.h"
  19. #import "OperationNodePanorama.h"
  20. #import "QuitMultipleModeAlertViewController.h"
  21. #import <CoreMotion/CoreMotion.h>
  22. #import "OperationNodeMovie.h"
  23. #import "SDKParameters.h"
  24. #import "PhotoListViewController.h"
  25. #import "CustomModalViewTransition.h"
  26. #import "MovieListViewController.h"
  27. #import "TimerLabel.h"
  28. #import "MoviePlayerViewController.h"
  29. #import "PanoramaOrientationView.h"
  30. #import "PanoramaGuideView.h"
  31. #import "Renderer.h"
  32. #import "CameraTextureRenderPass.h"
  33. #import "LenzSDKConstant.h"
  34. #import "TensorFlowWrapper.h"
  35. #import "DBManager.h"
  36. #import <Photos/Photos.h>
  37. #import "BaseViewTapGestureDelegate.h"
  38. #import "MovieListCellModel.h"
  39. #import "PreviewSingleViewController.h"
  40. #import "OperationNodeAIPanorama.h"
  41. #import "PhotoAlbumListViewController.h"
  42. #import "PhotoAlbumModel.h"
  43. //#import "LenStitcher.h"
  44. #import <LenzStitchSDK/LenzStitchSDK.h>
  45. #import "LenzDataManager.h"
  46. #import "LenzHeader.h"
  47. #import "LenzCachedResourceModel.h"
  48. #import "LenzDataManager.h"
  49. #import "PCSPreviewViewController.h"
  50. #import "SVProgressHUD.h"
  51. #import <LenzTensorFlowSDK/LenzTensorFlow.h>
  52. #define MODE_LIST_INDEX_2_MODE_ENUM(x) ((x))
  53. // PCS means panoramic camera sdk
  54. @interface PCSBaseViewController ()<AVCapturePhotoCaptureDelegate,
  55. AVCaptureFileOutputRecordingDelegate,
  56. AVCaptureAudioDataOutputSampleBufferDelegate,
  57. UIViewControllerTransitioningDelegate,
  58. AVCaptureVideoDataOutputSampleBufferDelegate,
  59. PhotoListViewControllerDelegate,
  60. PanoramaOrientationViewDelegate>
  61. @property (nonatomic, assign) CGFloat accX;
  62. @property (nonatomic, nullable, readonly) AVCaptureDevice* currentCamera;
  63. @property (nonatomic, nullable, readonly) AVCaptureDeviceInput* currentCameraInput;
  64. @property (nonatomic, strong) AVCaptureSession* captureSession;
  65. @property (nonatomic, strong) AVCaptureVideoDataOutput* videoDataOutput;
  66. @property (nonatomic, strong) AVCaptureMovieFileOutput* movieFileOutput;
  67. @property (nonatomic, strong) AVCapturePhotoOutput* photoOutput;
  68. @property (nonatomic, strong) AVCapturePhotoSettings* outputSettings;
  69. @property (nonatomic, copy) dispatch_queue_t videoDataQueue;
  70. @property (nonatomic, strong) AVAssetWriter* videoWriter;
  71. @property (nonatomic, strong) AVAssetWriterInput* videoWriterInput;
  72. @property (nonatomic, assign) BOOL cameraPrepared;
  73. @property (nonatomic, assign) BOOL flag;
  74. @property (nonatomic, assign) BOOL hasCache;
  75. @property (nonatomic, strong) UIView* focusView;
  76. @property (nonatomic, strong, nullable) NSTimer* recordTimer;
  77. @property (nonatomic) dispatch_source_t touchSourceTimer;
  78. @property (nonatomic) CGFloat touchTime;
  79. @property (nonatomic, strong, nullable) NSTimer* motionTimer;
  80. @property (nonatomic, strong) BaseViewTapGestureDelegate* tapDelegate;
  81. /**
  82. key: PhotographModeEnum
  83. value: subclass of OperationNodeProtocol
  84. */
  85. @property (nonatomic, strong) NSDictionary<NSNumber*, id<OperationNodeProtocol>>* operationNodes;
  86. @property (nonatomic, strong) NSArray<id<OperationNodeProtocol>>* operationNodesArray;
  87. @property (nonatomic) dispatch_semaphore_t videoStitchSemaphore;
  88. //@property (nonatomic) NSMutableDictionary <NSString * , NSMutableArray *> *resultDict;
  89. //@property (nonatomic) UIImageView *testImageView;
  90. @property (nonatomic) LenzCachedResourceModel *resourceModel;
  91. //@property (nonatomic) dispatch_source_t stitchTimer;
  92. @property (nonatomic) UIView *stitchView;
  93. @property (nonatomic) UIImageView *stitchImageView;
  94. @property (nonatomic) UILabel *stitchLabel;
  95. @property (nonatomic) CABasicAnimation *loadingAnimation;
  96. @property (nonatomic) BOOL isStitchBigImage;
  97. @property (nonatomic) CGFloat brightnessValue;
  98. @property (nonatomic) CMMotionManager *motionManager;
  99. @property (nonatomic) BOOL isTakePhoto;
  100. @property (nonatomic) NSLock *stitchkLock;
  101. @property (nonatomic) LenVideoStitchResult stitchResult;
  102. @property (nonatomic) NSNumber *startPitchX;
  103. @property (nonatomic) NSNumber *startRollY;
  104. @property (nonatomic) LenzTensorFlow *tensorFlow;
  105. @end
  106. @implementation PCSBaseViewController
  107. #pragma mark - Life Circle
  108. - (void)dealloc{
  109. [self stopAllSensors];
  110. [[NSNotificationCenter defaultCenter] removeObserver:self];
  111. // dispatch_semaphore_signal(self.semaphore);
  112. [[LenzDBManager shared] close];
  113. }
  114. - (void)viewDidLayoutSubviews{
  115. [super viewDidLayoutSubviews];
  116. // [self updatePreViewLayer];
  117. // self.previewLayer.frame = self.view.layer.bounds;
  118. }
  119. - (void)awakeFromNib{
  120. [super awakeFromNib];
  121. [self setup];
  122. }
  123. - (void)viewDidLoad {
  124. [super viewDidLoad];
  125. // Do any additional setup after loading the view.
  126. // [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
  127. [SVProgressHUD setDefaultStyle:SVProgressHUDStyleLight];
  128. [SVProgressHUD setMinimumDismissTimeInterval:1.5];
  129. [SVProgressHUD setMaximumDismissTimeInterval:3];
  130. [SVProgressHUD setFont:[UIFont systemFontOfSize:14]];
  131. self.tensorFlow = [[LenzTensorFlow alloc]initWithFileName:@"moire_mobilenetv2_79"];
  132. self.stitchkLock = [[NSLock alloc]init];
  133. self.totalArray = [[NSMutableArray alloc]init];
  134. self.cachesArray = [[NSMutableArray alloc]init];
  135. self.typeArray = [[NSMutableArray alloc]init];
  136. self.resourceModel = [[LenzCachedResourceModel alloc]init];
  137. self.motionManager = [[CMMotionManager alloc]init];
  138. self.motionManager.deviceMotionUpdateInterval = 1/5;
  139. // self.resultDict = [NSMutableDictionary dictionary];
  140. if (!JK_IS_IPHONE_X) {
  141. self.safeBottom.constant = 25;
  142. self.safeTop.constant = 15;
  143. }else{
  144. self.safeBottom.constant = 0;
  145. }
  146. [self.timerLabel updateWith:100];
  147. self.albumButton.layer.cornerRadius = 6;
  148. self.albumButton.clipsToBounds = YES;
  149. switch ([SDKParameters shared].flashMode) {
  150. case SDK_FLASH_MODE_AUTO:{
  151. self.outputSettings.flashMode = AVCaptureFlashModeAuto;
  152. [self.flashButton setImage:[UIImage sdkImageNamed:@"flash-auto-btn"] forState:UIControlStateNormal];
  153. break;
  154. }
  155. case SDK_FLASH_MODE_ON:{
  156. self.outputSettings.flashMode = AVCaptureFlashModeOn;
  157. [self.flashButton setImage:[UIImage sdkImageNamed:@"flash-btn"] forState:UIControlStateNormal];
  158. break;
  159. }
  160. case SDK_FLASH_MODE_OFF:{
  161. self.outputSettings.flashMode = AVCaptureFlashModeOff;
  162. [self.flashButton setImage:[UIImage sdkImageNamed:@"flash-disable-btn"] forState:UIControlStateNormal];
  163. break;
  164. }
  165. default:
  166. break;
  167. }
  168. [PCSMotionManager shared];
  169. __weak typeof(self) weakself = self;
  170. [self.modeList reloadWith:self.operationNodesArray];
  171. self.modeList.indexChangedHandler = ^BOOL(NSUInteger newIndex, NSUInteger oldIndex) {
  172. __strong typeof(weakself) strongSelf = weakself;
  173. if ([SDKParameters shared].retainedMode == SDK_DATA_RETAINED_CLEAR) {
  174. BOOL needAlert = NO;
  175. switch (self.mode) {
  176. case SDK_CAPTURE_MODE_CONTINUOUS:
  177. needAlert = self.resourceModel.continousArray.count;
  178. break;
  179. case SDK_CAPTURE_MODE_SINGLE:
  180. needAlert = self.resourceModel.singleArray.count;
  181. break;
  182. case SDK_CAPTURE_MODE_MOVIE:
  183. needAlert = self.resourceModel.movieArray.count;
  184. break;
  185. case SDK_CAPTURE_MODE_PANORAMA:
  186. needAlert = self.resourceModel.panoramArray.count;
  187. break;
  188. case SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA:
  189. needAlert = self.resourceModel.aiPanoramArray.count;
  190. break;
  191. default:
  192. break;
  193. }
  194. if (needAlert) {
  195. [QuitMultipleModeAlertViewController show:self title:@"确认提醒" text:@"切换模式会清除已拍摄数据,请确认" leftBtnTitle:@"取消" rightBtnTitle:@"确定" withLeftButtonCallBack:^(QuitMultipleModeAlertViewController * _Nonnull alertController) {
  196. [alertController dismissViewControllerAnimated:NO completion:^{}];
  197. } rightButtonCallBack:^(QuitMultipleModeAlertViewController * _Nonnull alertController) {
  198. switch (self.mode) {
  199. case SDK_CAPTURE_MODE_CONTINUOUS: {
  200. [self.resourceModel.continousArray removeAllObjects];
  201. [self updateViewStatus];
  202. }
  203. break;
  204. case SDK_CAPTURE_MODE_SINGLE: {
  205. [self.resourceModel.singleArray removeAllObjects];
  206. [self updateViewStatus];
  207. }
  208. break;
  209. case SDK_CAPTURE_MODE_MOVIE:
  210. {
  211. [self.resourceModel.movieArray removeAllObjects];
  212. [self updateViewStatus];
  213. }
  214. break;
  215. case SDK_CAPTURE_MODE_PANORAMA:
  216. {
  217. [self.resourceModel.panoramArray removeAllObjects];
  218. [self updateViewStatus];
  219. }
  220. break;
  221. case SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA:
  222. {
  223. [self.resourceModel.aiPanoramArray removeAllObjects];
  224. [self updateViewStatus];
  225. }
  226. break;
  227. default:
  228. break;
  229. }
  230. self.modeList.index = newIndex;
  231. [self.modeList updateItemsConstraints];
  232. [strongSelf modeWillChange:newIndex oldIndex:oldIndex];
  233. id<OperationNodeProtocol> oldModelNode = strongSelf.currentOperationNode;
  234. PhotographModeEnum mode = (PhotographModeEnum)MODE_LIST_INDEX_2_MODE_ENUM(newIndex);
  235. strongSelf.mode = mode;
  236. self.ai_fullView.hidden = !(mode == SDK_CAPTURE_MODE_PANORAMA);
  237. [strongSelf modeDidChange:newIndex oldIndex:oldIndex];
  238. if([oldModelNode respondsToSelector:@selector(didQuit)]){
  239. [oldModelNode didQuit];
  240. }
  241. [alertController dismissViewControllerAnimated:NO completion:^{}];
  242. }];
  243. return NO;
  244. }
  245. // return YES;
  246. }
  247. if ([SDKParameters shared].retainedMode == SDK_DATA_RETAINED_RETAIN) {
  248. //保留模式无单拍
  249. if (newIndex > 0) {
  250. newIndex += 1;
  251. }
  252. if (oldIndex > 0) {
  253. oldIndex += 1;
  254. }
  255. }
  256. [strongSelf modeWillChange:newIndex oldIndex:oldIndex];
  257. id<OperationNodeProtocol> oldModelNode = strongSelf.currentOperationNode;
  258. PhotographModeEnum mode = (PhotographModeEnum)MODE_LIST_INDEX_2_MODE_ENUM(newIndex);
  259. strongSelf.mode = mode;
  260. self.ai_fullView.hidden = !(mode == SDK_CAPTURE_MODE_PANORAMA);
  261. [strongSelf modeDidChange:newIndex oldIndex:oldIndex];
  262. if([oldModelNode respondsToSelector:@selector(didQuit)]){
  263. [oldModelNode didQuit];
  264. }
  265. return YES;
  266. };
  267. [self modeWillChange:[SDKParameters shared].modeIndex oldIndex:0lu];
  268. self.modeList.mode = [SDKParameters shared].modeIndex;
  269. self.mode = [SDKParameters shared].modeIndex;
  270. // dispatch_async(dispatch_get_main_queue(), ^{
  271. [self modeDidChange:[SDKParameters shared].modeIndex oldIndex:0lu];
  272. // });
  273. UIVisualEffectView* effectView = [[UIVisualEffectView alloc] initWithEffect: [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark]];
  274. effectView.alpha = 0.8;
  275. effectView.effect = nil;
  276. self.effectView = effectView;
  277. [self.view insertSubview:self.effectView belowSubview:self.backButton];
  278. [self.effectView mas_makeConstraints:^(MASConstraintMaker *make) {
  279. make.edges.equalTo(self.view);
  280. }];
  281. if(!self.cameraPrepared){
  282. [self prepareCamera];
  283. }
  284. self.panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGestureHandler:)];
  285. [self.view addGestureRecognizer:self.panGesture];
  286. // self.tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureHandler:)];
  287. // self.tapGesture.delegate = self.tapDelegate;
  288. // [self.view addGestureRecognizer:self.tapGesture];
  289. UIImageView* loadingImageView = [[UIImageView alloc] initWithImage:[UIImage sdkImageNamed:@"loading"]];
  290. self.loadingIndicator = loadingImageView;
  291. self.loadingIndicator.hidden = YES;
  292. [self.view addSubview:self.loadingIndicator];
  293. [loadingImageView mas_remakeConstraints:^(MASConstraintMaker *make) {
  294. make.center.equalTo(self.view);
  295. }];
  296. self.savePhotoButton.titleLabel.textColor = [UIColor whiteColor];
  297. self.discardPhotoButton.titleLabel.textColor = [UIColor whiteColor];
  298. // [self.takePhotoButton mas_remakeConstraints:^(MASConstraintMaker *make) {
  299. // make.centerX.equalTo(self.view);
  300. // make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom);
  301. // }];
  302. [self updateUIByMode];
  303. self.panoramOrientationGuideView.delegate = self;
  304. [self.view addSubview:self.panoramaGuideView];
  305. [self panoramaOrientationViewslt:(PanoramaOrientationViewLeft)];
  306. self.panoramaGuideView.hidden = YES;
  307. self.ablumImageView = [[UIImageView alloc]init];
  308. [self.view addSubview:self.ablumImageView];
  309. self.ablumImageView.layer.cornerRadius = 6;
  310. self.ablumImageView.layer.masksToBounds = YES;
  311. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(showPreview:)];
  312. [self.ablumImageView addGestureRecognizer:tap];
  313. self.ablumImageView.userInteractionEnabled = YES;
  314. self.ablumImageView.hidden = YES;
  315. // self.ablumImageView.backgroundColor = [UIColor redColor];
  316. self.ablumImageView.contentMode = UIViewContentModeScaleAspectFill;
  317. [self.ablumImageView mas_makeConstraints:^(MASConstraintMaker *make) {
  318. make.centerY.mas_equalTo(self.takePhotoButton);
  319. make.left.mas_equalTo(20);
  320. make.width.height.mas_equalTo(60);
  321. // make.top.left.mas_equalTo(50);
  322. // make.width.height.mas_equalTo(300);
  323. }];
  324. UILongPressGestureRecognizer *ges = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPressGes:)];
  325. // ges.numberOfTapsRequired = 1;
  326. ges.minimumPressDuration = 1;
  327. [self.takePhotoButton addGestureRecognizer:ges];
  328. self.timerLabel.layer.cornerRadius = 6;
  329. self.timerLabel.layer.masksToBounds = YES;
  330. [self.ai_fullView addTarget:self action:@selector(alFullViewAction:) forControlEvents:UIControlEventTouchUpInside];
  331. [self.view addSubview:self.stitchView];
  332. [self.stitchView mas_makeConstraints:^(MASConstraintMaker *make) {
  333. make.centerY.mas_equalTo(self.view);
  334. make.centerX.mas_equalTo(self.view);
  335. make.width.mas_offset(200);
  336. make.height.mas_offset(200);
  337. }];
  338. }
  339. - (void)viewWillAppear:(BOOL)animated{
  340. [super viewWillAppear:animated];
  341. self.panGesture.enabled = YES;
  342. if([self.currentOperationNode respondsToSelector:@selector(updateUI)])
  343. [self.currentOperationNode updateUI];
  344. }
  345. - (void)viewDidAppear:(BOOL)animated{
  346. [super viewDidAppear:animated];
  347. if(self.cameraPrepared){
  348. switch ([AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo]) {
  349. case AVAuthorizationStatusAuthorized:
  350. [self startCaptureSession];
  351. [[PCSMotionManager shared] startAccelerometerUpdates];
  352. break;
  353. case AVAuthorizationStatusNotDetermined:{
  354. [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
  355. if(granted){
  356. [self startCaptureSession];
  357. [[PCSMotionManager shared] startAccelerometerUpdates];
  358. }
  359. else{
  360. [[NSNotificationCenter defaultCenter] postNotificationName:CameraNotificationNotPermission object:self];
  361. }
  362. }];
  363. break;
  364. }
  365. case AVAuthorizationStatusDenied:{
  366. [[NSNotificationCenter defaultCenter] postNotificationName:CameraNotificationNotPermission object:self];
  367. break;
  368. }
  369. case AVAuthorizationStatusRestricted:
  370. break;
  371. default:
  372. break;
  373. }
  374. switch ([AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio]) {
  375. case AVAuthorizationStatusAuthorized:
  376. [self setupMicrophone];
  377. break;
  378. case AVAuthorizationStatusNotDetermined:{
  379. [AVCaptureDevice requestAccessForMediaType:AVMediaTypeAudio completionHandler:^(BOOL granted) {
  380. if(granted){
  381. [self setupMicrophone];
  382. }
  383. else{
  384. [[NSNotificationCenter defaultCenter] postNotificationName:MicrophoneNotificationNotPermission object:self];
  385. }
  386. }];
  387. break;
  388. }
  389. case AVAuthorizationStatusDenied:{
  390. [[NSNotificationCenter defaultCenter] postNotificationName:MicrophoneNotificationNotPermission object:self];
  391. break;
  392. }
  393. case AVAuthorizationStatusRestricted:
  394. break;
  395. default:
  396. break;
  397. }
  398. }
  399. }
  400. - (void)viewWillDisappear:(BOOL)animated{
  401. [super viewWillDisappear:animated];
  402. [self stopCaptureSession];
  403. [[PCSMotionManager shared] stopAccelerometerUpdates];
  404. }
  405. - (UIView *)stitchView {
  406. if (!_stitchView) {
  407. _stitchView = [[UIView alloc]init];
  408. [_stitchView addSubview:self.stitchImageView];
  409. [self.stitchImageView mas_makeConstraints:^(MASConstraintMaker *make) {
  410. make.centerX.mas_equalTo(_stitchView);
  411. make.top.mas_equalTo(0);
  412. make.width.height.mas_equalTo(68);
  413. }];
  414. [_stitchView addSubview:self.stitchLabel];
  415. [self.stitchLabel mas_makeConstraints:^(MASConstraintMaker *make) {
  416. make.top.mas_equalTo(self.stitchImageView.mas_bottom).mas_offset(20);
  417. make.centerX.mas_equalTo(self.stitchImageView);
  418. }];
  419. _stitchView.hidden = YES;
  420. }
  421. return _stitchView;
  422. }
  423. - (UIImageView *)stitchImageView {
  424. if (!_stitchImageView) {
  425. _stitchImageView = [[UIImageView alloc]init];
  426. _stitchImageView.image = [UIImage loadNamed:@"loading"];
  427. }
  428. return _stitchImageView;
  429. }
  430. - (CABasicAnimation *)loadingAnimation {
  431. if (!_loadingAnimation) {
  432. _loadingAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
  433. _loadingAnimation.fromValue = [NSNumber numberWithFloat:0.f];
  434. _loadingAnimation.toValue = [NSNumber numberWithFloat: M_PI *2];
  435. _loadingAnimation.duration = 3;
  436. _loadingAnimation.autoreverses = NO;
  437. _loadingAnimation.fillMode = kCAFillModeForwards;
  438. _loadingAnimation.repeatCount = MAXFLOAT;
  439. }
  440. return _loadingAnimation;
  441. }
  442. - (UILabel *)stitchLabel {
  443. if (!_stitchLabel) {
  444. _stitchLabel = [[UILabel alloc]init];
  445. _stitchLabel.text = @"正在拼接中,请稍等";
  446. _stitchLabel.font = [UIFont systemFontOfSize:12];
  447. _stitchLabel.textColor = [UIColor whiteColor];
  448. }
  449. return _stitchLabel;
  450. }
  451. #pragma mark - Private Method
  452. //+ (instancetype)makeViewController{
  453. // UIStoryboard* sb = [UIStoryboard storyboardWithName:[PCSTools shared].mainStoryboardName bundle:[PCSTools sdkBundle]];
  454. // return ;
  455. //}
  456. - (void)alFullViewAction:(UIButton *)button {
  457. // self.currentOperationNode.needHiddenDir = !self.currentOperationNode.needHiddenDir;
  458. if (self.mode == SDK_CAPTURE_MODE_PANORAMA) {
  459. OperationNodePanorama *pan = nil;
  460. if ([self.currentOperationNode isKindOfClass:[OperationNodePanorama class]]) {
  461. pan = self.currentOperationNode;
  462. pan.needHiddenDir = !pan.needHiddenDir;
  463. }
  464. self.panoramOrientationGuideView.hidden = pan.needHiddenDir;
  465. } else if (self.mode == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA) {
  466. OperationNodeAIPanorama *aiPan = nil;
  467. if ([self.currentOperationNode isKindOfClass:[OperationNodeAIPanorama class]]) {
  468. aiPan = self.currentOperationNode;
  469. aiPan.needHiddenDir = !aiPan.needHiddenDir;
  470. }
  471. self.panoramOrientationGuideView.hidden = aiPan.needHiddenDir;
  472. }
  473. }
  474. - (void)showPreview:(UITapGestureRecognizer *)tap {
  475. if (self.ablumImageView.hidden) {
  476. return;
  477. }
  478. if(self.mode != SDK_CAPTURE_MODE_SINGLE) {
  479. PCSPreviewViewController *vc = [[PCSPreviewViewController alloc]init];
  480. vc.model = self.resourceModel;
  481. vc.dataChangeBlock = ^{
  482. [self updateViewStatus];
  483. };
  484. [self presentViewController:vc animated:YES completion:nil];
  485. } else {
  486. PreviewSingleViewController* dst = [[PreviewSingleViewController alloc]init];
  487. dst.singleModeNode = self.currentOperationNode;
  488. if (self.resourceModel.singleArray.count > 0) {
  489. LenzResourceItemModel *model = self.resourceModel.singleArray.firstObject;
  490. dst.image = model.image;
  491. }
  492. [self presentViewController:dst animated:YES completion:nil];
  493. }
  494. }
  495. + (instancetype)initWithParams:(NSDictionary *)params complete:(PCSBaseVCCompleteBLock)complete {
  496. [self parser:params];
  497. UIStoryboard* sb = [UIStoryboard storyboardWithName:[PCSTools shared].mainStoryboardName bundle:[PCSTools sdkBundle]];
  498. PCSBaseViewController *vc = (PCSBaseViewController *)[sb instantiateViewControllerWithIdentifier:@"sample"];
  499. vc.completeBlock = complete;
  500. return vc;
  501. }
  502. #pragma mark - Config param
  503. + (void)parser: (NSDictionary*)params{
  504. SDKParameters* sdkParams = [SDKParameters shared];
  505. NSString* retainedMode = params[@"dataRetainedMode"];
  506. if(retainedMode != nil){
  507. if([retainedMode isEqual:@"retain"]){
  508. sdkParams.retainedMode = SDK_DATA_RETAINED_RETAIN;
  509. }
  510. else if([retainedMode isEqual:@"clear"]){
  511. sdkParams.retainedMode = SDK_DATA_RETAINED_CLEAR;
  512. }
  513. // if([retainedMode isEqual:@"userConfirm"]){
  514. // sdkParams.retainedMode = SDK_DATA_RETAINED_USER_CONFIRM;
  515. // }
  516. }
  517. NSArray* arr = params[@"cameraMode"];
  518. if(arr != nil){
  519. NSDictionary<NSString*, NSNumber*>* table = @{
  520. @"continuous": @(SDK_CAPTURE_MODE_CONTINUOUS),
  521. @"single" : @(SDK_CAPTURE_MODE_SINGLE),
  522. @"video" : @(SDK_CAPTURE_MODE_MOVIE),
  523. @"panorama" : @(SDK_CAPTURE_MODE_PANORAMA),
  524. @"panoramaPlus" : @(SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA)
  525. };
  526. NSMutableArray<NSNumber*>* modeIndiciesTable = [NSMutableArray arrayWithArray:@[
  527. @(SDK_CAPTURE_MODE_CONTINUOUS),
  528. @(SDK_CAPTURE_MODE_SINGLE),
  529. @(SDK_CAPTURE_MODE_MOVIE),
  530. @(SDK_CAPTURE_MODE_PANORAMA),
  531. @(SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA),
  532. ]];
  533. NSMutableDictionary<NSNumber*, NSNumber*>* modes = [NSMutableDictionary dictionary];
  534. [arr enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  535. if(table[obj] != nil){
  536. modes[table[obj]] = @(YES);
  537. }
  538. }];
  539. [modeIndiciesTable enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(NSNumber * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  540. if(modes[obj] == nil){
  541. [modeIndiciesTable removeObject:obj];
  542. }
  543. }];
  544. sdkParams.modeIndices = [modeIndiciesTable copy];
  545. if(table[arr.firstObject] != nil){
  546. sdkParams.modeIndex = (SDKCaptureModeIndex)[table[arr.firstObject] unsignedIntegerValue];
  547. }
  548. else{
  549. sdkParams.modeIndex = (SDKCaptureModeIndex)[sdkParams.modeIndices.firstObject unsignedIntegerValue];
  550. }
  551. }
  552. NSString* cameraPosition = params[@"type"];
  553. if(cameraPosition != nil){
  554. if([cameraPosition isEqual:@"back"]){
  555. sdkParams.cameraPosition = SDK_CAMERA_PISITION_BACK;
  556. sdkParams.cameraPositionString = cameraPosition;
  557. }
  558. else if([cameraPosition isEqual:@"front"]){
  559. sdkParams.cameraPosition = SDK_CAMERA_PISITION_FRONT;
  560. sdkParams.cameraPositionString = cameraPosition;
  561. }
  562. }
  563. NSNumber* recTime = params[@"recTime"];
  564. if(recTime != nil){
  565. sdkParams.limitRecordTime = [recTime integerValue];
  566. }
  567. sdkParams.keyFrame = params[@"keyframe"];
  568. NSString* flashMode = params[@"flashMode"];
  569. if(flashMode != nil){
  570. sdkParams.flashModeString = flashMode;
  571. if([flashMode isEqualToString:@"auto"]){
  572. sdkParams.flashMode = SDK_FLASH_MODE_AUTO;
  573. }
  574. else if([flashMode isEqualToString:@"on"]){
  575. sdkParams.flashMode = SDK_FLASH_MODE_ON;
  576. }
  577. else if([flashMode isEqualToString:@"off"]){
  578. sdkParams.flashMode = SDK_FLASH_MODE_OFF;
  579. }
  580. }
  581. NSNumber* videoQualityNum = params[@"videoQuality"];
  582. if(videoQualityNum != nil){
  583. NSInteger videoQuality = [videoQualityNum integerValue];
  584. if(videoQuality == 480){
  585. sdkParams.videoQuality = SDK_VIDEO_QUALITY_480;
  586. }
  587. else if(videoQuality == 720){
  588. sdkParams.videoQuality = SDK_VIDEO_QUALITY_720;
  589. }
  590. else if(videoQuality == 1080){
  591. sdkParams.videoQuality = SDK_VIDEO_QUALITY_1080;
  592. }
  593. else if(videoQuality == 2160){
  594. sdkParams.videoQuality = SDK_VIDEO_QUALITY_2160;
  595. }
  596. }
  597. NSNumber* showPreviewForPanorama = params[@"showPreview"];
  598. if(showPreviewForPanorama != nil){
  599. sdkParams.showPreviewForPanorama = [showPreviewForPanorama boolValue];
  600. }
  601. }
  602. // 拍照界面
  603. - (void)showPreviewView: (BOOL)show{
  604. self.previewLayer.hidden = !show;
  605. self.takePhotoButton.enabled = show;
  606. self.resultImageView.hidden = show;
  607. self.backButton.hidden = !show;
  608. self.flashButton.hidden = !show;
  609. self.switchButton.hidden = !show;
  610. self.discardPhotoButton.hidden = show;
  611. self.savePhotoButton.hidden = show;
  612. }
  613. - (void)setup{
  614. // 打开数据库
  615. [[LenzDBManager shared] openSqlDataBase];
  616. [LenzDataManager creatDirectory];
  617. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  618. [[PCSTools shared] cleanDiskCache];
  619. });
  620. _mode = SDK_CAPTURE_MODE_CONTINUOUS;
  621. _captureSession = [[AVCaptureSession alloc] init];
  622. _captureSession.sessionPreset = AVCaptureSessionPresetInputPriority;
  623. _movieFileOutput = [[AVCaptureMovieFileOutput alloc] init];
  624. _movieFileOutput.maxRecordedDuration = CMTimeMake(self.parameters.limitRecordTime, 1);
  625. // setup video data output for panoramic
  626. _videoDataQueue = dispatch_queue_create("video data", DISPATCH_QUEUE_SERIAL);
  627. _videoDataOutput = [[AVCaptureVideoDataOutput alloc] init];
  628. _videoDataOutput.alwaysDiscardsLateVideoFrames = YES;
  629. _videoDataOutput.videoSettings = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:kCVPixelFormatType_32BGRA]
  630. forKey:(id)kCVPixelBufferPixelFormatTypeKey];
  631. _photoOutput = [[AVCapturePhotoOutput alloc] init];
  632. NSDictionary *setDic = @{AVVideoCodecKey:AVVideoCodecTypeJPEG};
  633. _outputSettings = [AVCapturePhotoSettings photoSettingsWithFormat:setDic];
  634. [_photoOutput setPhotoSettingsForSceneMonitoring:_outputSettings];
  635. _previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.captureSession];
  636. NSMutableArray* nodesArr = [NSMutableArray array];
  637. NSMutableDictionary* nodesDic = [NSMutableDictionary dictionary];
  638. NSDictionary<NSNumber*, Class>* nodeClsTable = @{
  639. @(SDK_CAPTURE_MODE_CONTINUOUS): [OperationNodeMultiple class],
  640. @(SDK_CAPTURE_MODE_SINGLE): [OperationNodeSingle class],
  641. @(SDK_CAPTURE_MODE_MOVIE): [OperationNodeMovie class],
  642. @(SDK_CAPTURE_MODE_PANORAMA): [OperationNodePanorama class],
  643. @(SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA): [OperationNodeAIPanorama class],
  644. };
  645. [[SDKParameters shared].modeIndices enumerateObjectsUsingBlock:^(NSNumber * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  646. //
  647. // if(nodeClsTable[obj] != nil){
  648. // id node = [[nodeClsTable[obj] alloc] initWithController: self];
  649. // [nodesArr addObject: node];
  650. // nodesDic[obj] = node;
  651. // }
  652. if(nodeClsTable[obj] != nil){
  653. if ([SDKParameters shared].retainedMode == SDK_DATA_RETAINED_RETAIN && obj.intValue == SDK_CAPTURE_MODE_SINGLE) {
  654. return;
  655. } else {
  656. id node = [[nodeClsTable[obj] alloc] initWithController: self];
  657. if ([node isKindOfClass:[OperationNodeVideoBase class]]) {
  658. OperationNodeVideoBase *base = (OperationNodeVideoBase *)node;
  659. base.recTime = [SDKParameters shared].limitRecordTime;
  660. }
  661. [nodesArr addObject: node];
  662. nodesDic[obj] = node;
  663. }
  664. }
  665. }];
  666. _operationNodesArray = [nodesArr copy];
  667. _operationNodes = [nodesDic copy];
  668. // _operationNodes = @{
  669. // @(SDK_CAPTURE_MODE_SINGLE): [[OperationNodeSingle alloc] initWithController:self],
  670. // @(SDK_CAPTURE_MODE_CONTINUOUS): [[OperationNodeMultiple alloc] initWithController:self],
  671. // @(SDK_CAPTURE_MODE_MOVIE): [[OperationNodeMovie alloc] initWithController:self],
  672. // @(SDK_CAPTURE_MODE_PANORAMA): [[OperationNodePanorama alloc] initWithController:self],
  673. // @(SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA): [[OperationNodeAIPanorama alloc] initWithController:self],
  674. // };
  675. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(willEnterForeground:) name:UIApplicationWillEnterForegroundNotification object:nil];
  676. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(willEnterBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil];
  677. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationWillChange:) name:UIDeviceOrientationDidChangeNotification object:nil];
  678. }
  679. - (void)startMotion {
  680. if (self.motionManager.deviceMotionAvailable) {
  681. __weak typeof(self)wearSelf = self;
  682. [self.motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue mainQueue] withHandler:^(CMDeviceMotion * _Nullable motion, NSError * _Nullable error) {
  683. if (!self.startPitchX && !self.startRollY) {
  684. self.startPitchX = @(motion.attitude.pitch * 100);
  685. self.startRollY = @(motion.attitude.roll *100);
  686. }
  687. double x = self.startPitchX.doubleValue - motion.attitude.pitch * 100;
  688. double y = self.startRollY.doubleValue - motion.attitude.roll * 100;
  689. LenVideoStitchDirction dir = (LenVideoStitchDirction)wearSelf.panoramOrientationGuideView.selectedItemIndex;
  690. if (dir == LenVideoStitchDirctionLeft || dir == LenVideoStitchDirctionRight) {
  691. if (fabs(x) < 3) {
  692. // NSLog(@"~~~~~~~~~~水平");
  693. [wearSelf.panoramaGuideView updateArrowWith:PanoramaArrowDirCenter dir:dir];
  694. } else {
  695. if (x > 0) {
  696. // NSLog(@"~~~~~~~~~~向下");
  697. [wearSelf.panoramaGuideView updateArrowWith:PanoramaArrowDirDown dir:dir];
  698. } else {
  699. // NSLog(@"~~~~~~~~~~向上");
  700. [wearSelf.panoramaGuideView updateArrowWith:PanoramaArrowDirUp dir:dir];
  701. }
  702. }
  703. } else if (dir == LenVideoStitchDirctionUp || dir == LenVideoStitchDirctionDown) {
  704. if (fabs(y) < 3) {
  705. [wearSelf.panoramaGuideView updateArrowWith:PanoramaArrowDirCenter dir:dir];
  706. } else {
  707. if (y > 0) {
  708. [wearSelf.panoramaGuideView updateArrowWith:PanoramaArrowDirLeft dir:dir];
  709. } else {
  710. [wearSelf.panoramaGuideView updateArrowWith:PanoramaArrowDirRight dir:dir];
  711. }
  712. }
  713. }
  714. }];
  715. }
  716. }
  717. - (void)stopMotion {
  718. [self.motionManager stopDeviceMotionUpdates];
  719. self.startPitchX = nil;
  720. self.startRollY = nil;
  721. LenVideoStitchDirction dir = (LenVideoStitchDirction)self.panoramOrientationGuideView.selectedItemIndex;
  722. [self.panoramaGuideView updateArrowWith:PanoramaArrowDirCenter dir:dir];
  723. }
  724. #pragma mark - Lazy Load
  725. - (BaseViewTapGestureDelegate *)tapDelegate{
  726. if(_tapDelegate == nil){
  727. _tapDelegate = [[BaseViewTapGestureDelegate alloc] init];
  728. _tapDelegate.controller = self;
  729. }
  730. return _tapDelegate;
  731. }
  732. - (AVCaptureDevice *)currentCamera{
  733. __block AVCaptureDevice* camera = nil;
  734. [self.captureSession.inputs enumerateObjectsUsingBlock:^(__kindof AVCaptureInput * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  735. AVCaptureDeviceInput* inputDevice = obj;
  736. if([inputDevice.device hasMediaType:AVMediaTypeVideo]){
  737. camera = inputDevice.device;
  738. *stop = YES;
  739. }
  740. }];
  741. return self.currentCameraInput.device;
  742. }
  743. - (AVCaptureDeviceInput*)currentCameraInput{
  744. __block AVCaptureDeviceInput* cameraInput = nil;
  745. [self.captureSession.inputs enumerateObjectsUsingBlock:^(__kindof AVCaptureInput * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  746. AVCaptureDeviceInput* inputDevice = obj;
  747. if([inputDevice.device hasMediaType:AVMediaTypeVideo]){
  748. cameraInput = inputDevice;
  749. *stop = YES;
  750. }
  751. }];
  752. return cameraInput;
  753. }
  754. - (SDKParameters *)parameters{
  755. return [SDKParameters shared];
  756. }
  757. #pragma mark - Action
  758. - (void)focusOn: (CGPoint)point{
  759. CGPoint pt = [self.previewLayer captureDevicePointOfInterestForPoint:point];
  760. AVCaptureDevice* curr = self.currentCamera;
  761. [[CameraManager shared] focusOn:pt device:curr];
  762. [self showFocusViewAt:point];
  763. }
  764. - (void)showFocusViewAt: (CGPoint)point{
  765. [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(hideFocusView) object:nil];
  766. if(self.focusView == nil){
  767. UIImageView* imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 42, 42)];
  768. imgView.image = [UIImage sdkImageNamed:@"focus"];
  769. imgView.contentMode = UIViewContentModeScaleAspectFit;
  770. self.focusView = imgView;
  771. [self.view addSubview:self.focusView];
  772. }
  773. self.focusView.hidden = NO;
  774. CABasicAnimation* flash = [CABasicAnimation animationWithKeyPath:@"opacity"];
  775. flash.duration = 0.2;
  776. flash.fromValue = @(1);
  777. flash.toValue = @(0.1);
  778. flash.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
  779. flash.autoreverses = YES;
  780. flash.repeatCount = 3;
  781. [self.focusView.layer removeAnimationForKey:@"flash"];
  782. [self.focusView.layer addAnimation:flash forKey:@"flash"];
  783. self.focusView.frame = CGRectMake(point.x - 21, point.y - 21, 42, 42);
  784. [self performSelector:@selector(hideFocusView) withObject:nil afterDelay:3];
  785. }
  786. - (void)hideFocusView{
  787. [self.focusView.layer removeAnimationForKey:@"flash"];
  788. self.focusView.hidden = YES;
  789. }
  790. - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
  791. if(error != nil){
  792. return;
  793. }
  794. if(self.mode == SDK_CAPTURE_MODE_SINGLE){
  795. [self dismissViewControllerAnimated:YES completion:^{}];
  796. }
  797. else{
  798. [self startCaptureSession];
  799. [self showPreviewView:YES];
  800. }
  801. }
  802. - (AVCaptureVideoOrientation)videoOrientation{
  803. UIDeviceOrientation curr = UIDeviceOrientationUnknown;
  804. return [self videoOrientation:&curr];
  805. }
  806. - (AVCaptureVideoOrientation)videoOrientation:(UIDeviceOrientation*)currentDeviceOrientation{
  807. return [[PCSMotionManager shared] videoOrientation:currentDeviceOrientation];;
  808. }
  809. - (void)takeStillPhoto:(AVCaptureVideoPreviewLayer*)previewLayer {
  810. AVCaptureConnection *connection = [self.photoOutput connectionWithMediaType:AVMediaTypeVideo];
  811. if(connection == nil){
  812. [self showAlertForAuthorization];
  813. return;
  814. }
  815. if (connection.supportsVideoOrientation) {
  816. // 根据motion设置照片方向
  817. AVCaptureVideoOrientation videoOrientation = [self videoOrientation];
  818. connection.videoMirrored = self.currentCamera == [CameraManager shared].front;
  819. connection.videoOrientation = videoOrientation;
  820. }
  821. // 创建 AVCapturePhotoSettings
  822. AVCapturePhotoSettings *photoSettings = [AVCapturePhotoSettings photoSettings];
  823. if ([self.photoOutput.availablePhotoCodecTypes containsObject:AVVideoCodecTypeJPEG]) {
  824. NSDictionary *format = @{AVVideoCodecKey: AVVideoCodecTypeJPEG};
  825. photoSettings = [AVCapturePhotoSettings photoSettingsWithFormat:format];
  826. // NSLog(@"-----:%ld",(long)self.currentCameraInput.device.position);
  827. if (self.currentCameraInput.device.position == SDK_CAMERA_PISITION_BACK) {
  828. photoSettings.flashMode = self.outputSettings.flashMode;
  829. }
  830. photoSettings.previewPhotoFormat = @{
  831. (NSString*)kCVPixelBufferPixelFormatTypeKey : photoSettings.availablePreviewPhotoPixelFormatTypes.firstObject,
  832. (NSString*)kCVPixelBufferWidthKey: @(160),
  833. (NSString*)kCVPixelBufferHeightKey: @(160),
  834. };
  835. }
  836. photoSettings.autoStillImageStabilizationEnabled = YES;
  837. // 拍照
  838. [self.photoOutput capturePhotoWithSettings:photoSettings delegate:self];
  839. }
  840. #pragma mark - Notification
  841. - (void)orientationWillChange: (NSNotification*)noti{
  842. NSLog(@"orientationWillChange");
  843. }
  844. - (void)willEnterForeground: (NSNotification*)noti{
  845. // if(self.broken){
  846. // [self.player play];
  847. // self.broken = NO;
  848. // }
  849. }
  850. //UIBackgroundTaskIdentifier _bgTaskToken;
  851. - (void)willEnterBackground: (NSNotification*)noti{
  852. if([self.currentOperationNode conformsToProtocol:@protocol(OperationNodeBackgroundProtocol)]){
  853. id<OperationNodeBackgroundProtocol> obj = self.currentOperationNode;
  854. if ([obj respondsToSelector:@selector(willEnterBackground:)]) {
  855. [obj willEnterBackground:noti];
  856. }
  857. }
  858. }
  859. - (void)orientationDidChange: (NSNotification*)noti{
  860. NSLog(@"orientationDidChange");
  861. if([self.currentOperationNode respondsToSelector:@selector(stop)])
  862. [self.currentOperationNode stop];
  863. }
  864. #pragma mark - alert
  865. - (void)showAlertForAuthorizationWithText: (NSString*)text{
  866. [QuitMultipleModeAlertViewController show:self title:@"" text:text leftBtnTitle:@"取消" rightBtnTitle:@"确认" withLeftButtonCallBack:^(QuitMultipleModeAlertViewController * _Nonnull alertController) {
  867. [alertController dismissViewControllerAnimated:YES completion:^{
  868. // [self dismissViewControllerAnimated:YES completion:^{
  869. //
  870. // }];
  871. }];
  872. } rightButtonCallBack:^(QuitMultipleModeAlertViewController * _Nonnull alertController) {
  873. [alertController dismissViewControllerAnimated:YES completion:^{
  874. NSURL* url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
  875. if(url != nil){
  876. [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success) {
  877. // NSLog(succ)
  878. }];
  879. }
  880. }];
  881. }];
  882. }
  883. - (void)showAlertForAuthorization{
  884. [self showAlertForAuthorizationWithText:@"请在系统设置里打开摄像机访问权限后重试"];
  885. }
  886. #pragma mark - Capture
  887. - (void)takeStillPhoto{
  888. [self takeStillPhoto:self.previewLayer];
  889. }
  890. - (BOOL)startRecording{
  891. if(self.movieFileOutput.isRecording){
  892. return NO;
  893. }
  894. self.movieFileOutput.maxRecordedDuration = CMTimeMake([SDKParameters shared].limitRecordTime, 1);
  895. [self.recordTimer invalidate];
  896. dispatch_async(dispatch_get_main_queue(), ^{
  897. self.recordTimer = [NSTimer timerWithTimeInterval:0.2 repeats:YES block:^(NSTimer * _Nonnull timer) {
  898. [self.timerLabel updateWith:self.movieFileOutput.recordedDuration.value / self.movieFileOutput.recordedDuration.timescale];
  899. }];
  900. [[NSRunLoop currentRunLoop] addTimer:self.recordTimer forMode:NSDefaultRunLoopMode];
  901. });
  902. NSURL* tmpMovieFileUrl = [NSURL fileURLWithPath:[LenzDataManager moviePath]];
  903. AVCaptureConnection* connection = [self.movieFileOutput connectionWithMediaType:AVMediaTypeVideo];
  904. if(connection == nil){
  905. [self showAlertForAuthorization];
  906. return NO;
  907. }
  908. UIDeviceOrientation currOrientation = UIDeviceOrientationUnknown;
  909. connection.videoOrientation = [self videoOrientation:&currOrientation];
  910. AVCaptureDevice* camera = self.currentCamera;
  911. [camera lockForConfiguration:nil];
  912. if ([camera hasFlash] && self.currentCameraInput.device.position == SDK_CAMERA_PISITION_BACK) {
  913. if (self.outputSettings.flashMode == AVCaptureFlashModeOff) {
  914. [camera setTorchMode:AVCaptureTorchModeOff];
  915. } else if (self.outputSettings.flashMode == AVCaptureFlashModeOn) {
  916. [camera setTorchMode:AVCaptureTorchModeOn];
  917. } else {
  918. [camera setTorchMode:AVCaptureTorchModeAuto];
  919. }
  920. }
  921. [camera unlockForConfiguration];
  922. self.thumbnailOritaionByCurrentVideoOrientation = [UIImage imageOrientationByDeviceOrientation:currOrientation isFrontCamera:camera == [CameraManager shared].front];
  923. [self.movieFileOutput startRecordingToOutputFileURL: tmpMovieFileUrl recordingDelegate:self];
  924. return YES;
  925. }
  926. - (void)stopRecording{
  927. [self.movieFileOutput stopRecording];
  928. AVCaptureDevice* camera = self.currentCamera;
  929. [camera lockForConfiguration:nil];
  930. if ([camera hasFlash] && self.currentCameraInput.device.position == SDK_CAMERA_PISITION_BACK) {
  931. [camera setTorchMode:AVCaptureTorchModeOff];
  932. }
  933. [camera unlockForConfiguration];
  934. [self.recordTimer invalidate];
  935. self.recordTimer = nil;
  936. }
  937. - (BOOL)startVideoDataOutputing{
  938. [[NSNotificationCenter defaultCenter] removeObserver:self name:PCS_NotificationNameOrientationDidChange object:nil];
  939. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationDidChange:) name:PCS_NotificationNameOrientationDidChange object:nil];
  940. UIDeviceOrientation deviceOrientation = UIDeviceOrientationPortrait;
  941. AVCaptureVideoOrientation orientation = [self videoOrientation:&deviceOrientation];
  942. CGFloat degree = 0;
  943. AVCaptureDevice* camera = self.currentCamera;
  944. CameraManager* cameraMgr = [CameraManager shared];
  945. BOOL isFront = camera == cameraMgr.front;
  946. BOOL isLandscape = NO;
  947. // 前摄像头需要镜像一下
  948. CGAffineTransform originalMat = isFront ? CGAffineTransformMakeScale(-1, 1) : CGAffineTransformIdentity;
  949. switch (deviceOrientation) {
  950. case UIDeviceOrientationPortrait:
  951. // self.panoramOrientationGuideView.selectedItemIndex = PanoramaOrientationViewUp;
  952. degree = 0;
  953. break;
  954. case UIDeviceOrientationLandscapeRight:
  955. // self.panoramOrientationGuideView.selectedItemIndex = PanoramaOrientationViewRight;
  956. degree = isFront ? 90 : -90;
  957. isLandscape = YES;
  958. break;
  959. case UIDeviceOrientationPortraitUpsideDown:
  960. // self.panoramOrientationGuideView.selectedItemIndex = PanoramaOrientationViewDown;
  961. degree = 180;
  962. break;
  963. case UIDeviceOrientationLandscapeLeft:
  964. // self.panoramOrientationGuideView.selectedItemIndex = PanoramaOrientationViewLeft;
  965. degree = isFront ? -90 : 90;
  966. isLandscape = YES;
  967. break;
  968. default:
  969. break;
  970. }
  971. __block BOOL ret = NO;
  972. dispatch_sync(self.videoDataQueue, ^{
  973. if(self.videoDataOutput.sampleBufferDelegate != nil){
  974. return;
  975. }
  976. if([self configureVideoWritter]){
  977. AVCaptureConnection *connection = [self.videoDataOutput connectionWithMediaType:AVMediaTypeVideo];
  978. if(connection == nil){
  979. [self showAlertForAuthorization];
  980. return;
  981. }
  982. [connection setVideoOrientation:orientation];
  983. // self.panoramaGuideView.transform = CGAffineTransformRotate(originalMat, dgree_2_rad(degree));
  984. // 设置小预览框高宽比
  985. CGFloat aspect = isFront ? cameraMgr.frontAspect : cameraMgr.backAspect;
  986. aspect = isLandscape ? 1.0 / aspect : aspect;
  987. // [self.panoramaGuideView updatePreviewAspect: aspect];
  988. // self.panoramOrientationGuideView.transform = self.panoramaGuideView.transform;
  989. [self.videoDataOutput setSampleBufferDelegate:self queue:self.videoDataQueue];
  990. ret = YES;
  991. }
  992. });
  993. return ret;
  994. }
  995. - (PanoramaGuideView *)panoramaGuideView{
  996. if (_panoramaGuideView == nil) {
  997. _panoramaGuideView = [[PanoramaGuideView alloc]init];
  998. _panoramaGuideView.hidden = YES;
  999. }
  1000. return _panoramaGuideView;;
  1001. }
  1002. - (void)stopVideoDataOutputing{
  1003. [self.motionTimer invalidate];
  1004. self.motionTimer = nil;
  1005. [[NSNotificationCenter defaultCenter] removeObserver:self name:PCS_NotificationNameOrientationDidChange object:nil];
  1006. dispatch_async(self.videoDataQueue, ^{
  1007. [self.videoDataOutput setSampleBufferDelegate:nil queue:nil];
  1008. [Renderer shared].cameraPass.texture = nil;
  1009. });
  1010. [self stopMotion];
  1011. [self.panoramaGuideView showImageWith:nil dir:self.panoramOrientationGuideView.selectedItemIndex];
  1012. }
  1013. - (void)updateViewStatusWhenStitchSave:(BOOL)isSaveIng {
  1014. dispatch_async(dispatch_get_main_queue(), ^{
  1015. self.stitchView.hidden = !isSaveIng;
  1016. if (self.stitchView.hidden) {
  1017. [self.stitchImageView.layer removeAnimationForKey:@"loadingAnimation"];
  1018. } else {
  1019. [self.stitchImageView.layer addAnimation:self.loadingAnimation forKey:@"loadingAnimation"];
  1020. }
  1021. self.flashButton.hidden = isSaveIng;
  1022. if (self.mode == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA) {
  1023. self.panoramOrientationGuideView.hidden = YES;
  1024. self.ai_fullView.hidden = YES;
  1025. self.panoramaGuideView.hidden = YES;
  1026. } else {
  1027. self.panoramOrientationGuideView.hidden = isSaveIng;
  1028. self.ai_fullView.hidden = isSaveIng;
  1029. self.panoramaGuideView.hidden = isSaveIng;
  1030. }
  1031. self.modeList.hidden = isSaveIng;
  1032. self.savePhotoButton.hidden = isSaveIng;
  1033. self.takePhotoButton.hidden = isSaveIng;
  1034. // self.switchButton.hidden = isSaveIng;
  1035. self.discardPhotoButton.hidden = isSaveIng;
  1036. self.backButton.hidden = !isSaveIng;
  1037. self.ablumImageView.hidden = isSaveIng;
  1038. // self.timerLabel.hidden = isSaveIng;
  1039. });
  1040. }
  1041. - (void)updateViewStatusWhenStitchFail {
  1042. dispatch_async(dispatch_get_main_queue(), ^{
  1043. self.stitchView.hidden = YES;
  1044. self.flashButton.hidden = NO;
  1045. self.modeList.hidden = NO;
  1046. self.savePhotoButton.hidden = NO;
  1047. self.takePhotoButton.hidden = NO;
  1048. if (self.mode == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA) {
  1049. self.ai_fullView.hidden = YES;
  1050. self.panoramOrientationGuideView.hidden = YES;
  1051. self.panoramaGuideView.hidden = YES;
  1052. } else {
  1053. self.ai_fullView.hidden = NO;
  1054. self.panoramOrientationGuideView.hidden = NO;
  1055. self.panoramaGuideView.hidden = NO;
  1056. }
  1057. // self.switchButton.hidden = isSaveIng;
  1058. self.discardPhotoButton.hidden = NO;
  1059. self.backButton.hidden = YES;
  1060. self.ablumImageView.hidden = NO;
  1061. [self.takePhotoButton setImage:[UIImage loadNamed:@"take-photo-btn"] forState:UIControlStateNormal];
  1062. // self.timerLabel.hidden = isSaveIng;
  1063. });
  1064. }
  1065. - (BOOL)getStitchBigImageIfNeed {
  1066. BOOL isSuccess = NO;
  1067. NSString *s = [LenStitcher getCurrentPanoramaShow];
  1068. if (s.length) {
  1069. isSuccess = YES;
  1070. }
  1071. return isSuccess;
  1072. }
  1073. - (BOOL)configureVideoWritter{
  1074. // setup asset writter for the video data output
  1075. NSURL* tmpMovieFileUrl = [NSURL fileURLWithPath:[[PCSTools shared].tmpPath stringByAppendingPathComponent:@"video-data-tmp-file.mov"] isDirectory:NO];
  1076. NSError* err = nil;
  1077. [[NSFileManager defaultManager] removeItemAtURL:tmpMovieFileUrl error:nil];
  1078. self.videoWriter = [[AVAssetWriter alloc] initWithURL:tmpMovieFileUrl fileType:AVFileTypeQuickTimeMovie error:&err];
  1079. if(err != nil){
  1080. NSLog(@"%@", err);
  1081. self.videoWriter = nil;
  1082. return NO;
  1083. }
  1084. SDKParameters* params = [SDKParameters shared];
  1085. NSDictionary* settings = [NSDictionary dictionaryWithObjectsAndKeys:
  1086. AVVideoCodecTypeH264, AVVideoCodecKey,
  1087. [NSNumber numberWithInteger: params.resolution.width], AVVideoWidthKey,
  1088. [NSNumber numberWithInteger: params.resolution.height], AVVideoHeightKey,
  1089. nil];
  1090. self.videoWriterInput = [AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeVideo outputSettings:settings];
  1091. self.videoWriterInput.expectsMediaDataInRealTime = YES;
  1092. [self.videoWriter addInput:self.videoWriterInput];
  1093. return YES;
  1094. }
  1095. - (void)prepareCamera{
  1096. if (self.cameraPrepared) {
  1097. return;
  1098. }
  1099. AVCaptureDevice* device = [SDKParameters shared].cameraPosition == SDK_CAMERA_PISITION_BACK ? [CameraManager shared].back : [CameraManager shared].front;
  1100. if (device == nil) {
  1101. self.cameraPrepared = false;
  1102. return;
  1103. }
  1104. NSError* error;
  1105. AVCaptureDeviceInput* input = [[AVCaptureDeviceInput alloc] initWithDevice:device error:&error];
  1106. if(error != nil){
  1107. self.cameraPrepared = false;
  1108. return;
  1109. }
  1110. [self.captureSession beginConfiguration];
  1111. if([self.captureSession canAddInput:input]){
  1112. [self.captureSession addInput:input];
  1113. }
  1114. else{
  1115. return;
  1116. }
  1117. self.previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:self.captureSession];
  1118. self.previewLayer.frame = self.view.layer.bounds;
  1119. self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
  1120. [self.view.layer insertSublayer:self.previewLayer atIndex:0u];
  1121. if([self.captureSession canAddOutput:self.photoOutput]){
  1122. [self.captureSession addOutput:self.photoOutput];
  1123. }
  1124. if([self.captureSession canAddOutput:self.movieFileOutput]){
  1125. [self.captureSession addOutput:self.movieFileOutput];
  1126. }
  1127. [self.captureSession commitConfiguration];
  1128. self.cameraPrepared = YES;
  1129. [[CameraManager shared] setResolutionFor:AVCaptureDevicePositionBack with:self.parameters.resolution.height];
  1130. [[CameraManager shared] setResolutionFor:AVCaptureDevicePositionFront with:self.parameters.resolution.height];
  1131. [self updatePreViewLayer];
  1132. }
  1133. #pragma mark - Gesture
  1134. - (void)tapGestureHandler: (UITapGestureRecognizer*)gesture{
  1135. switch(gesture.state){
  1136. case UIGestureRecognizerStateBegan:{
  1137. break;
  1138. }
  1139. case UIGestureRecognizerStateChanged:{
  1140. break;
  1141. }
  1142. case UIGestureRecognizerStateEnded:{
  1143. CGPoint pt = [gesture locationInView:self.view];
  1144. [self focusOn:pt];
  1145. break;
  1146. }
  1147. case UIGestureRecognizerStateCancelled:{
  1148. break;
  1149. }
  1150. default:
  1151. break;
  1152. }
  1153. }
  1154. - (void)panGestureHandler: (UIPanGestureRecognizer*)gesture{
  1155. switch(gesture.state){
  1156. case UIGestureRecognizerStateBegan:{
  1157. break;
  1158. }
  1159. case UIGestureRecognizerStateChanged:{
  1160. if(self.flag){
  1161. return;
  1162. }
  1163. self.flag = YES;
  1164. CGPoint translation = [gesture translationInView:self.view];
  1165. [self.modeList updateIndexByTanslation:translation];
  1166. break;
  1167. }
  1168. case UIGestureRecognizerStateEnded:{
  1169. self.flag = NO;
  1170. break;
  1171. }
  1172. case UIGestureRecognizerStateCancelled:{
  1173. self.flag = NO;
  1174. break;
  1175. }
  1176. default:
  1177. self.flag = NO;
  1178. break;
  1179. }
  1180. }
  1181. #pragma mark - orientation
  1182. - (UIInterfaceOrientationMask)supportedInterfaceOrientations{
  1183. return UIInterfaceOrientationMaskPortrait;
  1184. }
  1185. - (void)updateUIByMode{
  1186. self.albumButton.hidden = YES;
  1187. self.numberOfImagesLabel.hidden = YES;
  1188. self.modeLabel.text = self.currentOperationNode.modeTitleString;
  1189. self.ai_fullView.hidden = !(self.mode == SDK_CAPTURE_MODE_PANORAMA);
  1190. self.panGesture.enabled = YES;
  1191. // self.controller.savePhotoButton.hidden = !self.hasCache;
  1192. // self.controller.discardPhotoButton.hidden = !self.hasCache;
  1193. //
  1194. // self.controller.albumButton.hidden = !self.hasCache;
  1195. // self.controller.backButton.hidden = self.hasCache;
  1196. if([self.currentOperationNode respondsToSelector:@selector(updateUI)]){
  1197. [self.currentOperationNode updateUI];
  1198. }
  1199. [self updatePreViewLayer];
  1200. }
  1201. - (void)updatePreViewLayer {
  1202. CGFloat width = [UIScreen mainScreen].bounds.size.width;
  1203. CGFloat height = [UIScreen mainScreen].bounds.size.height;
  1204. switch (self.mode) {
  1205. case SDK_CAPTURE_MODE_CONTINUOUS: {
  1206. self.switchButton.hidden = NO;
  1207. self.panoramaGuideView.hidden = YES;
  1208. self.panoramOrientationGuideView.hidden = YES;
  1209. self.previewLayer.frame = CGRectMake(0, (height - width*4/3)/2, width, width*4/3);
  1210. }
  1211. break;
  1212. case SDK_CAPTURE_MODE_SINGLE: {
  1213. self.switchButton.hidden = NO;
  1214. self.panoramaGuideView.hidden = YES;
  1215. self.panoramOrientationGuideView.hidden = YES;
  1216. self.previewLayer.frame = CGRectMake(0, (height - width*4/3)/2, width, width*4/3);
  1217. }
  1218. break;
  1219. case SDK_CAPTURE_MODE_MOVIE: {
  1220. self.switchButton.hidden = NO;
  1221. self.panoramaGuideView.hidden = YES;
  1222. self.panoramOrientationGuideView.hidden = YES;
  1223. self.previewLayer.frame = self.view.layer.bounds;
  1224. }
  1225. break;
  1226. case SDK_CAPTURE_MODE_PANORAMA: {
  1227. self.switchButton.hidden = YES;
  1228. self.panoramaGuideView.hidden = NO;
  1229. self.panoramOrientationGuideView.hidden = NO;
  1230. self.previewLayer.frame = self.view.layer.bounds;
  1231. }
  1232. break;
  1233. case SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA: {
  1234. self.switchButton.hidden = YES;
  1235. self.panoramaGuideView.hidden = YES;
  1236. self.panoramOrientationGuideView.hidden = YES;
  1237. self.previewLayer.frame = self.view.layer.bounds;
  1238. }
  1239. break;
  1240. default:
  1241. break;
  1242. }
  1243. }
  1244. - (void)modeWillChange: (NSUInteger)newIndex oldIndex: (NSUInteger)oldIndex{
  1245. if(newIndex >= INT_MAX){
  1246. return;
  1247. }
  1248. [self.currentOperationNode willQuitOnCompletion:^() {}];
  1249. }
  1250. - (void)modeDidChange: (NSUInteger)newIndex oldIndex: (NSUInteger)oldIndex{
  1251. if(newIndex >= INT_MAX){
  1252. return;
  1253. }
  1254. // self.modeList.userInteractionEnabled = NO;
  1255. // [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark]
  1256. if(self.effectView.superview != nil){
  1257. // self.effectView.effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
  1258. [UIView animateWithDuration:0.5 animations:^{
  1259. self.effectView.effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
  1260. }];
  1261. }
  1262. dispatch_async(dispatch_get_global_queue(0, 0), ^{
  1263. if(newIndex == SDK_CAPTURE_MODE_SINGLE || newIndex == SDK_CAPTURE_MODE_CONTINUOUS){
  1264. [[CameraManager shared] setResolutionFor:AVCaptureDevicePositionBack with:self.parameters.resolution.height];
  1265. [[CameraManager shared] setResolutionFor:AVCaptureDevicePositionFront with:self.parameters.resolution.height];
  1266. }
  1267. else{
  1268. [[CameraManager shared] setResolutionFor:AVCaptureDevicePositionBack with:self.parameters.videoResolution.height];
  1269. [[CameraManager shared] setResolutionFor:AVCaptureDevicePositionFront with:self.parameters.videoResolution.height];
  1270. }
  1271. PhotographModeEnum oldModeEnum = (PhotographModeEnum)(oldIndex);
  1272. if((self.mode == SDK_CAPTURE_MODE_PANORAMA || self.mode == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA)
  1273. && oldModeEnum != SDK_CAPTURE_MODE_PANORAMA
  1274. && oldModeEnum != SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA){
  1275. if([self.captureSession canAddOutput:self.videoDataOutput]){
  1276. [self.captureSession addOutput:self.videoDataOutput];
  1277. [self.captureSession removeOutput:self.movieFileOutput];
  1278. }
  1279. }
  1280. else if((self.mode == SDK_CAPTURE_MODE_MOVIE)
  1281. && (oldModeEnum == SDK_CAPTURE_MODE_PANORAMA
  1282. || oldModeEnum == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA)){
  1283. if([self.captureSession canAddOutput:self.movieFileOutput]){
  1284. [self.captureSession addOutput:self.movieFileOutput];
  1285. [self.captureSession removeOutput:self.videoDataOutput];
  1286. }
  1287. }
  1288. dispatch_sync(dispatch_get_main_queue(), ^{
  1289. // self.modeList.userInteractionEnabled = YES;
  1290. self.effectView.effect = nil;
  1291. });
  1292. });
  1293. [self updateUIByMode];
  1294. [self switchDevicePositionBack];
  1295. [self updateNumberLabel];
  1296. }
  1297. - (void)setupMicrophone{
  1298. NSError* audioError = nil;
  1299. AVCaptureDevice* audioDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
  1300. AVCaptureDeviceInput* audioInput = [AVCaptureDeviceInput deviceInputWithDevice:audioDevice error:&audioError];
  1301. if(audioError == nil){
  1302. AVCaptureAudioDataOutput* audioOutput = [[AVCaptureAudioDataOutput alloc] init];
  1303. [audioOutput setSampleBufferDelegate:self queue:dispatch_get_global_queue(0, 0)];
  1304. if([self.captureSession canAddInput:audioInput]){
  1305. [self.captureSession addInput:audioInput];
  1306. }
  1307. if([self.captureSession canAddOutput:audioOutput]){
  1308. [self.captureSession addOutput:audioOutput];
  1309. }
  1310. }
  1311. }
  1312. - (UIStatusBarStyle)preferredStatusBarStyle{
  1313. return UIStatusBarStyleLightContent;
  1314. }
  1315. #pragma mark 方向调用的代理
  1316. - (void)panoramaOrientationViewslt:(PanoramaOrientationViewDirectionEnum)direction{
  1317. // NSLog(@"方向%ld",direction);
  1318. self.panoramaGuideView.hidden = NO;
  1319. // [LenStitcher videoResetPath];
  1320. [UIView animateWithDuration:0.25 animations:^{
  1321. [self.panoramaGuideView mas_remakeConstraints:^(MASConstraintMaker *make) {
  1322. switch (direction) {
  1323. case PanoramaOrientationViewLeft:
  1324. case PanoramaOrientationViewRight:
  1325. {
  1326. make.left.right.offset(0);
  1327. make.centerY.mas_equalTo(self.view);
  1328. make.height.mas_equalTo(PanoramaGuideViewWOrH);
  1329. }
  1330. break;
  1331. case PanoramaOrientationViewUp:
  1332. case PanoramaOrientationViewDown:
  1333. {
  1334. make.centerX.mas_equalTo(self.view);
  1335. make.width.mas_equalTo(PanoramaGuideViewWOrH);
  1336. make.bottom.mas_equalTo(self.panoramOrientationGuideView.mas_top).offset(-25);
  1337. make.top.mas_equalTo(self.timerLabel.mas_bottom).offset(15);
  1338. }
  1339. break;
  1340. case PanoramaOrientationViewAny: {
  1341. self.panoramaGuideView.hidden = YES;
  1342. }
  1343. break;
  1344. default:
  1345. break;
  1346. }
  1347. }];
  1348. if (self.mode != SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA) {
  1349. [self.panoramaGuideView setNeedsLayout];
  1350. [self.panoramaGuideView layoutIfNeeded];
  1351. }
  1352. } completion:^(BOOL finished) {
  1353. [self.panoramaGuideView direction:direction];
  1354. }];
  1355. }
  1356. - (void)stopAllSensors{
  1357. [self.captureSession stopRunning];
  1358. [[PCSMotionManager shared] stopAccelerometerUpdates];
  1359. }
  1360. #pragma mark - session
  1361. - (void)turnTorchOff{
  1362. AVCaptureDevice* currentDevice = self.currentCamera;
  1363. if(currentDevice == nil || !currentDevice.hasTorch){
  1364. return;
  1365. }
  1366. NSError* error;
  1367. if(error == nil){
  1368. [currentDevice lockForConfiguration:&error];
  1369. currentDevice.torchMode = AVCaptureTorchModeOff;
  1370. [currentDevice unlockForConfiguration];
  1371. }
  1372. }
  1373. - (void)stopCaptureSession{
  1374. [self turnTorchOff];
  1375. if (self.captureSession.isRunning) {
  1376. [self.captureSession stopRunning];
  1377. }
  1378. }
  1379. - (void)startCaptureSession{
  1380. if (!self.cameraPrepared) {
  1381. [self prepareCamera];
  1382. }
  1383. if (self.cameraPrepared && (!self.captureSession.isRunning)) {
  1384. [self.captureSession startRunning];
  1385. }
  1386. }
  1387. #pragma mark - Btn call back
  1388. -(IBAction)switchCameraTapped:(id)sender
  1389. {
  1390. if(self.captureSession == nil){
  1391. return;
  1392. }
  1393. AVCaptureDeviceInput* currInput = self.currentCameraInput;
  1394. if(currInput == nil){
  1395. return;
  1396. }
  1397. AVCaptureDevice* currentDevice = currInput.device;
  1398. AVCaptureDevice *newCamera = nil;
  1399. if(currentDevice.position == AVCaptureDevicePositionBack){
  1400. newCamera = [CameraManager shared].front;
  1401. }
  1402. else if(currentDevice.position == AVCaptureDevicePositionFront){
  1403. newCamera = [CameraManager shared].back;
  1404. }
  1405. else{
  1406. return;
  1407. }
  1408. [self.captureSession beginConfiguration];
  1409. if(currentDevice.hasTorch){
  1410. NSError* error;
  1411. [currentDevice lockForConfiguration:&error];
  1412. currentDevice.torchMode = AVCaptureTorchModeOff;
  1413. [currentDevice unlockForConfiguration];
  1414. }
  1415. [self.captureSession removeInput:currInput];
  1416. self.flashButton.hidden = !newCamera.hasFlash;
  1417. NSError *err = nil;
  1418. AVCaptureDeviceInput *newVideoInput = [[AVCaptureDeviceInput alloc] initWithDevice:newCamera error:&err];
  1419. if(newVideoInput == nil || err != nil){
  1420. NSLog(@"Error creating capture device input: %@", err.localizedDescription);
  1421. }
  1422. else if([self.captureSession canAddInput:newVideoInput]){
  1423. [self.captureSession addInput:newVideoInput];
  1424. }
  1425. [self.captureSession commitConfiguration];
  1426. }
  1427. - (void)switchDevicePositionBack {
  1428. if(self.captureSession == nil ||
  1429. (self.mode != SDK_CAPTURE_MODE_PANORAMA && self.mode != SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA)){
  1430. return;
  1431. }
  1432. AVCaptureDeviceInput* currInput = self.currentCameraInput;
  1433. if(currInput == nil){
  1434. return;
  1435. }
  1436. AVCaptureDevice* currentDevice = currInput.device;
  1437. AVCaptureDevice *newCamera = nil;
  1438. if(currentDevice.position == AVCaptureDevicePositionBack){
  1439. return;
  1440. }
  1441. if(currentDevice.position == AVCaptureDevicePositionFront){
  1442. newCamera = [CameraManager shared].back;
  1443. }
  1444. [self.captureSession beginConfiguration];
  1445. if(currentDevice.hasTorch){
  1446. NSError* error;
  1447. [currentDevice lockForConfiguration:&error];
  1448. currentDevice.torchMode = AVCaptureTorchModeOff;
  1449. [currentDevice unlockForConfiguration];
  1450. }
  1451. [self.captureSession removeInput:currInput];
  1452. NSError *err = nil;
  1453. AVCaptureDeviceInput *newVideoInput = [[AVCaptureDeviceInput alloc] initWithDevice:newCamera error:&err];
  1454. if(newVideoInput == nil || err != nil){
  1455. NSLog(@"Error creating capture device input: %@", err.localizedDescription);
  1456. } else if([self.captureSession canAddInput:newVideoInput]){
  1457. [self.captureSession addInput:newVideoInput];
  1458. }
  1459. [self.captureSession commitConfiguration];
  1460. }
  1461. - (void)takePhotoButtonTouchUpInside:(id)sender{
  1462. self.takePhotoButton.enabled = NO;
  1463. if (self.outputSettings.flashMode == AVCaptureFlashModeOn && (self.mode == SDK_CAPTURE_MODE_SINGLE || self.mode == SDK_CAPTURE_MODE_CONTINUOUS || self.mode == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA)) {
  1464. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  1465. self.takePhotoButton.enabled = YES;
  1466. });
  1467. } else {
  1468. dispatch_async(dispatch_get_main_queue(), ^{
  1469. self.takePhotoButton.enabled = YES;
  1470. });
  1471. }
  1472. if(![self.currentOperationNode respondsToSelector:@selector(enable)] || self.currentOperationNode.enable){
  1473. if (self.mode == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA) {
  1474. // [LenStitcher videoResetPath];
  1475. // LenzResourceItemModel *itemModel = [[LenzResourceItemModel alloc]init];
  1476. // [self.resourceModel.aiPanoramArray addObject:itemModel];
  1477. OperationNodeAIPanorama *aiPan = nil;
  1478. if ([self.currentOperationNode isKindOfClass:[OperationNodeAIPanorama class]]) {
  1479. aiPan = self.currentOperationNode;
  1480. if (!aiPan.isRecording) {
  1481. aiPan.AIType = OperationAITypeTap;
  1482. }
  1483. }
  1484. // [self startMotion];
  1485. // if (self.isVideoStitchStopedWhenRecording) {
  1486. //
  1487. //
  1488. //
  1489. // return;
  1490. // }
  1491. }
  1492. [self.currentOperationNode takePhotoButtonTouched];
  1493. if (self.mode == SDK_CAPTURE_MODE_PANORAMA && !self.isVideoStitchStopedWhenRecording) {
  1494. [LenStitcher videoResetPath];
  1495. LenzResourceItemModel *itemModel = [[LenzResourceItemModel alloc]init];
  1496. [self.resourceModel.panoramArray addObject:itemModel];
  1497. [self startMotion];
  1498. // self.videoStitchSemaphore = dispatch_semaphore_create(1);
  1499. }
  1500. // if (self.mode == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA) {
  1501. //
  1502. // OperationNodeAIPanorama *aiPan = nil;
  1503. // if ([self.currentOperationNode isKindOfClass:[OperationNodeAIPanorama class]]) {
  1504. // aiPan = self.currentOperationNode;
  1505. // aiPan.AIType = OperationAITypeTap;
  1506. // }
  1507. //
  1508. // }
  1509. }
  1510. }
  1511. - (void)longPressGes:(UILongPressGestureRecognizer *)ges {
  1512. switch (ges.state) {
  1513. case UIGestureRecognizerStateBegan:
  1514. {
  1515. if (self.mode == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA) {
  1516. OperationNodeAIPanorama *aiPan = nil;
  1517. if ([self.currentOperationNode isKindOfClass:[OperationNodeAIPanorama class]]) {
  1518. // self.videoStitchSemaphore = dispatch_semaphore_create(1);
  1519. [LenStitcher videoResetPath];
  1520. LenzResourceItemModel *itemModel = [[LenzResourceItemModel alloc]init];
  1521. [self.resourceModel.aiPanoramArray addObject:itemModel];
  1522. [self startMotion];
  1523. aiPan = self.currentOperationNode;
  1524. // self.touchTime = 0;
  1525. aiPan.AIType = OperationAITypeLongPress;
  1526. [self.currentOperationNode takePhotoButtonTouched];
  1527. }
  1528. }
  1529. }
  1530. break;
  1531. case UIGestureRecognizerStateEnded:
  1532. break;
  1533. default:
  1534. break;
  1535. }
  1536. }
  1537. - (void)takePhotoButtonTouchDownInside:(id)sender{
  1538. }
  1539. - (void)flashButtonTouchUpInside:(id)sender{
  1540. AVCaptureDevice* currentDevice = self.currentCamera;
  1541. if(currentDevice == nil || !currentDevice.hasFlash){
  1542. return;
  1543. }
  1544. NSError* error = nil;
  1545. [currentDevice lockForConfiguration:&error];
  1546. if(error != nil){
  1547. return;
  1548. }
  1549. if(self.outputSettings.flashMode == AVCaptureFlashModeOn){
  1550. self.outputSettings.flashMode = AVCaptureFlashModeAuto;
  1551. [self.flashButton setImage:[UIImage sdkImageNamed:@"flash-auto-btn"] forState:UIControlStateNormal];
  1552. }
  1553. else if(self.outputSettings.flashMode == AVCaptureFlashModeAuto){
  1554. self.outputSettings.flashMode = AVCaptureFlashModeOff;
  1555. [self.flashButton setImage:[UIImage sdkImageNamed:@"flash-disable-btn"] forState:UIControlStateNormal];
  1556. }
  1557. else{
  1558. self.outputSettings.flashMode = AVCaptureFlashModeOn;
  1559. [self.flashButton setImage:[UIImage sdkImageNamed:@"flash-btn"] forState:UIControlStateNormal];
  1560. }
  1561. [currentDevice unlockForConfiguration];
  1562. }
  1563. - (void)backButtonTouchUpInside:(id)sender{
  1564. if (!self.stitchView.hidden) {
  1565. [QuitMultipleModeAlertViewController show:self title:@"确认提醒" text:@"图片拼接中,返回会清空正在拼接的数据" leftBtnTitle:@"取消" rightBtnTitle:@"确定" withLeftButtonCallBack:^(QuitMultipleModeAlertViewController * _Nonnull alertController) {
  1566. [alertController dismissViewControllerAnimated:NO completion:^{}];
  1567. } rightButtonCallBack:^(QuitMultipleModeAlertViewController * _Nonnull alertController) {
  1568. [self updateViewStatusWhenStitchSave:NO];
  1569. [alertController dismissViewControllerAnimated:NO completion:^{
  1570. // [self dismissViewControllerAnimated:YES completion:^{}];
  1571. }];
  1572. }];
  1573. } else {
  1574. [self dismissViewControllerAnimated:YES completion:^{}];
  1575. }
  1576. }
  1577. - (void)makeResData:(NSMutableArray <LenzResourceItemModel *> *)array {
  1578. [array enumerateObjectsUsingBlock:^(LenzResourceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1579. }];
  1580. }
  1581. - (void)savePhotoButtonTouchUpInside:(id)sender{
  1582. //待优化
  1583. NSMutableArray *res = [NSMutableArray array];
  1584. __block NSInteger idIndex = 1;
  1585. [self.resourceModel.singleArray enumerateObjectsUsingBlock:^(LenzResourceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1586. idIndex += idx;
  1587. NSMutableDictionary *dict = [NSMutableDictionary dictionary];
  1588. dict[@"id"] = [NSString stringWithFormat:@"%ld", idIndex];
  1589. dict[@"path"] = obj.path;
  1590. dict[@"cameraMode"] = obj.cameraMode;
  1591. dict[@"cameraType"] = obj.cameraType;
  1592. dict[@"isRemake"] = @(obj.isRemake);
  1593. [res addObject:dict];
  1594. }];
  1595. [self.resourceModel.continousArray enumerateObjectsUsingBlock:^(LenzResourceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1596. idIndex += idx;
  1597. NSMutableDictionary *dict = [NSMutableDictionary dictionary];
  1598. dict[@"id"] = [NSString stringWithFormat:@"%ld", idIndex];
  1599. dict[@"path"] = obj.path;
  1600. dict[@"cameraMode"] = obj.cameraMode;
  1601. dict[@"cameraType"] = obj.cameraType;
  1602. dict[@"isRemake"] = @(obj.isRemake);
  1603. [res addObject:dict];
  1604. }];
  1605. [self.resourceModel.movieArray enumerateObjectsUsingBlock:^(LenzResourceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1606. idIndex += idx;
  1607. NSMutableDictionary *dict = [NSMutableDictionary dictionary];
  1608. dict[@"id"] = [NSString stringWithFormat:@"%ld", idIndex];
  1609. dict[@"path"] = obj.path;
  1610. dict[@"cameraMode"] = obj.cameraMode;
  1611. dict[@"cameraType"] = obj.cameraType;
  1612. dict[@"isRemake"] = @(obj.isRemake);
  1613. [res addObject:dict];
  1614. }];
  1615. [self.resourceModel.panoramArray enumerateObjectsUsingBlock:^(LenzResourceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1616. if (obj.path.length) {
  1617. idIndex += idx;
  1618. NSMutableDictionary *dict = [NSMutableDictionary dictionary];
  1619. dict[@"id"] = [NSString stringWithFormat:@"%ld", idIndex];
  1620. dict[@"path"] = obj.path;
  1621. dict[@"cameraMode"] = obj.cameraMode;
  1622. dict[@"cameraType"] = obj.cameraType;
  1623. dict[@"isRemake"] = @(obj.isRemake);
  1624. NSMutableArray *keyFrame = [NSMutableArray array];
  1625. [obj.keyFrame enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1626. [keyFrame addObject:obj];
  1627. }];
  1628. dict[@"keyFrame"] = keyFrame;
  1629. [res addObject:dict];
  1630. }
  1631. }];
  1632. [self.resourceModel.aiPanoramArray enumerateObjectsUsingBlock:^(LenzResourceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1633. if (obj.path.length) {
  1634. idIndex += idx;
  1635. NSMutableDictionary *dict = [NSMutableDictionary dictionary];
  1636. dict[@"id"] = [NSString stringWithFormat:@"%ld", idIndex];
  1637. dict[@"path"] = obj.path;
  1638. dict[@"cameraMode"] = obj.cameraMode;
  1639. dict[@"cameraType"] = obj.cameraType;
  1640. dict[@"isRemake"] = @(obj.isRemake);
  1641. NSMutableArray *keyFrame = [NSMutableArray array];
  1642. [obj.keyFrame enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1643. [keyFrame addObject:obj];
  1644. }];
  1645. dict[@"keyFrame"] = keyFrame;
  1646. [res addObject:dict];
  1647. }
  1648. }];
  1649. if (self.completeBlock) {
  1650. NSMutableDictionary *dict = [NSMutableDictionary dictionary];
  1651. dict[@"code"] = @(200);
  1652. dict[@"message"] = @"成功";
  1653. dict[@"data"] = res;
  1654. self.completeBlock(dict);
  1655. [self dismissViewControllerAnimated:YES completion:^{
  1656. }];
  1657. }
  1658. // self.panGesture.enabled = YES;
  1659. // // Access has not been determined.
  1660. // [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
  1661. //
  1662. // dispatch_async(dispatch_get_main_queue(), ^{
  1663. // if (status == PHAuthorizationStatusAuthorized) {
  1664. // // Access has been granted.
  1665. // [self.currentOperationNode save];
  1666. // }
  1667. // else {
  1668. // // Access has been denied.
  1669. // [self showAlertForAuthorizationWithText:@"请设置相册权限后重试"];
  1670. // }
  1671. // });
  1672. // }];
  1673. }
  1674. - (void)discardPhotoResultButtonTouchUpInside:(id)sender{
  1675. self.panGesture.enabled = YES;
  1676. // if([self.currentOperationNode respondsToSelector:@selector(discardPhotoResultButtonTouchUpInside)]){
  1677. // [self.currentOperationNode discardPhotoResultButtonTouchUpInside];
  1678. // }
  1679. NSString *title = @"返回会清空已拍摄数据,请确认!";
  1680. // if (self.mode == SDK_CAPTURE_MODE_MOVIE) {
  1681. // title = @"返回会清空已拍摄视频,请确认!";
  1682. // } else if (self.mode == SDK_CAPTURE_MODE_PANORAMA || self.mode == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA) {
  1683. // title = @"返回会清空已拼接图片,请确认!";
  1684. // }
  1685. [QuitMultipleModeAlertViewController show:self title:@"确认提醒" text:title leftBtnTitle:@"取消" rightBtnTitle:@"确定" withLeftButtonCallBack:^(QuitMultipleModeAlertViewController * _Nonnull alertController) {
  1686. [alertController dismissViewControllerAnimated:NO completion:^{}];
  1687. } rightButtonCallBack:^(QuitMultipleModeAlertViewController * _Nonnull alertController) {
  1688. // if (self.mode == SDK_CAPTURE_MODE_CONTINUOUS) {
  1689. [self.resourceModel.continousArray removeAllObjects];
  1690. // } else if (self.mode == SDK_CAPTURE_MODE_MOVIE) {
  1691. [self.resourceModel.movieArray removeAllObjects];
  1692. // } else if (self.mode == SDK_CAPTURE_MODE_PANORAMA) {
  1693. [self.resourceModel.panoramArray removeAllObjects];
  1694. // } else if (self.mode == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA) {
  1695. [self.resourceModel.aiPanoramArray removeAllObjects];
  1696. // }
  1697. [self updateViewStatus];
  1698. [alertController dismissViewControllerAnimated:NO completion:^{
  1699. }];
  1700. }];
  1701. }
  1702. - (void)albumButtonTouchUpInside:(id)sender{
  1703. [self performSegueWithIdentifier:@"show-photoalbum" sender:nil];
  1704. // if([self.currentOperationNode respondsToSelector:@selector(segueForAlbum)]){
  1705. // [self performSegueWithIdentifier:self.currentOperationNode.segueForAlbum sender:nil];
  1706. // }
  1707. }
  1708. - (__kindof id<OperationNodeProtocol>)currentOperationNode{
  1709. // NSLog(@"======:%u",self.mode);
  1710. // NSLog(@"------:%@",self.operationNodes);
  1711. return self.operationNodes[@(self.mode)];
  1712. }
  1713. - (void)updateNumberLabel {
  1714. switch (self.mode) {
  1715. case SDK_CAPTURE_MODE_CONTINUOUS: {
  1716. if (self.resourceModel.continousArray.count > 0) {
  1717. self.numberOfImagesLabel.hidden = NO;
  1718. self.numberOfImagesLabel.text = [NSString stringWithFormat:@"已连拍%ld张", self.resourceModel.continousArray.count];
  1719. } else {
  1720. self.numberOfImagesLabel.hidden = YES;
  1721. }
  1722. }
  1723. break;
  1724. case SDK_CAPTURE_MODE_MOVIE:{
  1725. if (self.resourceModel.movieArray.count > 0) {
  1726. self.numberOfImagesLabel.hidden = NO;
  1727. self.numberOfImagesLabel.text = [NSString stringWithFormat:@"已拍视频%ld条", self.resourceModel.movieArray.count];
  1728. } else {
  1729. self.numberOfImagesLabel.hidden = YES;
  1730. }
  1731. }
  1732. break;
  1733. case SDK_CAPTURE_MODE_PANORAMA:
  1734. {
  1735. if (self.resourceModel.panoramArray.count > 0) {
  1736. self.numberOfImagesLabel.hidden = NO;
  1737. self.numberOfImagesLabel.text = [NSString stringWithFormat:@"已拼接%ld张", self.resourceModel.panoramArray.count];
  1738. } else {
  1739. self.numberOfImagesLabel.hidden = YES;
  1740. }
  1741. }
  1742. break;
  1743. case SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA:
  1744. {
  1745. if (self.resourceModel.aiPanoramArray.count > 0) {
  1746. self.numberOfImagesLabel.hidden = NO;
  1747. self.numberOfImagesLabel.text = [NSString stringWithFormat:@"已拍摄%ld张", self.resourceModel.aiPanoramArray.count];
  1748. } else {
  1749. self.numberOfImagesLabel.text = @"单击拍摄,长按拼接";
  1750. self.numberOfImagesLabel.hidden = NO;
  1751. }
  1752. }
  1753. break;
  1754. default:
  1755. self.numberOfImagesLabel.hidden = YES;
  1756. break;
  1757. }
  1758. }
  1759. #pragma mark 相机单拍,和连拍的代理
  1760. - (void)captureOutput:(AVCapturePhotoOutput *)output didFinishProcessingPhoto:(AVCapturePhoto *)photo error:(NSError *)error{
  1761. NSData* imageData = [photo fileDataRepresentation];
  1762. if (imageData == nil){
  1763. NSLog(@"%s", "unable to create image data");
  1764. return;
  1765. }
  1766. NSString *path = [LenzDataManager saveImageWith:imageData mode:self.mode];
  1767. LenzResourceItemModel *itemModel = [[LenzResourceItemModel alloc]init];
  1768. itemModel.path = path;
  1769. itemModel.cameraType = [SDKParameters shared].cameraPositionString;
  1770. itemModel.mode = self.mode;
  1771. UIImage *image = [[UIImage alloc] initWithData:imageData];
  1772. BOOL isRemake = [self.tensorFlow remake:image];
  1773. itemModel.image = image;
  1774. NSDictionary *dict = [self.tensorFlow resultsDictWith:image];
  1775. itemModel.isRemake = isRemake;
  1776. switch (self.mode) {
  1777. case SDK_CAPTURE_MODE_CONTINUOUS:{
  1778. [self.resourceModel.continousArray addObject:itemModel];
  1779. }
  1780. break;
  1781. case SDK_CAPTURE_MODE_SINGLE: {
  1782. [self.resourceModel.singleArray addObject:itemModel];
  1783. }
  1784. break;
  1785. case SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA: {
  1786. [self.resourceModel.aiPanoramArray addObject:itemModel];
  1787. }
  1788. break;
  1789. default:
  1790. break;
  1791. }
  1792. self.resourceModel.lastIndex = self.mode;
  1793. [self updateViewStatus];
  1794. // [self.cachesArray addObject:image];
  1795. //
  1796. // [self.typeArray addObject:@"photo"];
  1797. //
  1798. // [self.totalArray addObject:image];
  1799. //
  1800. // self.capturedImage = image;
  1801. [self.currentOperationNode triggered];
  1802. if(self.mode == SDK_CAPTURE_MODE_SINGLE){
  1803. // self.panGesture.enabled = NO;
  1804. [self stopCaptureSession];
  1805. [self performSegueWithIdentifier:@"preview_single" sender:nil];
  1806. // [self showPreviewView:NO];
  1807. }
  1808. else if(self.mode == SDK_CAPTURE_MODE_CONTINUOUS){
  1809. self.discardPhotoButton.hidden = NO;
  1810. self.savePhotoButton.hidden = NO;
  1811. }
  1812. self.resultImageView.image = image;
  1813. // [self updateNumberLabel];
  1814. }
  1815. - (void)updateViewStatus {
  1816. dispatch_async(dispatch_get_main_queue(), ^{
  1817. UIImage *image = nil;
  1818. switch (self.resourceModel.lastIndex) {
  1819. case SDK_CAPTURE_MODE_CONTINUOUS: {
  1820. if (self.resourceModel.continousArray.count > 0) {
  1821. LenzResourceItemModel *model = self.resourceModel.continousArray.lastObject;
  1822. image = model.image;
  1823. } else {
  1824. if (self.resourceModel.singleArray.count > 0) {
  1825. LenzResourceItemModel *model = self.resourceModel.singleArray.lastObject;
  1826. image = model.image;
  1827. } else if (self.resourceModel.movieArray.count > 0) {
  1828. LenzResourceItemModel *model = self.resourceModel.movieArray.lastObject;
  1829. image = model.image;
  1830. } else if (self.resourceModel.panoramArray.count > 0) {
  1831. LenzResourceItemModel *model = self.resourceModel.panoramArray.lastObject;
  1832. image = model.image;
  1833. } else if (self.resourceModel.aiPanoramArray.count > 0) {
  1834. LenzResourceItemModel *model = self.resourceModel.aiPanoramArray.lastObject;
  1835. image = model.image;
  1836. }
  1837. }
  1838. }
  1839. break;
  1840. case SDK_CAPTURE_MODE_SINGLE:{
  1841. if (self.resourceModel.singleArray.count > 0) {
  1842. LenzResourceItemModel *model = self.resourceModel.singleArray.lastObject;
  1843. image = model.image;
  1844. } else {
  1845. if (self.resourceModel.continousArray.count > 0) {
  1846. LenzResourceItemModel *model = self.resourceModel.continousArray.lastObject;
  1847. image = model.image;
  1848. } else if (self.resourceModel.movieArray.count > 0) {
  1849. LenzResourceItemModel *model = self.resourceModel.movieArray.lastObject;
  1850. image = model.image;
  1851. } else if (self.resourceModel.panoramArray.count > 0) {
  1852. LenzResourceItemModel *model = self.resourceModel.panoramArray.lastObject;
  1853. image = model.image;
  1854. } else if (self.resourceModel.aiPanoramArray.count > 0) {
  1855. LenzResourceItemModel *model = self.resourceModel.aiPanoramArray.lastObject;
  1856. image = model.image;
  1857. }
  1858. }
  1859. }
  1860. break;
  1861. case SDK_CAPTURE_MODE_MOVIE:{
  1862. if (self.resourceModel.movieArray.count > 0) {
  1863. LenzResourceItemModel *model = self.resourceModel.movieArray.lastObject;
  1864. image = model.image;
  1865. } else {
  1866. if (self.resourceModel.singleArray.count > 0) {
  1867. LenzResourceItemModel *model = self.resourceModel.singleArray.lastObject;
  1868. image = model.image;
  1869. } else if (self.resourceModel.continousArray.count > 0) {
  1870. LenzResourceItemModel *model = self.resourceModel.continousArray.lastObject;
  1871. image = model.image;
  1872. } else if (self.resourceModel.panoramArray.count > 0) {
  1873. LenzResourceItemModel *model = self.resourceModel.panoramArray.lastObject;
  1874. image = model.image;
  1875. } else if (self.resourceModel.aiPanoramArray.count > 0) {
  1876. LenzResourceItemModel *model = self.resourceModel.aiPanoramArray.lastObject;
  1877. image = model.image;
  1878. }
  1879. }
  1880. }
  1881. break;
  1882. case SDK_CAPTURE_MODE_PANORAMA:{
  1883. if (self.resourceModel.panoramArray.count > 0) {
  1884. LenzResourceItemModel *model = self.resourceModel.panoramArray.lastObject;
  1885. image = model.image;
  1886. } else {
  1887. if (self.resourceModel.singleArray.count > 0) {
  1888. LenzResourceItemModel *model = self.resourceModel.singleArray.lastObject;
  1889. image = model.image;
  1890. } else if (self.resourceModel.movieArray.count > 0) {
  1891. LenzResourceItemModel *model = self.resourceModel.movieArray.lastObject;
  1892. image = model.image;
  1893. } else if (self.resourceModel.continousArray.count > 0) {
  1894. LenzResourceItemModel *model = self.resourceModel.continousArray.lastObject;
  1895. image = model.image;
  1896. } else if (self.resourceModel.aiPanoramArray.count > 0) {
  1897. LenzResourceItemModel *model = self.resourceModel.aiPanoramArray.lastObject;
  1898. image = model.image;
  1899. }
  1900. }
  1901. }
  1902. break;
  1903. case SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA:{
  1904. if (self.resourceModel.aiPanoramArray.count > 0) {
  1905. LenzResourceItemModel *model = self.resourceModel.aiPanoramArray.lastObject;
  1906. image = model.image;
  1907. } else {
  1908. if (self.resourceModel.singleArray.count > 0) {
  1909. LenzResourceItemModel *model = self.resourceModel.singleArray.lastObject;
  1910. image = model.image;
  1911. } else if (self.resourceModel.movieArray.count > 0) {
  1912. LenzResourceItemModel *model = self.resourceModel.movieArray.lastObject;
  1913. image = model.image;
  1914. } else if (self.resourceModel.panoramArray.count > 0) {
  1915. LenzResourceItemModel *model = self.resourceModel.panoramArray.lastObject;
  1916. image = model.image;
  1917. } else if (self.resourceModel.continousArray.count > 0) {
  1918. LenzResourceItemModel *model = self.resourceModel.continousArray.lastObject;
  1919. image = model.image;
  1920. }
  1921. }
  1922. }
  1923. break;
  1924. default:
  1925. break;
  1926. }
  1927. if (image) {
  1928. self.ablumImageView.image = image;
  1929. self.ablumImageView.hidden = NO;
  1930. self.discardPhotoButton.hidden = NO;
  1931. self.savePhotoButton.hidden = NO;
  1932. self.backButton.hidden = YES;
  1933. } else {
  1934. self.ablumImageView.image = nil;
  1935. self.ablumImageView.hidden = YES;
  1936. self.discardPhotoButton.hidden = YES;
  1937. self.savePhotoButton.hidden = YES;
  1938. self.backButton.hidden = NO;
  1939. }
  1940. [self updateNumberLabel];
  1941. });
  1942. }
  1943. #pragma mark - AVCaptureFileOutputRecordingDelegate
  1944. - (void)captureOutput:(AVCaptureFileOutput *)output didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL fromConnections:(NSArray<AVCaptureConnection *> *)connections error:(NSError *)error{
  1945. //视频录制
  1946. BOOL recordedSuccessfully = YES;
  1947. // A problem occurred: Find out if the recording was successful.
  1948. if(error.code == AVErrorMaximumDurationReached){
  1949. NSLog(@"%@", [error localizedDescription]);
  1950. }
  1951. else if (error.code == AVErrorDiskFull){
  1952. NSLog(@"%@", [error localizedDescription]);
  1953. dispatch_async(dispatch_get_main_queue(), ^{
  1954. [[NSNotificationCenter defaultCenter] postNotificationName:LenzSDKNotificationDiskIsFull object:error];
  1955. });
  1956. }
  1957. else if (error.code == AVErrorSessionWasInterrupted){
  1958. NSLog(@"%@", [error localizedDescription]);
  1959. }
  1960. id value = [[error userInfo] objectForKey:AVErrorRecordingSuccessfullyFinishedKey];
  1961. if (value) {
  1962. recordedSuccessfully = [value boolValue];
  1963. [self.recordTimer invalidate];
  1964. self.recordTimer = nil;
  1965. }
  1966. if(!recordedSuccessfully){
  1967. return;
  1968. }
  1969. OperationNodeMovie *node = nil;
  1970. if ([self.currentOperationNode isKindOfClass:[OperationNodeMovie class]]) {
  1971. node = (OperationNodeMovie *)self.currentOperationNode;
  1972. if (node.isRecording) {
  1973. [self.currentOperationNode takePhotoButtonTouched];
  1974. }
  1975. }
  1976. // NSString *path = [LenzDataManager saveVideoUrl:outputFileURL model:self.mode];
  1977. LenzResourceItemModel *itemModel = [[LenzResourceItemModel alloc]init];
  1978. itemModel.path = outputFileURL.absoluteString;
  1979. itemModel.cameraType = [SDKParameters shared].cameraPositionString;
  1980. itemModel.mode = self.mode;
  1981. itemModel.image = [self videoFrameImageWith:outputFileURL];
  1982. [self.resourceModel.movieArray addObject:itemModel];
  1983. self.resourceModel.lastIndex = self.mode;
  1984. // self.recordedFileUrl = outputFileURL;
  1985. // [self.typeArray addObject:@"movie"];
  1986. [self updateViewStatus];
  1987. [self.timerLabel updateWith:0];
  1988. dispatch_async(dispatch_get_main_queue(), ^{
  1989. [self.currentOperationNode triggered];
  1990. self.thumbnailOritaionByCurrentVideoOrientation = UIImageOrientationUp;
  1991. });
  1992. }
  1993. - (BOOL)encodeFrame:(CMSampleBufferRef) sampleBuffer{
  1994. if (CMSampleBufferDataIsReady(sampleBuffer)) {
  1995. if (self.videoWriter.status == AVAssetWriterStatusUnknown) {
  1996. CMTime startTime = CMSampleBufferGetPresentationTimeStamp(sampleBuffer);
  1997. [self.videoWriter startWriting];
  1998. [self.videoWriter startSessionAtSourceTime:startTime];
  1999. }
  2000. if (self.videoWriter.status == AVAssetWriterStatusFailed) {
  2001. NSLog(@"writer error %@", self.videoWriter.error.localizedDescription);
  2002. return NO;
  2003. }
  2004. if (self.videoWriterInput.readyForMoreMediaData) {
  2005. [self.videoWriterInput appendSampleBuffer:sampleBuffer];
  2006. return YES;
  2007. }
  2008. }
  2009. return NO;
  2010. }
  2011. #pragma mark - AVCaptureAudioDataOutputSampleBufferDelegate
  2012. #pragma mark - UIViewControllerTransitioningDelegate
  2013. - (id<UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source{
  2014. return [[CustomModalViewTransitionPresent alloc] init];
  2015. }
  2016. - (id<UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed{
  2017. return [[CustomModalViewTransitionDismiss alloc] init];
  2018. }
  2019. #pragma mark - PhotoListViewControllerDelegate
  2020. //删除视频
  2021. - (void)deleteMovie: (MovieListCellModel*)model completion: (DeleteImageCompletionCallBackType)completion{
  2022. for (int i = 0; i < self.totalArray.count; i ++) {
  2023. UIImage *image = self.totalArray[i];
  2024. if (image == (UIImage *)model.movieModel.thumbnail) {
  2025. [self.totalArray removeObjectAtIndex:i];
  2026. [self.typeArray removeObjectAtIndex:i];
  2027. break;;
  2028. }
  2029. }
  2030. // id<OperationNodeProtocol> curr = self.currentOperationNode;
  2031. id<OperationNodeProtocol> curr = (__kindof id<OperationNodeProtocol>)self.operationNodes[@(2)];
  2032. if([curr respondsToSelector:@selector(deleteCacheForKey:completion:)]){
  2033. [curr deleteCacheForKey:model.movieModel.fileUrl.path completion:completion];
  2034. }
  2035. }
  2036. //连拍删除
  2037. - (void)deleteImage:(UIImage *)image completion:(nonnull DeleteImageCompletionCallBackType)completion{
  2038. // id<OperationNodeProtocol> curr = self.currentOperationNode;
  2039. for (int i = 0; i < self.totalArray.count; i ++) {
  2040. UIImage *img = self.totalArray[i];
  2041. if (img == image) {
  2042. [self.totalArray removeObjectAtIndex:i];
  2043. [self.typeArray removeObjectAtIndex:i];
  2044. break;;
  2045. }
  2046. }
  2047. id<OperationNodeProtocol> curr = (__kindof id<OperationNodeProtocol>)self.operationNodes[@(0)];
  2048. if([curr respondsToSelector:@selector(deleteCacheForImage:completion:)]){
  2049. [curr deleteCacheForImage:image completion:completion];
  2050. }
  2051. }
  2052. - (void)deleteImageWithName:(NSString *)name completion:(nonnull DeleteImageCompletionCallBackType)completion{
  2053. id<OperationNodeProtocol> curr = self.currentOperationNode;
  2054. if([curr respondsToSelector:@selector(deleteCacheForKey:completion:)]){
  2055. [curr deleteCacheForKey:name completion:completion];
  2056. }
  2057. }
  2058. #pragma mark - AVCaptureVideoDataOutputSampleBufferDelegate
  2059. - (void)captureOutput:(AVCaptureOutput *)output didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection {
  2060. @autoreleasepool {
  2061. if (connection == [self.videoDataOutput connectionWithMediaType:AVMediaTypeVideo]) {
  2062. NSLog(@"11111");
  2063. [self.stitchkLock lock];
  2064. // dispatch_semaphore_wait(self.videoStitchSemaphore, DISPATCH_TIME_FOREVER);
  2065. OperationNodeVideoBase *base = nil;
  2066. if ([self.currentOperationNode isKindOfClass:[OperationNodeVideoBase class]]) {
  2067. base = (OperationNodeVideoBase *)self.currentOperationNode;
  2068. }
  2069. NSLog(@"2222");
  2070. if (self.isVideoStitchStopedWhenRecording &&
  2071. (self.stitchResult != LenVideoStitchResultFail && self.stitchResult != LenVideoStitchResultStitchFail)) {
  2072. [self updateViewStatusWhenStitchSave:YES];
  2073. self.isStitchBigImage = YES;
  2074. }
  2075. [LenStitcher videoStitchWith:sampleBuffer
  2076. dirction:(LenVideoStitchDirction)self.panoramOrientationGuideView.selectedItemIndex
  2077. isStop:self.isVideoStitchStopedWhenRecording
  2078. complete:^(LenVideoStitchResult result, LenVideoStitchNeedSave needSave) {
  2079. self.stitchResult = result;
  2080. NSLog(@"333");
  2081. self.isVideoStitchStopedWhenRecording = NO;
  2082. UIImage *image = [LenStitcher getCurrentPanoramaShowImage];
  2083. LenzResourceItemModel *model = nil;
  2084. if (self.mode == SDK_CAPTURE_MODE_PANORAMA) {
  2085. model = self.resourceModel.panoramArray.lastObject;
  2086. } else if (self.mode == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA) {
  2087. model = self.resourceModel.aiPanoramArray.lastObject;
  2088. }
  2089. if (!image || !model) {
  2090. [self.stitchkLock unlock];
  2091. return;
  2092. }
  2093. if (result == LenVideoStitchResultSuccess) {
  2094. dispatch_async(dispatch_get_main_queue(), ^{
  2095. if (self.isStitchBigImage) {
  2096. //保存大图拼接路径
  2097. model.cameraType = [SDKParameters shared].cameraPositionString;
  2098. model.mode = self.mode;
  2099. if ([LenStitcher getCurrentPanoramaShow]) {
  2100. model.image = image;
  2101. model.path = [LenStitcher getCurrentPanoramaShow];
  2102. }
  2103. [self updateViewStatusWhenStitchSave:NO];
  2104. self.isStitchBigImage = NO;
  2105. [self.panoramaGuideView clearImage];
  2106. [self updateViewStatus];
  2107. [self.panoramaGuideView showImageWith:nil dir:self.panoramOrientationGuideView.selectedItemIndex];
  2108. } else {
  2109. if (base.isRecording) {
  2110. if (needSave && [SDKParameters shared].keyFrame.boolValue) {
  2111. NSString *path = [LenzDataManager saveImageWith:UIImageJPEGRepresentation(image, .6) mode:self.mode];
  2112. // itemModel.path = path;
  2113. if (path) {
  2114. [model.keyFrame addObject:path];
  2115. }
  2116. }
  2117. if (self.panoramOrientationGuideView.selectedItemIndex != PanoramaOrientationViewAny) {
  2118. [self.panoramaGuideView showImageWith:image dir:self.panoramOrientationGuideView.selectedItemIndex];
  2119. } else {
  2120. self.ablumImageView.hidden = NO;
  2121. self.ablumImageView.image = image;
  2122. }
  2123. }
  2124. }
  2125. self.resourceModel.lastIndex = self.mode;
  2126. });
  2127. } else {
  2128. if (!base.isRecording) {
  2129. // [self removeLastStich];
  2130. //停止拼接,移除保存中 非success数据
  2131. if (self.mode == SDK_CAPTURE_MODE_PANORAMA) {
  2132. NSMutableArray *array = [NSMutableArray array];
  2133. [self.resourceModel.panoramArray enumerateObjectsUsingBlock:^(LenzResourceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  2134. if (obj.path.length) {
  2135. [array addObject:obj];
  2136. }
  2137. }];
  2138. self.resourceModel.panoramArray = array;
  2139. } else if (self.mode == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA) {
  2140. NSMutableArray *array = [NSMutableArray array];
  2141. [self.resourceModel.aiPanoramArray enumerateObjectsUsingBlock:^(LenzResourceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  2142. if (obj.path.length) {
  2143. [array addObject:obj];
  2144. }
  2145. }];
  2146. self.resourceModel.aiPanoramArray = array;
  2147. }
  2148. [self updateViewStatus];
  2149. [self.stitchkLock unlock];
  2150. return;
  2151. }
  2152. if (result == LenVideoStitchResultFail || result == LenVideoStitchResultStitchFail) {
  2153. if (result == LenVideoStitchResultFail) {
  2154. [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"拼接失败,流程结束"];
  2155. } else {
  2156. [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"拼接大图失败,流程结束"];
  2157. }
  2158. self.isVideoStitchStopedWhenRecording = NO;
  2159. // base.isRecording = NO;
  2160. dispatch_async(dispatch_get_main_queue(), ^{
  2161. [base takePhotoButtonTouched];
  2162. [self stopMotion];
  2163. // [self takePhotoButtonTouchUpInside:[NSObject new]];
  2164. [self removeLastStich];
  2165. [self updateViewStatusWhenStitchFail];
  2166. [self.panoramaGuideView clearImage];
  2167. [self updateViewStatus];
  2168. [self.panoramaGuideView showImageWith:nil dir:self.panoramOrientationGuideView.selectedItemIndex];
  2169. });
  2170. [SVProgressHUD dismissWithDelay:3 completion:^{
  2171. }];
  2172. } else if(result == LenVideoStitchResultSlowMore) {
  2173. [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"特征点变少,放慢速度"];
  2174. } else if (result == LenVideoStitchResultSlow) {
  2175. [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"特征点极少,即将失败"];
  2176. } else {
  2177. [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"请勿往反方向移动"];
  2178. }
  2179. }
  2180. [self.stitchkLock unlock];
  2181. // dispatch_semaphore_signal(self.videoStitchSemaphore);
  2182. }];
  2183. }
  2184. }
  2185. }
  2186. - (void)removeLastStich {
  2187. if (self.mode == SDK_CAPTURE_MODE_PANORAMA) {
  2188. if (self.resourceModel.panoramArray.count > 0) {
  2189. [self.resourceModel.panoramArray removeLastObject];
  2190. }
  2191. } else if (self.mode == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA) {
  2192. if (self.resourceModel.aiPanoramArray.count > 0) {
  2193. [self.resourceModel.aiPanoramArray removeLastObject];
  2194. }
  2195. }
  2196. }
  2197. //*
  2198. #pragma mark - Navigation
  2199. // In a storyboard-based application, you will often want to do a little preparation before navigation
  2200. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
  2201. // Get the new view controller using [segue destinationViewController].
  2202. // Pass the selected object to the new view controller.
  2203. if([segue.identifier isEqualToString:@"show-photos"]){
  2204. if([segue.destinationViewController isKindOfClass:[PhotoListViewController class]]){
  2205. PhotoListViewController* dst = segue.destinationViewController;
  2206. OperationNodeMultiple* node = self.currentOperationNode;
  2207. dst.transitioningDelegate = self;
  2208. [dst setImagesInMemory:node.cachesInMemory andImageNamesOnDisk:node.cachesOnDisk];
  2209. dst.delegate = self;
  2210. }
  2211. }
  2212. else if([segue.identifier isEqualToString:@"show-movies"]){
  2213. if([segue.destinationViewController isKindOfClass:[MovieListViewController class]]){
  2214. MovieListViewController* dst = segue.destinationViewController;
  2215. OperationNodeMovie* node = self.currentOperationNode;
  2216. dst.transitioningDelegate = self;
  2217. dst.movieModels = node.cachedMovies;
  2218. dst.delegate = self;
  2219. }
  2220. }
  2221. else if([segue.identifier isEqualToString:@"preview_single"]){
  2222. PreviewSingleViewController* dst = segue.destinationViewController;
  2223. dst.singleModeNode = self.currentOperationNode;
  2224. if (self.resourceModel.singleArray.count > 0) {
  2225. LenzResourceItemModel *model = self.resourceModel.singleArray.firstObject;
  2226. dst.image = model.image;
  2227. }
  2228. // dst.image = self.capturedImage;
  2229. }else if ([segue.identifier isEqualToString:@"show-photoalbum"]){
  2230. PhotoAlbumListViewController *dst = segue.destinationViewController;
  2231. dst.typeArray = self.typeArray;
  2232. //图片数据
  2233. NSString *typeStr = self.typeArray.lastObject;
  2234. // if ([typeStr isEqualToString:@"photo"]) {
  2235. OperationNodeMultiple* node = (__kindof id<OperationNodeProtocol>)self.operationNodes[@(0)];
  2236. // OperationNodeMultiple* node = self.currentOperationNode;
  2237. dst.node = node;
  2238. dst.photoListVC.transitioningDelegate = self;
  2239. [dst.photoListVC setImagesInMemory:node.cachesInMemory andImageNamesOnDisk:node.cachesOnDisk];
  2240. dst.photoListVC.delegate = self;
  2241. // }else if ([typeStr isEqualToString:@"movie"]) {
  2242. OperationNodeMovie* movieNode = (__kindof id<OperationNodeProtocol>)self.operationNodes[@(2)];
  2243. dst.movieListVC.transitioningDelegate = self;
  2244. dst.movieListVC.movieModels = movieNode.cachedMovies;
  2245. dst.movieListVC.delegate = self;
  2246. // }
  2247. //视频数据
  2248. }
  2249. }
  2250. //*/
  2251. - (void)clearSingleData {
  2252. [self.resourceModel.singleArray removeAllObjects];
  2253. [self updateViewStatus];
  2254. }
  2255. - (UIImage *)videoFrameImageWith:(NSURL *)url {
  2256. AVURLAsset* asset = [[AVURLAsset alloc] initWithURL:url options:nil];
  2257. AVAssetImageGenerator *generateImg = [[AVAssetImageGenerator alloc] initWithAsset:asset];
  2258. NSError *err = NULL;
  2259. CMTime time = CMTimeMake(1, 65);
  2260. CGImageRef refImg = [generateImg copyCGImageAtTime:time actualTime:NULL error:&err];
  2261. UIImage *frameImage= [[UIImage alloc] initWithCGImage:refImg scale:1.0 orientation:self.thumbnailOritaionByCurrentVideoOrientation];
  2262. return frameImage;
  2263. }
  2264. @end