PCSBaseViewController.m 109 KB

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