PCSBaseViewController.m 109 KB

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