PCSBaseViewController.m 109 KB

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