PCSBaseViewController.m 135 KB

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