PCSBaseViewController.m 118 KB

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