PCSBaseViewController.m 109 KB

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