PCSBaseViewController.m 108 KB

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