PCSBaseViewController.m 109 KB

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