PCSBaseViewController.m 109 KB

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