PCSBaseViewController.m 107 KB

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